Debian Codegraph @

converter/other/pnmtops.c

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