Debian Codegraph @

converter/other/pnmtops.c

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /* pnmtops.c - read a PNM image and produce a PostScript program.
2
3 Copyright information is at end of file.
4
5 We produce two main kinds of Postscript program:
6
7 1) Use built in Postscript filters /ASCII85Decode, /ASCIIHexDecode,
8 /RunLengthDecode, and /FlateDecode;
9
10 We use methods we learned from Dirk Krause's program Bmeps.
11 Previous versions used raster encoding code based on Bmeps
12 code. This program does not use any code from Bmeps.
13
14 2) Use our own filters and redefine /readstring . This is aboriginal
15 Netpbm code, from when Postscript was young. The filters are
16 nearly identical to /ASCIIHexDecode and /RunLengthDecode. We
17 use the same raster encoding code with slight modifications.
18
19 (2) is the default. (1) gives more options, but relies on features
20 introduced in Postscript Level 2, which appeared in 1991. Postcript
21 devices made before 1991 can't handle them. The user selects (1)
22 with the -psfilter option.
23
24 We also do a few other bold new things only when the user specifies
25 -psfilter, because we're not sure they work for everyone.
26
27 (I actually don't know Postscript, so some of this description, not to
28 mention the code, may be totally bogus.)
29
30 NOTE: it is possible to put transparency information in an
31 encapsulated Postscript program. Bmeps does this. We don't. It
32 might be hard to do, because in Postscript, the transparency information
33 goes in separate from the rest of the raster.
34 */
35
36 #define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */
37 #define _BSD_SOURCE /* Make sure string.h contains strdup() */
38 #define _XOPEN_SOURCE 500 /* Make sure strdup() is in string.h */
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <sys/types.h>
42 #include <sys/wait.h>
43 #include <unistd.h>
44 #include <assert.h>
45 #include <string.h>
46 #include <errno.h>
47 #include <signal.h>
48 #ifndef NOFLATE
49 #include <zlib.h>
50 #endif
51
52 #include "pm_c_util.h"
53 #include "pam.h"
54 #include "mallocvar.h"
55 #include "shhopt.h"
56 #include "nstring.h"
57 #include "runlength.h"
58
59
60
61 unsigned int const psScaleFactor = 72;
62
63
64
65 static void
66 setSignals() {
67 /*----------------------------------------------------------------------------
68 Set up the process-global signal-related state.
69
70 Note that we can't rely on defaults, because much of this is inherited
71 from the process that forked and exec'ed this program.
72 -----------------------------------------------------------------------------*/
73 /* See waitForChildren() for why we do this to SIGCHLD */
74
75 struct sigaction sigchldAction;
76 int rc;
77 sigset_t emptySet;
78
79 sigemptyset(&emptySet);
80
81 sigchldAction.sa_handler = SIG_DFL;
82 sigchldAction.sa_mask = emptySet;
83 sigchldAction.sa_flags = SA_NOCLDSTOP;
84
85 rc = sigaction(SIGCHLD, &sigchldAction, NULL);
86
87 if (rc != 0)
88 pm_error("sigaction() to set up signal environment failed, "
89 "errno = %d (%s)", errno, strerror(errno));
90 }
91
92
93
94 struct CmdlineInfo {
95 /* All the information the user supplied in the command line,
96 in a form easy for the program to use.
97 */
98 const char * inputFileName; /* Filespecs of input file */
99 float scale;
100 unsigned int dpiX; /* horiz component of DPI option */
101 unsigned int dpiY; /* vert component of DPI option */
102 unsigned int width; /* in 1/72 inch */
103 unsigned int height; /* in 1/72 inch */
104 unsigned int mustturn;
105 bool canturn;
106 unsigned int rle;
107 bool center;
108 unsigned int imagewidth; /* in 1/72 inch; zero if unspec */
109 unsigned int imageheight; /* in 1/72 inch; zero if unspec */
110 unsigned int equalpixels;
111 unsigned int bitspersampleSpec;
112 unsigned int bitspersample;
113 unsigned int setpage;
114 bool showpage;
115 unsigned int level;
116 unsigned int levelSpec;
117 unsigned int psfilter;
118 unsigned int flate;
119 unsigned int ascii85;
120 unsigned int dict;
121 unsigned int vmreclaim;
122 unsigned int verbose;
123 unsigned int debug;
124 };
125
126 static bool debug;
127 static bool verbose;
128
129
130
131 static void
132 parseDpi(const char * const dpiOpt,
133 unsigned int * const dpiXP,
134 unsigned int * const dpiYP) {
135
136 char *dpistr2;
137 unsigned long int dpiX, dpiY;
138
139 dpiX = strtol(dpiOpt, &dpistr2, 10);
140 if (dpistr2 == dpiOpt)
141 pm_error("Invalid value for -dpi: '%s'. Must be either number "
142 "or NxN ", dpiOpt);
143 else if (dpiX > INT_MAX)
144 pm_error("Invalid value for -dpi: '%s'. "
145 "Value too large for computation", dpiOpt);
146 else {
147 if (*dpistr2 == '\0') {
148 *dpiXP = dpiX;
149 *dpiYP = dpiX;
150 } else if (*dpistr2 == 'x') {
151 char * dpistr3;
152
153 dpistr2++; /* Move past 'x' */
154 dpiY = strtol(dpistr2, &dpistr3, 10);
155 if (dpiY > INT_MAX)
156 pm_error("Invalid value for -dpi: '%s'. "
157 "Value too large for computation", dpiOpt);
158 else if (dpistr3 != dpistr2 && *dpistr3 == '\0') {
159 *dpiXP = dpiX;
160 *dpiYP = dpiY;
161 } else {
162 pm_error("Invalid value for -dpi: '%s'. Must be either "
163 "number or NxN", dpiOpt);
164 }
165 }
166 }
167 }
168
169
170
171 static void
172 validateBps_1_2_4_8_12(unsigned int const bitsPerSample) {
173
174 switch (bitsPerSample) {
175 case 1:
176 case 2:
177 case 4:
178 case 8:
179 case 12:
180 break;
181 default:
182 pm_error("Invalid -bitspersample value: %u. Must be "
183 "1, 2, 4, 8, or 12", bitsPerSample);
184 }
185 }
186
187
188
189 static void
190 validateCompDimension(unsigned int const value,
191 unsigned int const scaleFactor,
192 const char * const vname) {
193 /*----------------------------------------------------------------------------
194 Validate that the image dimension (width or height) 'value' isn't so big
195 that in this program's calculations, involving scale factor 'scaleFactor',
196 it would cause a register overflow. If it is, abort the program and refer
197 to the offending dimension as 'vname' in the error message.
198
199 Note that this early validation approach (calling this function) means
200 the actual computations don't have to be complicated with arithmetic
201 overflow checks, so they're easier to read.
202 -----------------------------------------------------------------------------*/
203 if (value > 0) {
204 unsigned int const maxWidthHeight = INT_MAX - 2;
205 unsigned int const maxScaleFactor = maxWidthHeight / value;
206
207 if (scaleFactor > maxScaleFactor)
208 pm_error("%s is too large for compuations: %u", vname, value);
209 }
210 }
211
212
213
214 static void
215 parseCommandLine(int argc, const char ** argv,
216 struct CmdlineInfo * const cmdlineP) {
217
218 unsigned int imagewidthSpec, imageheightSpec;
219 float imagewidth, imageheight;
220 unsigned int center, nocenter;
221 unsigned int nosetpage;
222 float width, height;
223 unsigned int noturn;
224 unsigned int showpage, noshowpage;
225 const char * dpiOpt;
226 unsigned int dpiSpec, scaleSpec, widthSpec, heightSpec;
227
228 optStruct3 opt;
229 unsigned int option_def_index = 0;
230 optEntry * option_def;
231
232 MALLOCARRAY_NOFAIL(option_def, 100);
233
234 OPTENT3(0, "scale", OPT_FLOAT, &cmdlineP->scale, &scaleSpec, 0);
235 OPTENT3(0, "dpi", OPT_STRING, &dpiOpt, &dpiSpec, 0);
236 OPTENT3(0, "width", OPT_FLOAT, &width, &widthSpec, 0);
237 OPTENT3(0, "height", OPT_FLOAT, &height, &heightSpec, 0);
238 OPTENT3(0, "psfilter", OPT_FLAG, NULL, &cmdlineP->psfilter, 0);
239 OPTENT3(0, "turn", OPT_FLAG, NULL, &cmdlineP->mustturn, 0);
240 OPTENT3(0, "noturn", OPT_FLAG, NULL, &noturn, 0);
241 OPTENT3(0, "rle", OPT_FLAG, NULL, &cmdlineP->rle, 0);
242 OPTENT3(0, "runlength", OPT_FLAG, NULL, &cmdlineP->rle, 0);
243 OPTENT3(0, "ascii85", OPT_FLAG, NULL, &cmdlineP->ascii85, 0);
244 OPTENT3(0, "center", OPT_FLAG, NULL, &center, 0);
245 OPTENT3(0, "nocenter", OPT_FLAG, NULL, &nocenter, 0);
246 OPTENT3(0, "equalpixels", OPT_FLAG, NULL, &cmdlineP->equalpixels, 0);
247 OPTENT3(0, "imagewidth", OPT_FLOAT, &imagewidth, &imagewidthSpec, 0);
248 OPTENT3(0, "imageheight", OPT_FLOAT, &imageheight, &imageheightSpec, 0);
249 OPTENT3(0, "bitspersample", OPT_UINT, &cmdlineP->bitspersample,
250 &cmdlineP->bitspersampleSpec, 0);
251 OPTENT3(0, "nosetpage", OPT_FLAG, NULL, &nosetpage, 0);
252 OPTENT3(0, "setpage", OPT_FLAG, NULL, &cmdlineP->setpage, 0);
253 OPTENT3(0, "noshowpage", OPT_FLAG, NULL, &noshowpage, 0);
254 OPTENT3(0, "flate", OPT_FLAG, NULL, &cmdlineP->flate, 0);
255 OPTENT3(0, "dict", OPT_FLAG, NULL, &cmdlineP->dict, 0);
256 OPTENT3(0, "vmreclaim", OPT_FLAG, NULL, &cmdlineP->vmreclaim, 0);
257 OPTENT3(0, "showpage", OPT_FLAG, NULL, &showpage, 0);
258 OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0);
259 OPTENT3(0, "debug", OPT_FLAG, NULL, &cmdlineP->debug, 0);
260 OPTENT3(0, "level", OPT_UINT, &cmdlineP->level,
261 &cmdlineP->levelSpec, 0);
262
263 opt.opt_table = option_def;
264 opt.short_allowed = FALSE;
265 opt.allowNegNum = FALSE;
266
267 pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
268
269 if (cmdlineP->mustturn && noturn)
270 pm_error("You cannot specify both -turn and -noturn");
271 if (center && nocenter)
272 pm_error("You cannot specify both -center and -nocenter");
273 if (showpage && noshowpage)
274 pm_error("You cannot specify both -showpage and -noshowpage");
275 if (cmdlineP->setpage && nosetpage)
276 pm_error("You cannot specify both -setpage and -nosetpage");
277
278 if (!scaleSpec)
279 cmdlineP->scale = 1.0;
280
281 if (!widthSpec)
282 width = 8.5;
283
284 if (!heightSpec)
285 height = 11.0;
286
287 if (dpiSpec)
288 parseDpi(dpiOpt, &cmdlineP->dpiX, &cmdlineP->dpiY);
289 else {
290 cmdlineP->dpiX = 300;
291 cmdlineP->dpiY = 300;
292 }
293
294 cmdlineP->center = !nocenter;
295 cmdlineP->canturn = !noturn;
296 cmdlineP->showpage = !noshowpage;
297
298 validateCompDimension(width, psScaleFactor, "-width value");
299 validateCompDimension(height, psScaleFactor, "-height value");
300
301 cmdlineP->width = width * psScaleFactor;
302 cmdlineP->height = height * psScaleFactor;
303
304 if (imagewidthSpec) {
305 validateCompDimension(imagewidth, psScaleFactor, "-imagewidth value");
306 cmdlineP->imagewidth = imagewidth * psScaleFactor;
307 }
308 else
309 cmdlineP->imagewidth = 0;
310 if (imageheightSpec) {
311 validateCompDimension(imagewidth, psScaleFactor, "-imageheight value");
312 cmdlineP->imageheight = imageheight * psScaleFactor;
313 }
314 else
315 cmdlineP->imageheight = 0;
316
317 if (!cmdlineP->psfilter &&
318 (cmdlineP->flate || cmdlineP->ascii85))
319 pm_error("You must specify -psfilter in order to specify "
320 "-flate or -ascii85");
321
322 if (cmdlineP->bitspersampleSpec)
323 validateBps_1_2_4_8_12(cmdlineP->bitspersample);
324
325 if (argc-1 == 0)
326 cmdlineP->inputFileName = "-";
327 else if (argc-1 != 1)
328 pm_error("Program takes zero or one argument (filename). You "
329 "specified %d", argc-1);
330 else
331 cmdlineP->inputFileName = argv[1];
332
333 free(option_def);
334 }
335
336
337
338 static bool
339 progIsFlateCapable(void) {
340
341 return
342 #ifdef NOFLATE
343 false
344 #else
345 true
346 #endif
347 ;
348 }
349
350
351
352 static const char *
353 basebasename(const char * const filespec) {
354 /*----------------------------------------------------------------------------
355 Return filename up to first period
356 -----------------------------------------------------------------------------*/
357 char const dirsep = '/';
358 const char * const lastSlashPos = strrchr(filespec, dirsep);
359
360 char * name;
361 const char * filename;
362
363 if (lastSlashPos)
364 filename = lastSlashPos + 1;
365 else
366 filename = filespec;
367
368 name = strdup(filename);
369 if (name != NULL) {
370 char * const dotPosition = strchr(name, '.');
371
372 if (dotPosition)
373 *dotPosition = '\0';
374 }
375 return name;
376 }
377
378
379
380 static void
381 writeFile(const unsigned char * const buffer,
382 size_t const writeCt,
383 const char * const name,
384 FILE * const ofP) {
385
386 size_t writtenCt;
387
388 writtenCt = fwrite(buffer, 1, writeCt, ofP);
389
390 if (writtenCt != writeCt)
391 pm_error("Error writing to %s output file", name);
392 }
393
394
395
396 static void
397 writeFileChar(const char * const buffer,
398 size_t const writeCt,
399 const char * const name,
400 FILE * const ofP) {
401
402 writeFile((const unsigned char *)buffer, writeCt, name, ofP);
403 }
404
405
406
407 #define MAX_FILTER_CT 10
408 /* The maximum number of filters this code is capable of applying */
409
410
411
412 static void
413 initPidList(pid_t * const pidList) {
414
415 pidList[0] = (pid_t)0; /* end of list marker */
416 }
417
418
419
420 static void
421 addToPidList(pid_t * const pidList,
422 pid_t const newPid) {
423
424 unsigned int i;
425
426 for (i = 0; i < MAX_FILTER_CT && pidList[i]; ++i);
427
428 assert(i < MAX_FILTER_CT);
429
430 pidList[i] = newPid;
431 pidList[i+1] = (pid_t)0; /* end of list marker */
432 }
433
434
435
436 /*===========================================================================
437 The output encoder
438 ===========================================================================*/
439
440 enum OutputType {AsciiHex, Ascii85};
441
442 typedef struct {
443 enum OutputType outputType;
444 bool compressRle;
445 bool compressFlate;
446 unsigned int runlengthRefresh;
447 } OutputEncoder;
448
449
450
451 static unsigned int
452 bytesPerRow (unsigned int const cols,
453 unsigned int const bitsPerSample) {
454 /*----------------------------------------------------------------------------
455 Size of row buffer, padded up to byte boundary, given that the image
456 has 'cols' samples per row, 'bitsPerSample' bits per sample.
457 -----------------------------------------------------------------------------*/
458 unsigned int retval;
459
460 assert(bitsPerSample==1 || bitsPerSample==2 || bitsPerSample==4 ||
461 bitsPerSample==8 || bitsPerSample==12);
462
463 switch (bitsPerSample) {
464 case 1:
465 case 2:
466 case 4:
467 retval = cols / (8/bitsPerSample)
468 + (cols % (8/bitsPerSample) > 0 ? 1 : 0);
469 /* A more straightforward calculation would be
470 (cols * bitsPerSample + 7) / 8 ,
471 but this overflows when icols is large.
472 */
473 break;
474 case 8:
475 retval = cols;
476 break;
477 case 12:
478 retval = cols + (cols+1)/2;
479 break;
480 }
481
482 return retval;
483 }
484
485
486
487 static void
488 initOutputEncoder(OutputEncoder * const oeP,
489 unsigned int const icols,
490 unsigned int const bitsPerSample,
491 bool const rle,
492 bool const flate,
493 bool const ascii85,
494 bool const psFilter) {
495
496 oeP->outputType = ascii85 ? Ascii85 : AsciiHex;
497
498 if (rle) {
499 oeP->compressRle = true;
500 oeP->runlengthRefresh =
501 psFilter ? 1024*1024*16 : bytesPerRow(icols, bitsPerSample);
502 } else
503 oeP->compressRle = false;
504
505 if (flate) {
506 assert(psFilter);
507 oeP->compressFlate = true;
508 } else
509 oeP->compressFlate = false;
510
511 if (ascii85) {
512 assert(psFilter);
513 oeP->outputType = Ascii85;
514 } else
515 oeP->outputType = AsciiHex;
516 }
517
518
519
520 typedef void FilterFn(FILE * const ifP,
521 FILE * const ofP,
522 OutputEncoder * const oeP);
523 /* This is a function that can be run in a separate process to do
524 arbitrary modifications of the raster data stream.
525 */
526
527
528
529 #ifndef NOFLATE
530 static void
531 initZlib(z_stream * const strmP) {
532
533 int const level = 9; /* maximum compression. see zlib.h */
534
535 int ret;
536
537 /* allocate deflate state */
538 strmP->zalloc = Z_NULL;
539 strmP->zfree = Z_NULL;
540 strmP->opaque = Z_NULL;
541
542 ret = deflateInit(strmP, level);
543 if (ret != Z_OK)
544 pm_error("Failed to initialize zlib.");
545 }
546 #endif
547
548
549
550 static FilterFn flateFilter;
551
552 static void
553 flateFilter(FILE * const ifP,
554 FILE * const ofP,
555 OutputEncoder * const oeP) {
556
557 #ifndef NOFLATE
558
559 /* This code is based on def() in zpipe.c. zpipe is an example program
560 which comes with the zlib source package. zpipe.c is public domain and
561 is available from the Zlib website: http://www.zlib.net/
562
563 See zlib.h for details on zlib parameters Z_NULL, Z_OK, etc.
564 */
565 unsigned int const chunkSz = 128*1024;
566 /* 128K recommended in zpipe.c. 4096 is not efficient but works. */
567
568 int flush;
569 z_stream strm;
570 unsigned char * in;
571 unsigned char * out;
572
573 in = pm_allocrow(chunkSz, 1);
574 out = pm_allocrow(chunkSz, 1);
575
576 initZlib(&strm);
577
578 /* compress until end of file */
579 do {
580 strm.avail_in = fread(in, 1, chunkSz, ifP);
581 if (ferror(ifP)) {
582 deflateEnd(&strm);
583 pm_error("Error reading from internal pipe during "
584 "flate compression.");
585 }
586 flush = feof(ifP) ? Z_FINISH : Z_NO_FLUSH;
587 strm.next_in = in;
588
589 /* run deflate() on input until output buffer not full, finish
590 compression if we have reached end of input.
591 */
592 do {
593 unsigned int have;
594
595 strm.avail_out = chunkSz;
596 strm.next_out = out;
597 deflate(&strm, flush);
598 have = chunkSz - strm.avail_out;
599 writeFile(out, have, "flate filter", ofP);
600 } while (strm.avail_out == 0);
601 assert(strm.avail_in == 0); /* all input is used */
602
603 /* done when last data in file processed */
604 } while (flush != Z_FINISH);
605
606 free(in);
607 free(out);
608 deflateEnd(&strm);
609 fclose(ifP);
610 fclose(ofP);
611 #else
612 assert(false); /* filter is never used */
613 #endif
614 }
615
616
617
618 /* Run length encoding
619
620 In this simple run-length encoding scheme, compressed and uncompressed
621 strings follow a single index byte N. N 0-127 means the next N+1
622 bytes are uncompressed; 129-255 means the next byte is to be repeated
623 257-N times.
624
625 In native (non-psfilter) mode, the run length filter must flush at
626 the end of every row. But the entire raster is sent to the run length
627 filter as one continuous stream. The run length filter learns the
628 refresh interval from oeP->runlengthRefresh. In ps-filter mode the
629 run length filter ignores row boundaries and flushes every 4096 bytes.
630 */
631
632 static FilterFn rleFilter;
633
634 static void
635 rleFilter (FILE * const ifP,
636 FILE * const ofP,
637 OutputEncoder * const oeP) {
638
639 unsigned int const inSize = oeP->runlengthRefresh;
640
641 bool eof;
642 unsigned char * inbuf;
643 unsigned char * outbuf;
644 size_t outSize;
645
646 MALLOCARRAY(inbuf, inSize);
647 if (inbuf == NULL)
648 pm_error("Failed to allocate %u bytes of memory for RLE filter",
649 inSize);
650 pm_rlenc_allocoutbuf(&outbuf, inSize, PM_RLE_PACKBITS);
651
652 for (eof = false; !eof; ) {
653 size_t const bytesRead = fread(inbuf, 1, inSize, ifP);
654
655 if (feof(ifP))
656 eof = true;
657 else if (ferror(ifP) || bytesRead == 0)
658 pm_error("Internal read error: RLE compression");
659
660 pm_rlenc_compressbyte(inbuf, outbuf, PM_RLE_PACKBITS,
661 bytesRead, &outSize);
662 writeFile(outbuf, outSize, "rlePutBuffer", ofP);
663 }
664
665 fclose(ifP);
666 fclose(ofP);
667 }
668
669
670
671 static FilterFn asciiHexFilter;
672
673 static void
674 asciiHexFilter(FILE * const ifP,
675 FILE * const ofP,
676 OutputEncoder * const oeP) {
677
678 char const hexits[16] = "0123456789abcdef";
679
680 bool eof;
681 unsigned char inbuff[40], outbuff[81];
682
683 for (eof = false; !eof; ) {
684 size_t readCt;
685
686 readCt = fread(inbuff, 1, 40, ifP);
687
688 if (readCt == 0)
689 eof = true;
690 else {
691 unsigned int i;
692
693 for (i = 0; i < readCt; ++i) {
694 int const item = inbuff[i];
695 outbuff[i*2] = hexits[item >> 4];
696 outbuff[i*2+1] = hexits[item & 15];
697 }
698 outbuff[readCt * 2] = '\n';
699 writeFile(outbuff, readCt * 2 + 1, "asciiHex filter", ofP);
700 }
701 }
702
703 fclose(ifP);
704 fclose(ofP);
705 }
706
707
708
709 static FilterFn ascii85Filter;
710
711 static void
712 ascii85Filter(FILE * const ifP,
713 FILE * const ofP,
714 OutputEncoder * const oeP) {
715
716 bool eof;
717 char outbuff[5];
718 unsigned long int value; /* requires 32 bits */
719 int count;
720 int outcount;
721
722 value = 0; /* initial value */
723 count = 0; /* initial value */
724 outcount = 0; /* initial value */
725
726 for (eof = false; !eof; ) {
727 int c;
728
729 c = fgetc(ifP);
730
731 if (c == EOF)
732 eof = true;
733 else {
734 value = value*256 + c;
735 ++count;
736
737 if (value == 0 && count == 4) {
738 writeFileChar("z", 1, "ASCII 85 filter", ofP);
739 /* Ascii85 encoding z exception */
740 ++outcount;
741 count = 0;
742 } else if (count == 4) {
743 outbuff[4] = value % 85 + 33; value/=85;
744 outbuff[3] = value % 85 + 33; value/=85;
745 outbuff[2] = value % 85 + 33; value/=85;
746 outbuff[1] = value % 85 + 33;
747 outbuff[0] = value / 85 + 33;
748
749 writeFileChar(outbuff, count + 1, "ASCII 85 filter", ofP);
750
751 count = value = 0;
752 outcount += 5;
753 }
754
755 if (outcount > 75) {
756 writeFileChar("\n", 1, "ASCII 85 filter", ofP);
757 outcount = 0;
758 }
759 }
760 }
761
762 if (count > 0) { /* EOF, flush */
763 assert (count < 4);
764
765 value <<= (4 - count) * 8; value/=85;
766 outbuff[3] = value % 85 + 33; value/=85;
767 outbuff[2] = value % 85 + 33; value/=85;
768 outbuff[1] = value % 85 + 33;
769 outbuff[0] = value / 85 + 33;
770 outbuff[count + 1] = '\n';
771
772 writeFileChar(outbuff, count + 2, "ASCII 85 filter", ofP);
773 }
774
775 fclose(ifP);
776 fclose(ofP);
777 }
778
779
780
781 static void
782 makePipe(int * const pipeFdArray) {
783
784 int rc;
785 rc = pm_pipe(pipeFdArray);
786 if (rc == -1)
787 pm_error("pipe() failed, errno = %d (%s)", errno, strerror(errno));
788 }
789
790
791
792 static void
793 closeAllBut(int const saveFd0,
794 int const saveFd1,
795 int const saveFd2) {
796 /*----------------------------------------------------------------------------
797 Close every file descriptor in this process except 'saveFd0',
798 'saveFd1', and 'saveFd2'.
799
800 This is helpful because even if this process doesn't touch other file
801 descriptors, its very existence will keep the files open.
802 -----------------------------------------------------------------------------*/
803
804 /* Unix provides no good way to do this; we just assume file descriptors
805 above 9 are not used in this program; Caller must ensure that is true.
806 */
807 int fd;
808
809 for (fd = 0; fd < 10; ++fd) {
810 if (fd != saveFd0 && fd != saveFd1 && fd != saveFd2)
811 close(fd);
812 }
813 }
814
815
816
817 static void
818 spawnFilter(FILE * const ofP,
819 FilterFn * const filterFn,
820 OutputEncoder * const oeP,
821 FILE ** const feedFilePP,
822 pid_t * const pidP) {
823 /*----------------------------------------------------------------------------
824 Fork a child process to run filter function 'filterFn' and send its
825 output to *ofP.
826
827 Create a pipe for feeding the filter and return as *feedFilePP the
828 stream to which Caller can write to push stuff into the filter.
829
830 *oeP is the parameter to 'filterFn'.
831 -----------------------------------------------------------------------------*/
832 int pipeFd[2];
833 pid_t rc;
834
835 makePipe(pipeFd);
836
837 rc = fork();
838
839 if (rc == (pid_t)-1)
840 pm_error("fork() of filter process failed. errno=%d (%s)",
841 errno, strerror(errno));
842 else if (rc == 0) {
843 /* This is the child process */
844
845 FILE * ifP;
846
847 ifP = fdopen(pipeFd[0], "r");
848
849 if (!ifP)
850 pm_error("filter process failed to make "
851 "file stream (\"FILE\") "
852 "out of the file descriptor which is input to the "
853 "filter. errno=%d (%s)",
854 errno, strerror(errno));
855
856 closeAllBut(fileno(ifP), fileno(ofP), STDERR_FILENO);
857
858 filterFn(ifP, ofP, oeP);
859
860 exit(EXIT_SUCCESS);
861 } else {
862 /* This is the parent process */
863
864 pid_t const childPid = rc;
865
866 close(pipeFd[0]);
867
868 *feedFilePP = fdopen(pipeFd[1], "w");
869
870 *pidP = childPid;
871 }
872 }
873
874
875
876 static void
877 addFilter(const char * const description,
878 FilterFn * const filter,
879 OutputEncoder * const oeP,
880 FILE ** const feedFilePP,
881 pid_t * const pidList) {
882 /*----------------------------------------------------------------------------
883 Add a filter to the front of the chain.
884
885 Spawn a process to do the filtering, by running function 'filter'.
886
887 *feedFilePP is the present head of the chain. We make the new filter
888 process write its output to that and get its input from a new pipe.
889 We update *feedFilePP to the sending end of the new pipe.
890
891 Add to the list pidList[] the PID of the process we spawn.
892 -----------------------------------------------------------------------------*/
893 FILE * const oldFeedFileP = *feedFilePP;
894
895 FILE * newFeedFileP;
896 pid_t pid;
897
898 spawnFilter(oldFeedFileP, filter, oeP, &newFeedFileP, &pid);
899
900 if (verbose)
901 pm_message("%s filter spawned: pid %u",
902 description, (unsigned)pid);
903
904 if (debug) {
905 int const outFd = fileno(oldFeedFileP);
906 int const supplyFd = fileno(newFeedFileP);
907 pm_message("PID %u writes to FD %u, its supplier writes to FD %u",
908 (unsigned)pid, outFd, supplyFd);
909 }
910 fclose(oldFeedFileP); /* Child keeps this open now */
911
912 addToPidList(pidList, pid);
913
914 *feedFilePP = newFeedFileP;
915 }
916
917
918
919 static void
920 spawnFilters(FILE * const ofP,
921 OutputEncoder * const oeP,
922 FILE ** const feedFilePP,
923 pid_t * const pidList) {
924 /*----------------------------------------------------------------------------
925 Get all the child processes for the filters running and connected.
926 Return at *feedFileP the file stream to which to write the raw data,
927 with the filtered data going to *ofP.
928
929 Filter according to *oeP.
930 -----------------------------------------------------------------------------*/
931
932 /* Build up the pipeline from the final to the initial stage. The
933 result is one of:
934
935 FEED | convertRow | asciiHexFilter | *ofP
936 FEED | convertRow | ascii85Filter | *ofP
937 FEED | convertRow | rleFilter | asciiHexFilter | *ofP
938 FEED | convertRow | flateFilter | asciiHexFilter | *ofP
939 FEED | convertRow | flateFilter | rleFilter | asciiHexFilter | *ofP
940 */
941
942 FILE * feedFileP;
943 /* The current head of the filter chain; changes as we add filters */
944
945 initPidList(pidList);
946
947 feedFileP = ofP; /* Initial state: no filter at all */
948
949 addFilter(
950 "output",
951 oeP->outputType == Ascii85 ? &ascii85Filter : asciiHexFilter,
952 oeP,
953 &feedFileP,
954 pidList);
955
956 if (oeP->compressFlate)
957 addFilter("flate", flateFilter, oeP, &feedFileP, pidList);
958
959 if (oeP->compressRle)
960 addFilter("rle", rleFilter, oeP, &feedFileP, pidList);
961
962 *feedFilePP = feedFileP;
963 }
964
965
966
967 static void
968 waitForChildren(const pid_t * const pidList) {
969 /*----------------------------------------------------------------------------
970 Wait for all child processes with PIDs in pidList[] to exit.
971 In pidList[], end-of-list is marked with a special zero value.
972 -----------------------------------------------------------------------------*/
973 /* There's an odd behavior in Unix such that if you have set the
974 action for SIGCHLD to ignore the signal (even though ignoring the
975 signal is the default), the process' children do not become
976 zombies. Consequently, waitpid() always fails with ECHILD - but
977 nonetheless waits for the child to exit.
978
979 We expect the process not to have the action for SIGCHLD set that
980 way.
981 */
982 unsigned int i;
983
984 for (i = 0; pidList[i]; ++i) {
985 pid_t rc;
986 int status;
987
988 if (verbose)
989 pm_message("Waiting for PID %u to exit", (unsigned)pidList[i]);
990
991 rc = waitpid(pidList[i], &status, 0);
992 if (rc == -1)
993 pm_error ("waitpid() for child %u failed, errno=%d (%s)",
994 i, errno, strerror(errno));
995 else if (status != EXIT_SUCCESS)
996 pm_error ("Child process %u terminated abnormally", i);
997 }
998 if (verbose)
999 pm_message("All children have exited");
1000 }
1001
1002
1003
1004 /*============================================================================
1005 END OF OUTPUT ENCODERS
1006 ============================================================================*/
1007
1008
1009
1010 static void
1011 validateComputableBoundingBox(float const scols,
1012 float const srows,
1013 float const llx,
1014 float const lly) {
1015
1016 float const bbWidth = llx + scols + 0.5;
1017 float const bbHeight = lly + srows + 0.5;
1018
1019 if ((double)bbHeight < INT_MIN || (double)bbHeight > INT_MAX ||
1020 (double)bbWidth < INT_MIN || (double)bbWidth > INT_MAX)
1021 pm_error("Bounding box dimensions %.1f x %.1f are too large "
1022 "for computations. "
1023 "This probably means input image width, height, "
1024 "or scale factor is too large", bbWidth, bbHeight);
1025 }
1026
1027
1028
1029 static void
1030 warnUserRescaling(float const scale) {
1031
1032 const char * const baseMsg = "warning, image too large for page";
1033
1034 if (pm_have_float_format())
1035 pm_message("%s; rescaling to %g", baseMsg, scale);
1036 else
1037 pm_message("%s; rescaling", baseMsg);
1038 }
1039
1040
1041
1042 static void
1043 computeImagePosition(int const dpiX,
1044 int const dpiY,
1045 int const icols,
1046 int const irows,
1047 bool const mustturn,
1048 bool const canturn,
1049 bool const center,
1050 int const pagewid,
1051 int const pagehgt,
1052 float const requestedScale,
1053 float const imagewidth,
1054 float const imageheight,
1055 bool const equalpixels,
1056 float * const scolsP,
1057 float * const srowsP,
1058 float * const llxP,
1059 float * const llyP,
1060 bool * const turnedP ) {
1061 /*----------------------------------------------------------------------------
1062 Determine where on the page the image is to go. This means position,
1063 dimensions, and orientation.
1064
1065 icols/irows are the dimensions of the PNM input in xels.
1066
1067 'mustturn' means we are required to rotate the image.
1068
1069 'canturn' means we may rotate the image if it fits better, but don't
1070 have to.
1071
1072 *scolsP, *srowsP are the dimensions of the image in 1/72 inch.
1073
1074 *llxP, *llyP are the coordinates in the Postcript frame, of the lower left
1075 corner of the image on the page. The Postscript frame is different from the
1076 Neptbm frame: units are 1/72 inch (1 point) and (0,0) is the lower left
1077 corner.
1078
1079 *turnedP is true iff the image is to be rotated 90 degrees on the page.
1080
1081 imagewidth/imageheight are the requested dimensions of the image on
1082 the page, in 1/72 inch. Image will be as large as possible within
1083 those dimensions. Zero means unspecified, so 'scale', 'pagewid',
1084 'pagehgt', 'irows', and 'icols' determine image size.
1085
1086 'equalpixels' means the user wants one printed pixel per input pixel.
1087 It is inconsistent with imagewidth or imageheight != 0
1088
1089 'requestedScale' is meaningful only when imageheight/imagewidth == 0
1090 and equalpixels == FALSE. It tells how many inches the user wants
1091 72 pixels of input to occupy, if it fits on the page.
1092 -----------------------------------------------------------------------------*/
1093 int cols, rows;
1094 /* Number of columns, rows of input xels in the output, as
1095 rotated if applicable
1096 */
1097 bool shouldturn; /* The image fits the page better if we turn it */
1098
1099 if (icols > irows && pagehgt > pagewid)
1100 shouldturn = TRUE;
1101 else if (irows > icols && pagewid > pagehgt)
1102 shouldturn = TRUE;
1103 else
1104 shouldturn = FALSE;
1105
1106 if (mustturn || (canturn && shouldturn)) {
1107 *turnedP = TRUE;
1108 cols = irows;
1109 rows = icols;
1110 } else {
1111 *turnedP = FALSE;
1112 cols = icols;
1113 rows = irows;
1114 }
1115 if (equalpixels) {
1116 *scolsP = (72.0/dpiX)*cols;
1117 *srowsP = (72.0/dpiY)*rows;
1118 } else if (imagewidth > 0 || imageheight > 0) {
1119 float scale;
1120
1121 if (imagewidth == 0)
1122 scale = (float) imageheight/rows;
1123 else if (imageheight == 0)
1124 scale = (float) imagewidth/cols;
1125 else
1126 scale = MIN((float)imagewidth/cols, (float)imageheight/rows);
1127
1128 *scolsP = cols*scale;
1129 *srowsP = rows*scale;
1130 } else {
1131 /* He didn't give us a bounding box for the image so figure
1132 out output image size from other inputs.
1133 */
1134 const int devpixX = dpiX / 72.0 + 0.5;
1135 const int devpixY = dpiY / 72.0 + 0.5;
1136 /* How many device pixels make up 1/72 inch, rounded to
1137 nearest integer */
1138 const float pixfacX = 72.0 / dpiX * devpixX; /* 1, approx. */
1139 const float pixfacY = 72.0 / dpiY * devpixY; /* 1, approx. */
1140 float scale;
1141
1142 scale = MIN(requestedScale,
1143 MIN((float)pagewid/cols, (float)pagehgt/rows));
1144
1145 *scolsP = scale * cols * pixfacX;
1146 *srowsP = scale * rows * pixfacY;
1147
1148 if (scale != requestedScale)
1149 warnUserRescaling(scale);
1150
1151 /* Before May 2001, Pnmtops enforced a 5% margin around the page.
1152 If the image would be too big to leave a 5% margin, Pnmtops would
1153 scale it down. But people have images that are exactly the size
1154 of a page, e.g. because they created them with Sane's 'scanimage'
1155 program from a full page of input. So we removed the gratuitous
1156 5% margin. -Bryan.
1157 */
1158 }
1159 *llxP = (center) ? ( pagewid - *scolsP ) / 2 : 0;
1160 *llyP = (center) ? ( pagehgt - *srowsP ) / 2 : 0;
1161
1162 validateComputableBoundingBox( *scolsP, *srowsP, *llxP, *llyP);
1163
1164 if (verbose)
1165 pm_message("Image will be %3.2f points wide by %3.2f points high, "
1166 "left edge %3.2f points from left edge of page, "
1167 "bottom edge %3.2f points from bottom of page; "
1168 "%sturned to landscape orientation",
1169 *scolsP, *srowsP, *llxP, *llyP, *turnedP ? "" : "NOT ");
1170 }
1171
1172
1173
1174 static void
1175 determineDictionaryRequirement(bool const userWantsDict,
1176 bool const psFilter,
1177 unsigned int * const dictSizeP) {
1178
1179 if (userWantsDict) {
1180 if (psFilter) {
1181 /* The Postscript this program generates to use built-in
1182 Postscript filters does not define any variables.
1183 */
1184 *dictSizeP = 0;
1185 } else
1186 *dictSizeP = 8;
1187 } else
1188 *dictSizeP = 0;
1189 }
1190
1191
1192
1193 static void
1194 defineReadstring(bool const rle) {
1195 /*----------------------------------------------------------------------------
1196 Write to Standard Output Postscript statements to define /readstring.
1197 -----------------------------------------------------------------------------*/
1198 if (rle) {
1199 printf("/rlestr1 1 string def\n");
1200 printf("/readrlestring {\n"); /* s -- nr */
1201 printf(" /rlestr exch def\n"); /* - */
1202 printf(" currentfile rlestr1 readhexstring pop\n"); /* s1 */
1203 printf(" 0 get\n"); /* c */
1204 printf(" dup 127 le {\n"); /* c */
1205 printf(" currentfile rlestr 0\n"); /* c f s 0 */
1206 printf(" 4 3 roll\n"); /* f s 0 c */
1207 printf(" 1 add getinterval\n"); /* f s */
1208 printf(" readhexstring pop\n"); /* s */
1209 printf(" length\n"); /* nr */
1210 printf(" } {\n"); /* c */
1211 printf(" 257 exch sub dup\n"); /* n n */
1212 printf(" currentfile rlestr1 readhexstring pop\n");/* n n s1 */
1213 printf(" 0 get\n"); /* n n c */
1214 printf(" exch 0 exch 1 exch 1 sub {\n"); /* n c 0 1 n-1*/
1215 printf(" rlestr exch 2 index put\n");
1216 printf(" } for\n"); /* n c */
1217 printf(" pop\n"); /* nr */
1218 printf(" } ifelse\n"); /* nr */
1219 printf("} bind def\n");
1220 printf("/readstring {\n"); /* s -- s */
1221 printf(" dup length 0 {\n"); /* s l 0 */
1222 printf(" 3 copy exch\n"); /* s l n s n l*/
1223 printf(" 1 index sub\n"); /* s l n s n r*/
1224 printf(" getinterval\n"); /* s l n ss */
1225 printf(" readrlestring\n"); /* s l n nr */
1226 printf(" add\n"); /* s l n */
1227 printf(" 2 copy le { exit } if\n"); /* s l n */
1228 printf(" } loop\n"); /* s l l */
1229 printf(" pop pop\n"); /* s */
1230 printf("} bind def\n");
1231 } else {
1232 printf("/readstring {\n"); /* s -- s */
1233 printf(" currentfile exch readhexstring pop\n");
1234 printf("} bind def\n");
1235 }
1236 }
1237
1238
1239
1240 static void
1241 setupReadstringNative(bool const rle,
1242 bool const color,
1243 unsigned int const icols,
1244 unsigned int const bitsPerSample) {
1245 /*----------------------------------------------------------------------------
1246 Write to Standard Output statements to define /readstring and also
1247 arguments for it (/picstr or /rpicstr, /gpicstr, and /bpicstr).
1248 -----------------------------------------------------------------------------*/
1249 unsigned int const bytesPerRow = icols / (8/bitsPerSample) +
1250 (icols % (8/bitsPerSample) > 0 ? 1 : 0);
1251 /* Size of row buffer, padded up to byte boundary. */
1252
1253 defineReadstring(rle);
1254
1255 if (color) {
1256 printf("/rpicstr %d string def\n", bytesPerRow);
1257 printf("/gpicstr %d string def\n", bytesPerRow);
1258 printf("/bpicstr %d string def\n", bytesPerRow);
1259 } else
1260 printf("/picstr %d string def\n", bytesPerRow);
1261 }
1262
1263
1264
1265 static void
1266 putFilters(unsigned int const postscriptLevel,
1267 bool const rle,
1268 bool const flate,
1269 bool const ascii85,
1270 bool const color) {
1271
1272 assert(postscriptLevel > 1);
1273
1274 /* We say to decode flate, then rle, so Caller must ensure it encodes
1275 rle, then flate.
1276 */
1277
1278 if (ascii85)
1279 printf("/ASCII85Decode filter ");
1280 else
1281 printf("/ASCIIHexDecode filter ");
1282 if (flate)
1283 printf("/FlateDecode filter ");
1284 if (rle)
1285 printf("/RunLengthDecode filter ");
1286 }
1287
1288
1289
1290 static void
1291 putReadstringNative(bool const color) {
1292
1293 if (color) {
1294 printf("{ rpicstr readstring }\n");
1295 printf("{ gpicstr readstring }\n");
1296 printf("{ bpicstr readstring }\n");
1297 } else
1298 printf("{ picstr readstring }\n");
1299 }
1300
1301
1302
1303 static void
1304 putSetup(unsigned int const dictSize,
1305 bool const psFilter,
1306 bool const rle,
1307 bool const color,
1308 unsigned int const icols,
1309 unsigned int const bitsPerSample) {
1310 /*----------------------------------------------------------------------------
1311 Put the setup section in the Postscript program on Standard Output.
1312 -----------------------------------------------------------------------------*/
1313 printf("%%%%BeginSetup\n");
1314
1315 if (dictSize > 0)
1316 /* inputf {r,g,b,}pictsr readstring readrlestring rlestring */
1317 printf("%u dict begin\n", dictSize);
1318
1319 if (!psFilter)
1320 setupReadstringNative(rle, color, icols, bitsPerSample);
1321
1322 printf("%%%%EndSetup\n");
1323 }
1324
1325
1326
1327 static void
1328 putImage(bool const psFilter,
1329 bool const color) {
1330 /*----------------------------------------------------------------------------
1331 Put the image/colorimage statement in the Postscript program on
1332 Standard Output.
1333 -----------------------------------------------------------------------------*/
1334 if (color) {
1335 if (psFilter)
1336 printf("false 3\n");
1337 else
1338 printf("true 3\n");
1339 printf("colorimage");
1340 } else
1341 printf("image");
1342 }
1343
1344
1345
1346 static void
1347 putInitPsFilter(unsigned int const postscriptLevel,
1348 bool const rle,
1349 bool const flate,
1350 bool const ascii85,
1351 bool const color) {
1352
1353 bool const filterTrue = TRUE;
1354
1355 printf("{ currentfile ");
1356
1357 putFilters(postscriptLevel, rle, flate, ascii85, color);
1358
1359 putImage(filterTrue, color);
1360
1361 printf(" } exec");
1362 }
1363
1364
1365
1366 static void
1367 putInitReadstringNative(bool const color) {
1368
1369 bool const filterFalse = FALSE;
1370
1371 putReadstringNative(color);
1372
1373 putImage(filterFalse, color);
1374 }
1375
1376
1377
1378 static void
1379 putInit(unsigned int const postscriptLevel,
1380 char const name[],
1381 int const icols,
1382 int const irows,
1383 float const scols,
1384 float const srows,
1385 float const llx,
1386 float const lly,
1387 int const bitsPerSample,
1388 int const pagewid,
1389 int const pagehgt,
1390 bool const color,
1391 bool const turned,
1392 bool const rle,
1393 bool const flate,
1394 bool const ascii85,
1395 bool const setpage,
1396 bool const psFilter,
1397 unsigned int const dictSize) {
1398 /*----------------------------------------------------------------------------
1399 Write out to Standard Output the headers stuff for the Postscript
1400 program (everything up to the raster).
1401 -----------------------------------------------------------------------------*/
1402 /* The numbers in the %! line often confuse people. They are NOT the
1403 PostScript language level. The first is the level of the DSC comment
1404 spec being adhered to, the second is the level of the EPSF spec being
1405 adhered to. It is *incorrect* to claim EPSF compliance if the file
1406 contains a setpagedevice.
1407 */
1408 printf("%%!PS-Adobe-3.0%s\n", setpage ? "" : " EPSF-3.0");
1409 printf("%%%%LanguageLevel: %u\n", postscriptLevel);
1410 printf("%%%%Creator: pnmtops\n");
1411 printf("%%%%Title: %s.ps\n", name);
1412 printf("%%%%Pages: 1\n");
1413 printf(
1414 "%%%%BoundingBox: %d %d %d %d\n",
1415 (int) llx, (int) lly,
1416 (int) (llx + scols + 0.5), (int) (lly + srows + 0.5));
1417 printf("%%%%EndComments\n");
1418
1419 putSetup(dictSize, psFilter, rle, color, icols, bitsPerSample);
1420
1421 printf("%%%%Page: 1 1\n");
1422 if (setpage)
1423 printf("<< /PageSize [ %d %d ] /ImagingBBox null >> setpagedevice\n",
1424 pagewid, pagehgt);
1425 printf("gsave\n");
1426 printf("%g %g translate\n", llx, lly);
1427 printf("%g %g scale\n", scols, srows);
1428 if (turned)
1429 printf("0.5 0.5 translate 90 rotate -0.5 -0.5 translate\n");
1430 printf("%d %d %d\n", icols, irows, bitsPerSample);
1431 printf("[ %d 0 0 -%d 0 %d ]\n", icols, irows, irows);
1432
1433 if (psFilter)
1434 putInitPsFilter(postscriptLevel, rle, flate, ascii85, color);
1435 else
1436 putInitReadstringNative(color);
1437
1438 printf("\n");
1439 fflush(stdout);
1440 }
1441
1442
1443
1444 static void
1445 putEnd(bool const showpage,
1446 bool const psFilter,
1447 bool const ascii85,
1448 unsigned int const dictSize,
1449 bool const vmreclaim) {
1450
1451 if (psFilter) {
1452 if (ascii85)
1453 printf("%s\n", "~>");
1454 else
1455 printf("%s\n", ">");
1456 } else {
1457 printf("currentdict /inputf undef\n");
1458 printf("currentdict /picstr undef\n");
1459 printf("currentdict /rpicstr undef\n");
1460 printf("currentdict /gpicstr undef\n");
1461 printf("currentdict /bpicstr undef\n");
1462 }
1463
1464 if (dictSize > 0)
1465 printf("end\n");
1466
1467 if (vmreclaim)
1468 printf("1 vmreclaim\n");
1469
1470 printf("grestore\n");
1471
1472 if (showpage)
1473 printf("showpage\n");
1474 printf("%%%%Trailer\n");
1475 }
1476
1477
1478
1479 static void
1480 validateBpsRequest(unsigned int const bitsPerSampleReq,
1481 unsigned int const postscriptLevel,
1482 bool const psFilter) {
1483
1484 if (postscriptLevel < 2 && bitsPerSampleReq > 8)
1485 pm_error("You requested %u bits per sample, but in Postscript "
1486 "level 1, 8 is the maximum. You can get 12 with "
1487 "-level 2 and -psfilter", bitsPerSampleReq);
1488 else if (!psFilter && bitsPerSampleReq > 8)
1489 pm_error("You requested %u bits per sample, but without "
1490 "-psfilter, the maximum is 8", bitsPerSampleReq);
1491 }
1492
1493
1494
1495 static unsigned int
1496 bpsFromInput(unsigned int const bitsRequiredByMaxval,
1497 unsigned int const postscriptLevel,
1498 bool const psFilter) {
1499
1500 unsigned int retval;
1501
1502 if (bitsRequiredByMaxval <= 1)
1503 retval = 1;
1504 else if (bitsRequiredByMaxval <= 2)
1505 retval = 2;
1506 else if (bitsRequiredByMaxval <= 4)
1507 retval = 4;
1508 else if (bitsRequiredByMaxval <= 8)
1509 retval = 8;
1510 else {
1511 /* Post script level 2 defines a format with 12 bits per sample,
1512 but I don't know the details of that format (both RLE and
1513 non-RLE variations) and existing native raster generation code
1514 simply can't handle bps > 8. But the built-in filters know
1515 how to do 12 bps.
1516 */
1517 if (postscriptLevel >= 2 && psFilter)
1518 retval = 12;
1519 else
1520 retval = 8;
1521 }
1522 return retval;
1523 }
1524
1525
1526
1527 static void
1528 warnUserAboutReducedDepth(unsigned int const bitsGot,
1529 unsigned int const bitsWanted,
1530 bool const userRequested,
1531 unsigned int const postscriptLevel,
1532 bool const psFilter) {
1533
1534 if (bitsGot < bitsWanted) {
1535 pm_message("Postscript will have %u bits of color resolution, "
1536 "though the input has %u bits.",
1537 bitsGot, bitsWanted);
1538
1539 if (!userRequested) {
1540 if (postscriptLevel < 2)
1541 pm_message("Postscript level %u has a maximum depth of "
1542 "8 bits. "
1543 "You could get up to 12 with -level=2 "
1544 "and -psfilter.",
1545 postscriptLevel);
1546 else {
1547 if (!psFilter)
1548 pm_message("You can get up to 12 bits with -psfilter");
1549 else
1550 pm_message("The Postscript maximum is 12.");
1551 }
1552 }
1553 }
1554 }
1555
1556
1557
1558 static void
1559 computeDepth(xelval const inputMaxval,
1560 unsigned int const postscriptLevel,
1561 bool const psFilter,
1562 unsigned int const bitsPerSampleReq,
1563 unsigned int * const bitsPerSampleP) {
1564 /*----------------------------------------------------------------------------
1565 Figure out how many bits will represent each sample in the Postscript
1566 program, and the maxval of the Postscript program samples. The maxval
1567 is just the maximum value allowable in the number of bits.
1568
1569 'bitsPerSampleReq' is the bits per sample that the user requests, or
1570 zero if he made no request.
1571 -----------------------------------------------------------------------------*/
1572 unsigned int const bitsRequiredByMaxval = pm_maxvaltobits(inputMaxval);
1573
1574 if (bitsPerSampleReq != 0) {
1575 validateBpsRequest(bitsPerSampleReq, postscriptLevel, psFilter);
1576 *bitsPerSampleP = bitsPerSampleReq;
1577 } else {
1578 *bitsPerSampleP = bpsFromInput(bitsRequiredByMaxval,
1579 postscriptLevel, psFilter);
1580 }
1581 warnUserAboutReducedDepth(*bitsPerSampleP, bitsRequiredByMaxval,
1582 bitsPerSampleReq != 0,
1583 postscriptLevel, psFilter);
1584
1585 if (verbose) {
1586 unsigned int const psMaxval = pm_bitstomaxval(*bitsPerSampleP);
1587 pm_message("Input maxval is %u. Postscript raster will have "
1588 "%u bits per sample, so maxval = %u",
1589 inputMaxval, *bitsPerSampleP, psMaxval);
1590 }
1591 }
1592
1593
1594
1595 /*===========================================================================
1596 The bit accumulator
1597 ===========================================================================*/
1598
1599 typedef struct {
1600 unsigned int value;
1601 unsigned int consumed;
1602 } BitAccumulator;
1603
1604
1605
1606 static void
1607 ba_init(BitAccumulator * const baP) {
1608
1609 baP->value = 0;
1610 baP->consumed = 0;
1611 }
1612
1613
1614
1615 static void
1616 ba_add12(BitAccumulator * const baP,
1617 unsigned int const new12,
1618 FILE * const fP) {
1619 /*----------------------------------------------------------------------------
1620 Read a 12-bit string into the bit accumulator baP->value.
1621 On every other call, combine two 12-bit strings and write out three bytes.
1622 -----------------------------------------------------------------------------*/
1623 assert (baP->consumed == 12 || baP->consumed == 0);
1624
1625 if (baP->consumed == 12){
1626 char const oldHi8 = (baP->value) >> 4;
1627 char const oldLo4 = (baP->value) & 0x0f;
1628 char const newHi4 = new12 >> 8;
1629 char const newLo8 = new12 & 0xff;
1630
1631 fputc(oldHi8, fP);
1632 fputc((oldLo4 << 4) | newHi4 , fP);
1633 fputc(newLo8, fP);
1634 baP->value = 0; baP->consumed = 0;
1635 } else {
1636 baP->value = new12; baP->consumed = 12;
1637 }
1638 }
1639
1640
1641
1642 static void
1643 ba_add(BitAccumulator * const baP,
1644 unsigned int const b,
1645 unsigned int const bitsPerSample,
1646 FILE * const fP) {
1647 /*----------------------------------------------------------------------------
1648 Combine bit sequences that do not fit into a byte.
1649
1650 Used when bitsPerSample =1, 2, 4.
1651 Logic also works for bitsPerSample = 8, 16.
1652
1653 The accumulator, baP->value is unsigned int (usually 32 bits), but
1654 only 8 bits are used.
1655 -----------------------------------------------------------------------------*/
1656 unsigned int const bufSize = 8;
1657
1658 assert (bitsPerSample == 1 || bitsPerSample == 2 || bitsPerSample == 4);
1659
1660 baP->value = (baP->value << bitsPerSample) | b ;
1661 baP->consumed += bitsPerSample;
1662 if (baP->consumed == bufSize) {
1663 /* flush */
1664 fputc( baP->value, fP);
1665 baP->value = 0;
1666 baP->consumed = 0;
1667 }
1668 }
1669
1670
1671
1672 static void
1673 ba_flush(BitAccumulator * const baP,
1674 FILE * const fP) {
1675 /*----------------------------------------------------------------------------
1676 Flush partial bits in baP->consumed.
1677 -----------------------------------------------------------------------------*/
1678 if (baP->consumed == 12) {
1679 char const oldHi8 = (baP->value) >> 4;
1680 char const oldLo4 = (baP->value) & 0x0f;
1681 fputc(oldHi8, fP);
1682 fputc(oldLo4 << 4, fP);
1683 } else if (baP->consumed == 8)
1684 fputc(baP->value , fP);
1685 else if (baP->consumed > 0) {
1686 unsigned int const leftShift = 8 - baP->consumed;
1687 assert(baP->consumed <= 8); /* why? */
1688 baP->value <<= leftShift;
1689 fputc(baP->value , fP);
1690 }
1691 baP->value = 0;
1692 baP->consumed = 0;
1693 }
1694
1695
1696
1697 static void
1698 outputSample(BitAccumulator * const baP,
1699 unsigned int const sampleValue,
1700 unsigned int const bitsPerSample,
1701 FILE * const fP) {
1702
1703 if (bitsPerSample == 8)
1704 fputc(sampleValue, fP);
1705 else if (bitsPerSample == 12)
1706 ba_add12(baP, sampleValue, fP);
1707 else
1708 ba_add(baP, sampleValue, bitsPerSample, fP);
1709 }
1710
1711
1712
1713 static void
1714 flushOutput(BitAccumulator * const baP,
1715 FILE * const fP) {
1716 ba_flush(baP, fP);
1717 }
1718
1719
1720
1721 /*----------------------------------------------------------------------
1722 Row converters
1723
1724 convertRowPbm is a fast routine for PBM images.
1725 It is used only when the input is PBM and the user does not specify
1726 a -bitspersample value greater than 1. It is not used when the input
1727 image is PGM or PPM and the output resolution is brought down to one
1728 bit per pixel by -bitpersample=1 .
1729
1730 convertRowNative and convertRowPsFilter are the general converters.
1731 They are quite similar, the differences being:
1732 (1) Native output separates the color planes:
1733 (RRR...RRR GGG...GGG BBB...BBB),
1734 whereas psFilter does not:
1735 (RGB RGB RGB RGB ......... RGB).
1736 (2) Native flushes the run-length encoder at the end of each row if
1737 grayscale, at the end of each plane if color.
1738
1739 Both convertRowNative and convertRowPsFilter can handle PBM, though we
1740 don't use them.
1741
1742 If studying the code, read convertRowPbm first. convertRowNative and
1743 convertRowPsFilter are constructs that pack raster data into a form
1744 similar to a binary PBM bitrow.
1745 ----------------------------------------------------------------------*/
1746
1747 static void
1748 convertRowPbm(struct pam * const pamP,
1749 unsigned char * const bitrow,
1750 bool const psFilter,
1751 FILE * const fP) {
1752 /*---------------------------------------------------------------------
1753 Feed PBM raster data directly to the output encoder.
1754 Invert bits: 0 is "white" in PBM, 0 is "black" in postscript.
1755 ----------------------------------------------------------------------*/
1756 unsigned int colChar;
1757 unsigned int const colChars = pbm_packed_bytes(pamP->width);
1758
1759 pbm_readpbmrow_packed(pamP->file, bitrow, pamP->width, pamP->format);
1760
1761 for (colChar = 0; colChar < colChars; ++colChar)
1762 bitrow[colChar] = ~ bitrow[colChar];
1763
1764 /* Zero clear padding beyond right edge */
1765 pbm_cleanrowend_packed(bitrow, pamP->width);
1766 writeFile(bitrow, colChars, "PBM reader", fP);
1767 }
1768
1769
1770
1771 static void
1772 convertRowNative(struct pam * const pamP,
1773 tuple * tuplerow,
1774 unsigned int const bitsPerSample,
1775 FILE * const fP) {
1776
1777 unsigned int const psMaxval = pm_bitstomaxval(bitsPerSample);
1778
1779 unsigned int plane;
1780 BitAccumulator ba;
1781
1782 ba_init(&ba);
1783
1784 pnm_readpamrow(pamP, tuplerow);
1785 pnm_scaletuplerow(pamP, tuplerow, tuplerow, psMaxval);
1786
1787 for (plane = 0; plane < pamP->depth; ++plane) {
1788 unsigned int col;
1789 for (col= 0; col < pamP->width; ++col)
1790 outputSample(&ba, tuplerow[col][plane], bitsPerSample, fP);
1791
1792 flushOutput(&ba, fP);
1793 }
1794 }
1795
1796
1797
1798 static void
1799 convertRowPsFilter(struct pam * const pamP,
1800 tuple * tuplerow,
1801 unsigned int const bitsPerSample,
1802 FILE * const fP) {
1803
1804 unsigned int const psMaxval = pm_bitstomaxval(bitsPerSample);
1805
1806 unsigned int col;
1807 BitAccumulator ba;
1808
1809 ba_init(&ba);
1810
1811 pnm_readpamrow(pamP, tuplerow);
1812 pnm_scaletuplerow(pamP, tuplerow, tuplerow, psMaxval);
1813
1814 for (col = 0; col < pamP->width; ++col) {
1815 unsigned int plane;
1816 for (plane = 0; plane < pamP->depth; ++plane)
1817 outputSample(&ba, tuplerow[col][plane], bitsPerSample, fP);
1818 }
1819 flushOutput(&ba, fP);
1820
1821 }
1822
1823
1824
1825 static void
1826 selectPostscriptLevel(bool const levelIsGiven,
1827 unsigned int const levelGiven,
1828 bool const color,
1829 bool const dict,
1830 bool const flate,
1831 bool const ascii85,
1832 bool const psFilter,
1833 unsigned int * const postscriptLevelP) {
1834
1835 unsigned int const maxPermittedLevel =
1836 levelIsGiven ? levelGiven : UINT_MAX;
1837 unsigned int minPossibleLevel;
1838
1839 /* Until we know, later in this function, that we needs certain
1840 features, we assume we can get by with classic Postscript Level 1:
1841 */
1842 minPossibleLevel = 1;
1843
1844 /* Now we increase 'minPossibleLevel' as we notice that each of
1845 various features are required:
1846 */
1847 if (color) {
1848 minPossibleLevel = MAX(minPossibleLevel, 2);
1849 if (2 > maxPermittedLevel)
1850 pm_error("Color requires at least Postscript level 2");
1851 }
1852 if (flate) {
1853 minPossibleLevel = MAX(minPossibleLevel, 3);
1854 if (2 > maxPermittedLevel)
1855 pm_error("flate compression requires at least Postscript level 3");
1856 }
1857 if (ascii85) {
1858 minPossibleLevel = MAX(minPossibleLevel, 2);
1859 if (2 > maxPermittedLevel)
1860 pm_error("ascii85 encoding requires at least Postscript level 2");
1861 }
1862 if (psFilter) {
1863 minPossibleLevel = MAX(minPossibleLevel, 2);
1864 if (2 > maxPermittedLevel)
1865 pm_error("-psfilter requires at least Postscript level 2");
1866 }
1867 if (levelIsGiven)
1868 *postscriptLevelP = levelGiven;
1869 else
1870 *postscriptLevelP = minPossibleLevel;
1871 }
1872
1873
1874
1875 static void
1876 convertRaster(struct pam * const inpamP,
1877 unsigned int const bitsPerSample,
1878 bool const psFilter,
1879 FILE * const fP) {
1880 /*----------------------------------------------------------------------------
1881 Read the raster described by *inpamP, and write a bit stream of samples
1882 to *fP. This stream has to be compressed and converted to text before it
1883 can be part of a Postscript program.
1884
1885 'psFilter' means to do the conversion using built in Postscript filters, as
1886 opposed to our own filters via /readstring.
1887
1888 'bitsPerSample' is how many bits each sample is to take in the Postscript
1889 output.
1890 -----------------------------------------------------------------------------*/
1891 if (PAM_FORMAT_TYPE(inpamP->format) == PBM_TYPE && bitsPerSample == 1) {
1892 unsigned char * bitrow;
1893 unsigned int row;
1894
1895 bitrow = pbm_allocrow_packed(inpamP->width);
1896
1897 for (row = 0; row < inpamP->height; ++row)
1898 convertRowPbm(inpamP, bitrow, psFilter, fP);
1899
1900 pbm_freerow(bitrow);
1901 } else {
1902 tuple *tuplerow;
1903 unsigned int row;
1904
1905 tuplerow = pnm_allocpamrow(inpamP);
1906
1907 for (row = 0; row < inpamP->height; ++row) {
1908 if (psFilter)
1909 convertRowPsFilter(inpamP, tuplerow, bitsPerSample, fP);
1910 else
1911 convertRowNative(inpamP, tuplerow, bitsPerSample, fP);
1912 }
1913 pnm_freepamrow(tuplerow);
1914 }
1915 }
1916
1917
1918
1919 /* FILE MANAGEMENT: File management is pretty hairy here. A filter, which
1920 runs in its own process, needs to be able to cause its output file to
1921 close because it might be an internal pipe and the next stage needs to
1922 know output is done. So the forking process must close its copy of the
1923 file descriptor. BUT: if the output of the filter is not an internal
1924 pipe but this program's output, then we don't want it closed when the
1925 filter terminates because we'll need it to be open for the next image
1926 the program converts (with a whole new chain of filters).
1927
1928 To prevent the program output file from getting closed, we pass a
1929 duplicate of it to spawnFilters() and keep the original open.
1930 */
1931
1932
1933
1934 static void
1935 convertPage(FILE * const ifP,
1936 int const turnflag,
1937 int const turnokflag,
1938 bool const psFilter,
1939 bool const rle,
1940 bool const flate,
1941 bool const ascii85,
1942 bool const setpage,
1943 bool const showpage,
1944 bool const center,
1945 float const scale,
1946 int const dpiX,
1947 int const dpiY,
1948 int const pagewid,
1949 int const pagehgt,
1950 int const imagewidth,
1951 int const imageheight,
1952 bool const equalpixels,
1953 unsigned int const bitsPerSampleReq,
1954 char const name[],
1955 bool const dict,
1956 bool const vmreclaim,
1957 bool const levelIsGiven,
1958 unsigned int const levelGiven) {
1959
1960 struct pam inpam;
1961 float scols, srows;
1962 float llx, lly;
1963 bool turned;
1964 bool color;
1965 unsigned int postscriptLevel;
1966 unsigned int bitsPerSample;
1967 unsigned int dictSize;
1968 /* Size of Postscript dictionary we should define */
1969 OutputEncoder oe;
1970 pid_t filterPidList[MAX_FILTER_CT + 1];
1971
1972 FILE * feedFileP;
1973 /* The file stream which is the head of the filter chain; we write to
1974 this and filtered stuff comes out the other end.
1975 */
1976 FILE * filterChainOfP;
1977
1978 pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
1979
1980 validateCompDimension(inpam.width, 16, "Input image width");
1981
1982 if (!STRSEQ(inpam.tuple_type, PAM_PBM_TUPLETYPE) &&
1983 !STRSEQ(inpam.tuple_type, PAM_PGM_TUPLETYPE) &&
1984 !STRSEQ(inpam.tuple_type, PAM_PPM_TUPLETYPE))
1985 pm_error("Unrecognized tuple type %s. This program accepts only "
1986 "PBM, PGM, PPM, and equivalent PAM input images",
1987 inpam.tuple_type);
1988
1989 color = STRSEQ(inpam.tuple_type, PAM_PPM_TUPLETYPE);
1990
1991 selectPostscriptLevel(levelIsGiven, levelGiven, color,
1992 dict, flate, ascii85, psFilter, &postscriptLevel);
1993
1994 if (color)
1995 pm_message("generating color Postscript program.");
1996
1997 computeDepth(inpam.maxval, postscriptLevel, psFilter, bitsPerSampleReq,
1998 &bitsPerSample);
1999
2000 /* In positioning/scaling the image, we treat the input image as if
2001 it has a density of 72 pixels per inch.
2002 */
2003 computeImagePosition(dpiX, dpiY, inpam.width, inpam.height,
2004 turnflag, turnokflag, center,
2005 pagewid, pagehgt, scale, imagewidth, imageheight,
2006 equalpixels,
2007 &scols, &srows, &llx, &lly, &turned);
2008
2009 determineDictionaryRequirement(dict, psFilter, &dictSize);
2010
2011 putInit(postscriptLevel, name, inpam.width, inpam.height,
2012 scols, srows, llx, lly, bitsPerSample,
2013 pagewid, pagehgt, color,
2014 turned, rle, flate, ascii85, setpage, psFilter, dictSize);
2015
2016 initOutputEncoder(&oe, inpam.width, bitsPerSample,
2017 rle, flate, ascii85, psFilter);
2018
2019 fflush(stdout);
2020 filterChainOfP = fdopen(dup(fileno(stdout)), "w");
2021 /* spawnFilters() closes this. See FILE MANAGEMENT above */
2022
2023 spawnFilters(filterChainOfP, &oe, &feedFileP, filterPidList);
2024
2025 convertRaster(&inpam, bitsPerSample, psFilter, feedFileP);
2026
2027 fflush(feedFileP);
2028 fclose(feedFileP);
2029
2030 waitForChildren(filterPidList);
2031
2032 putEnd(showpage, psFilter, ascii85, dictSize, vmreclaim);
2033 }
2034
2035
2036
2037 int
2038 main(int argc, const char * argv[]) {
2039
2040 FILE * ifP;
2041 const char * name; /* malloc'ed */
2042 struct CmdlineInfo cmdline;
2043
2044 pm_proginit(&argc, argv);
2045
2046 setSignals();
2047
2048 parseCommandLine(argc, argv, &cmdline);
2049
2050 verbose = cmdline.verbose || cmdline.debug;
2051 debug = cmdline.debug;
2052
2053 if (cmdline.flate && !progIsFlateCapable())
2054 pm_error("This program cannot do flate compression. "
2055 "(There are other versions of the program that do, "
2056 "though -- it's a build-time option");
2057
2058 ifP = pm_openr(cmdline.inputFileName);
2059
2060 if (streq(cmdline.inputFileName, "-"))
2061 name = strdup("noname");
2062 else
2063 name = basebasename(cmdline.inputFileName);
2064
2065 /* This program manages file descriptors in a way that assumes
2066 that new files will get file descriptor numbers less than 10,
2067 so we close superfluous files now to make sure that's true.
2068 */
2069 closeAllBut(fileno(ifP), fileno(stdout), fileno(stderr));
2070
2071 {
2072 int eof; /* There are no more images in the input file */
2073 unsigned int imageSeq;
2074
2075 /* I don't know if this works at all for multi-image PNM input.
2076 Before July 2000, it ignored everything after the first image,
2077 so this probably is at least as good -- it should be identical
2078 for a single-image file, which is the only kind which was legal
2079 before July 2000.
2080
2081 Maybe there needs to be some per-file header and trailers stuff
2082 in the Postscript program, with some per-page header and trailer
2083 stuff inside. I don't know Postscript. - Bryan 2000.06.19.
2084 */
2085
2086 eof = FALSE; /* There is always at least one image */
2087 for (imageSeq = 0; !eof; ++imageSeq) {
2088 convertPage(ifP, cmdline.mustturn, cmdline.canturn,
2089 cmdline.psfilter,
2090 cmdline.rle, cmdline.flate, cmdline.ascii85,
2091 cmdline.setpage, cmdline.showpage,
2092 cmdline.center, cmdline.scale,
2093 cmdline.dpiX, cmdline.dpiY,
2094 cmdline.width, cmdline.height,
2095 cmdline.imagewidth, cmdline.imageheight,
2096 cmdline.equalpixels,
2097 cmdline.bitspersampleSpec ? cmdline.bitspersample : 0,
2098 name,
2099 cmdline.dict, cmdline.vmreclaim,
2100 cmdline.levelSpec, cmdline.level);
2101 pnm_nextimage(ifP, &eof);
2102 }
2103 }
2104 pm_strfree(name);
2105
2106 pm_close(ifP);
2107
2108 return 0;
2109 }
2110
2111
2112
2113 /*
2114 ** Copyright (C) 1989 by Jef Poskanzer.
2115 **
2116 ** Permission to use, copy, modify, and distribute this software and its
2117 ** documentation for any purpose and without fee is hereby granted, provided
2118 ** that the above copyright notice appear in all copies and that both that
2119 ** copyright notice and this permission notice appear in supporting
2120 ** documentation. This software is provided "as is" without express or
2121 ** implied warranty.
2122 **
2123 **
2124 ** -nocenter option added November 1993 by Wolfgang Stuerzlinger,
2125 ** [email protected].
2126 **
2127 ** July 2011 afu
2128 ** row converters rewritten, fast PBM-only row converter added,
2129 ** rle compression slightly modified, flate compression added
2130 ** ascii85 output end added.
2131 **
2132 */