ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/px/ra_ps.c
Revision: 2.30
Committed: Thu Aug 2 18:33:47 2018 UTC (5 years, 9 months ago) by greg
Content type: text/plain
Branch: MAIN
CVS Tags: rad5R2
Changes since 2.29: +2 -2 lines
Log Message:
Created MAXFMTLEN to guard against buffer overrun attacks in header input

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.30 static const char RCSid[] = "$Id: ra_ps.c,v 2.29 2018/03/20 18:45:04 greg Exp $";
3 greg 2.1 #endif
4     /*
5     * Radiance picture to PostScript file translator -- one way!
6     */
7    
8     #include <stdio.h>
9 schorsch 2.27 #include <string.h>
10 greg 2.13 #include <math.h>
11 gregl 2.18 #include <ctype.h>
12 schorsch 2.25
13     #include "platform.h"
14 greg 2.29 #include "rtio.h"
15 greg 2.1 #include "color.h"
16 schorsch 2.27 #include "resolu.h"
17 greg 2.1
18 gregl 2.18 #define UPPER(c) ((c)&~0x20) /* ASCII trick */
19    
20 gregl 2.17 #define CODE6GAM 1.47 /* gamma for 6-bit codes */
21 gwlarson 2.21 #define DEFGGAM 1.0 /* greyscale device gamma */
22     #define DEFCGAM 1.8 /* color device gamma */
23 greg 2.13
24 greg 2.11 #define GRY -1 /* artificial index for grey */
25    
26 gregl 2.18 #define DEFMARG 0.5 /* default margin (inches) */
27     #define DEFWIDTH 8.5 /* default page width */
28     #define DEFHEIGHT 11 /* default page height */
29     #define HMARGIN (hmarg*72) /* horizontal margin */
30     #define VMARGIN (vmarg*72) /* vertical margin */
31     #define PWIDTH (width*72-2*HMARGIN) /* width of device */
32     #define PHEIGHT (height*72-2*VMARGIN) /* height of device */
33 greg 2.1
34 greg 2.9 #define RUNCHR '*' /* character to start rle */
35     #define MINRUN 4 /* minimum run-length */
36     #define RSTRT '!' /* character for MINRUN */
37     #define MAXRUN (MINRUN+'~'-RSTRT) /* maximum run-length */
38    
39 greg 2.1 char code[] = /* 6-bit code lookup table */
40     "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@+";
41    
42     int wrongformat = 0; /* input in wrong format? */
43 greg 2.6 double pixaspect = 1.0; /* pixel aspect ratio */
44 greg 2.1
45 gwlarson 2.21 double devgam = 0.; /* device gamma response */
46 gregl 2.18 double hmarg = DEFMARG,
47     vmarg = DEFMARG; /* horizontal and vertical margins */
48     double width = DEFWIDTH,
49     height = DEFHEIGHT; /* default paper width and height */
50 gregl 2.20 double dpi = 0; /* print density (0 if unknown) */
51 gwlarson 2.21 int docolor = 1; /* produce color image? */
52 greg 2.1 int bradj = 0; /* brightness adjustment */
53 greg 2.4 int ncopies = 1; /* number of copies */
54 greg 2.1
55 schorsch 2.28 char *progname;
56     int xmax, ymax; /* input image dimensions */
57 greg 2.15
58 schorsch 2.28 typedef void putprimf_t(COLR *scn, int pri);
59 greg 2.15
60 schorsch 2.28 static gethfunc headline;
61     static putprimf_t Aputprim, Bputprim, Cputprim;
62 greg 2.1
63 schorsch 2.28 static double unit2inch(register char *s);
64     static int matchid(char *name, char *id);
65     static void parsepaper(char *ps);
66     static void quiterr(char *err);
67     static void PSheader(int ac, char **av);
68     static void PStrailer(void);
69     static void PSprocdef(char *nam);
70     static void ra2ps(void);
71     static void putrle(int cnt, int cod);
72 greg 2.1
73    
74 schorsch 2.28 putprimf_t *putprim = Aputprim; /* function for writing scanline */
75 greg 2.6
76 schorsch 2.27
77     static int
78     headline( /* check header line */
79     char *s,
80     void *p
81     )
82 greg 2.1 {
83 greg 2.30 char fmt[MAXFMTLEN];
84 greg 2.1
85     if (isformat(s)) {
86     formatval(fmt, s);
87     wrongformat = strcmp(fmt, COLRFMT);
88     } else if (isaspect(s))
89     pixaspect *= aspectval(s);
90 gwlarson 2.22 return(0);
91 greg 2.1 }
92    
93 schorsch 2.28 int
94     main(int argc, char *argv[])
95 greg 2.1 {
96     int i;
97 gregl 2.18 double d;
98 greg 2.1
99     progname = argv[0];
100    
101     for (i = 1; i < argc; i++)
102     if (argv[i][0] == '-')
103     switch (argv[i][1]) {
104 greg 2.15 case 'b': /* produce b&w PostScript */
105     docolor = 0;
106     break;
107 greg 2.11 case 'c': /* produce color PostScript */
108 greg 2.15 docolor = 1;
109 greg 2.11 break;
110 greg 2.15 case 'A': /* standard ASCII encoding */
111     putprim = Aputprim;
112     break;
113     case 'B': /* standard binary encoding */
114     putprim = Bputprim;
115     break;
116     case 'C': /* compressed ASCII encoding */
117     putprim = Cputprim;
118     break;
119 gregl 2.20 case 'd': /* print density */
120     dpi = atof(argv[++i]);
121     break;
122 gregl 2.18 case 'g': /* device gamma adjustment */
123 gregl 2.17 devgam = atof(argv[++i]);
124     break;
125 gregl 2.18 case 'p': /* paper size */
126     parsepaper(argv[++i]);
127     break;
128     case 'm': /* margin */
129     d = atof(argv[i+1]);
130     d *= unit2inch(argv[i+1]);
131     switch (argv[i][2]) {
132     case '\0':
133     hmarg = vmarg = d;
134     break;
135     case 'h':
136     hmarg = d;
137     break;
138     case 'v':
139     vmarg = d;
140     break;
141     default:
142     goto userr;
143     }
144     i++;
145     break;
146 greg 2.1 case 'e': /* exposure adjustment */
147     if (argv[i+1][0] != '+' && argv[i+1][0] != '-')
148     goto userr;
149     bradj = atoi(argv[++i]);
150     break;
151 greg 2.4 case 'n': /* number of copies */
152     ncopies = atoi(argv[++i]);
153     break;
154 greg 2.1 default:
155     goto userr;
156     }
157     else
158     break;
159    
160     if (i < argc-2)
161     goto userr;
162     if (i <= argc-1 && freopen(argv[i], "r", stdin) == NULL) {
163     fprintf(stderr, "%s: can't open input \"%s\"\n",
164     progname, argv[i]);
165     exit(1);
166     }
167     if (i == argc-2 && freopen(argv[i+1], "w", stdout) == NULL) {
168 greg 2.7 fprintf(stderr, "%s: can't open output \"%s\"\n",
169 greg 2.1 progname, argv[i+1]);
170     exit(1);
171     }
172 schorsch 2.25 SET_FILE_BINARY(stdin);
173 greg 2.1 /* get our header */
174     getheader(stdin, headline, NULL);
175     if (wrongformat || fgetresolu(&xmax, &ymax, stdin) < 0)
176     quiterr("bad picture format");
177 greg 2.13 /* gamma compression */
178 gwlarson 2.21 if (devgam <= 0.05)
179     devgam = docolor ? DEFCGAM : DEFGGAM;
180 greg 2.15 if (putprim == Cputprim)
181 gregl 2.19 setcolrgam(CODE6GAM);
182 gregl 2.17 else if (devgam != 1.)
183 gregl 2.19 setcolrgam(devgam);
184 greg 2.1 /* write header */
185 gwlarson 2.21 PSheader(argc, argv);
186 greg 2.1 /* convert file */
187     ra2ps();
188     /* write trailer */
189     PStrailer();
190     exit(0);
191     userr:
192 gregl 2.18 fprintf(stderr,
193 gregl 2.20 "Usage: %s [-b|c][-A|B|C][-e +/-stops][-p paper][-m[h|v] margin][-d dpi][-g gamma] [input [output]]\n",
194 greg 2.11 progname);
195 gregl 2.18 exit(1);
196     }
197    
198    
199 schorsch 2.28 static double
200     unit2inch( /* determine unit */
201     register char *s
202     )
203 gregl 2.18 {
204 gwlarson 2.23 static struct unit {char n; float f;} u[] = {
205 schorsch 2.27 {'i', 1.},
206     {'m', 1./25.4},
207     {'c', 1./2.54},
208     {'\0',0} };
209 gregl 2.18 register struct unit *up;
210    
211     while (*s && !isalpha(*s))
212     s++;
213     for (up = u; up->n; up++)
214     if (up->n == *s)
215     return(up->f);
216     return(1.);
217     }
218    
219    
220 schorsch 2.28 static int
221     matchid( /* see if name matches id (case insensitive) */
222     char *name,
223     register char *id
224     )
225 gregl 2.18 {
226     register char *s = name;
227    
228     while (*s) {
229     if (isalpha(*s)) {
230     if (!isalpha(*id) || UPPER(*s) != UPPER(*id))
231     return(0);
232     } else if (*s != *id)
233     return(0);
234     s++; id++;
235     }
236     return(!*id || s-name >= 3); /* substrings >= 3 chars OK */
237     }
238    
239    
240 schorsch 2.28 static void
241     parsepaper( /* determine paper size from name */
242     char *ps
243     )
244 gregl 2.18 {
245     static struct psize {char n[12]; float w,h;} p[] = {
246 schorsch 2.27 {"envelope", 4.12, 9.5},
247     {"executive", 7.25, 10.5},
248     {"letter", 8.5, 11.},
249     {"lettersmall", 7.68, 10.16},
250     {"legal", 8.5, 14.},
251     {"monarch", 3.87, 7.5},
252     {"statement", 5.5, 8.5},
253     {"tabloid", 11., 17.},
254     {"A3", 11.69, 16.54},
255     {"A4", 8.27, 11.69},
256     {"A4small", 7.47, 10.85},
257     {"A5", 6.00, 8.27},
258     {"A6", 4.13, 6.00},
259     {"B4", 10.12, 14.33},
260     {"B5", 7.17, 10.12},
261     {"C5", 6.38, 9.01},
262     {"C6", 4.49, 6.38},
263     {"DL", 4.33, 8.66},
264     {"hagaki", 3.94, 5.83},
265     {"",0.0,0.0} };
266 gregl 2.18 register struct psize *pp;
267     register char *s = ps;
268     double d;
269    
270     if (isdigit(*s)) { /* check for WWxHH specification */
271     width = atof(s);
272     while (*s && !isalpha(*s))
273     s++;
274     d = unit2inch(s);
275     height = atof(++s);
276     width *= d;
277     height *= d;
278 schorsch 2.26 if ((width >= 1.) & (height >= 1.))
279 gregl 2.18 return;
280     } else /* check for match to standard size */
281     for (pp = p; pp->n[0]; pp++)
282     if (matchid(s, pp->n)) {
283     width = pp->w;
284     height = pp->h;
285     return;
286     }
287     fprintf(stderr, "%s: unknown paper size \"%s\" -- known sizes:\n",
288     progname, ps);
289     fprintf(stderr, "_Name________Width_Height_(inches)\n");
290     for (pp = p; pp->n[0]; pp++)
291     fprintf(stderr, "%-11s %5.2f %5.2f\n", pp->n, pp->w, pp->h);
292 gregl 2.19 fprintf(stderr, "Or use WWxHH size specification\n");
293 greg 2.1 exit(1);
294     }
295    
296    
297 schorsch 2.28 static void
298     quiterr( /* print message and exit */
299     char *err
300     )
301 greg 2.1 {
302     if (err != NULL) {
303     fprintf(stderr, "%s: %s\n", progname, err);
304     exit(1);
305     }
306     exit(0);
307     }
308    
309    
310 schorsch 2.28 static void
311     PSheader( /* print PostScript header */
312     int ac,
313     char **av
314     )
315 greg 2.1 {
316 greg 2.15 char *rstr;
317 gregl 2.20 int landscape, rotate, n;
318 greg 2.6 double pwidth, pheight;
319     double iwidth, iheight;
320 greg 2.10 /* EPS comments */
321 greg 2.11 puts("%!PS-Adobe-2.0 EPSF-2.0");
322 gwlarson 2.21 printf("%%%%Title: "); printargs(ac, av, stdout);
323 greg 2.24 printf("%%%%Creator: %s\n", progname);
324 greg 2.4 printf("%%%%Pages: %d\n", ncopies);
325 schorsch 2.26 if ( (landscape = xmax > pixaspect*ymax) )
326 greg 2.10 puts("%%Orientation: Landscape");
327 greg 2.1 else
328 greg 2.10 puts("%%Orientation: Portrait");
329 schorsch 2.26 if ( (rotate = (PWIDTH > PHEIGHT) ^ landscape) ) {
330 greg 2.1 pwidth = PHEIGHT;
331     pheight = PWIDTH;
332     } else {
333     pwidth = PWIDTH;
334     pheight = PHEIGHT;
335     }
336 schorsch 2.26 if (dpi > 100 && (pixaspect >= 0.99) & (pixaspect <= 1.01))
337 gregl 2.20 if (pheight/pwidth > ymax/xmax) {
338     n = pwidth*dpi/xmax; /* floor */
339     iwidth = n > 0 ? (double)(n*xmax)/dpi : pwidth;
340     iheight = iwidth*ymax/xmax;
341     } else {
342     n = pheight*dpi/ymax; /* floor */
343     iheight = n > 0 ? (double)(n*ymax)/dpi : pheight;
344     iwidth = iheight*xmax/ymax;
345     }
346     else
347     if (pheight/pwidth > pixaspect*ymax/xmax) {
348     iwidth = pwidth;
349     iheight = iwidth*pixaspect*ymax/xmax;
350     } else {
351     iheight = pheight;
352     iwidth = iheight*xmax/(pixaspect*ymax);
353     }
354     if (rotate)
355 greg 2.10 printf("%%%%BoundingBox: %.0f %.0f %.0f %.0f\n",
356     HMARGIN+(pheight-iheight)*.5,
357     VMARGIN+(pwidth-iwidth)*.5,
358     HMARGIN+(pheight-iheight)*.5+iheight,
359     VMARGIN+(pwidth-iwidth)*.5+iwidth);
360     else
361     printf("%%%%BoundingBox: %.0f %.0f %.0f %.0f\n",
362     HMARGIN+(pwidth-iwidth)*.5,
363     VMARGIN+(pheight-iheight)*.5,
364     HMARGIN+(pwidth-iwidth)*.5+iwidth,
365     VMARGIN+(pheight-iheight)*.5+iheight);
366     puts("%%EndComments");
367 greg 2.13 puts("gsave save");
368 greg 2.15 puts("17 dict begin");
369 greg 2.10 /* define image reader */
370 greg 2.11 if (docolor) {
371     printf("/redline %d string def\n", xmax);
372     printf("/grnline %d string def\n", xmax);
373     printf("/bluline %d string def\n", xmax);
374 greg 2.15 } else
375     printf("/gryline %d string def\n", xmax);
376     /* use compressed encoding? */
377     if (putprim == Cputprim)
378     PSprocdef("read6bitRLE");
379 greg 2.10 /* set up transformation matrix */
380     printf("%f %f translate\n", HMARGIN, VMARGIN);
381 gregl 2.20 if (rotate) {
382 greg 2.14 printf("%f 0 translate\n", PWIDTH);
383     puts("90 rotate");
384 greg 2.10 }
385 greg 2.2 printf("%f %f translate\n", (pwidth-iwidth)*.5, (pheight-iheight)*.5);
386     printf("%f %f scale\n", iwidth, iheight);
387 greg 2.12 puts("%%EndProlog");
388 greg 2.3 /* start image procedure */
389 greg 2.15 printf("%d %d 8 [%d 0 0 %d 0 %d]\n", xmax, ymax, xmax, -ymax, ymax);
390     if (putprim == Cputprim) {
391     if (docolor) {
392 greg 2.16 puts("{redline read6bitRLE}");
393     puts("{grnline read6bitRLE}");
394     puts("{bluline read6bitRLE}");
395     puts("true 3 colorimage");
396 greg 2.15 } else
397     puts("{gryline read6bitRLE} image");
398     } else {
399     rstr = putprim==Aputprim ? "readhexstring" : "readstring";
400     if (docolor) {
401     printf("{currentfile redline %s pop}\n", rstr);
402     printf("{currentfile grnline %s pop}\n", rstr);
403     printf("{currentfile bluline %s pop}\n", rstr);
404     puts("true 3 colorimage");
405     } else
406     printf("{currentfile gryline %s pop} image\n", rstr);
407     }
408 greg 2.1 }
409    
410    
411 schorsch 2.28 static void
412     PStrailer(void) /* print PostScript trailer */
413 greg 2.1 {
414     puts("%%Trailer");
415 greg 2.4 if (ncopies > 1)
416     printf("/#copies %d def\n", ncopies);
417     puts("showpage");
418 greg 2.1 puts("end");
419 greg 2.13 puts("restore grestore");
420 greg 2.1 puts("%%EOF");
421     }
422    
423    
424 schorsch 2.28 static void
425     PSprocdef( /* define PS procedure to read image */
426     char *nam
427     )
428 greg 2.1 {
429     short itab[128];
430     register int i;
431 greg 2.5 /* assign code values */
432     for (i = 0; i < 128; i++) /* clear */
433 greg 2.1 itab[i] = -1;
434 greg 2.5 for (i = 1; i < 63; i++) /* assign greys */
435 schorsch 2.28 itab[(int)code[i]] = 256.0*pow((i+.5)/64.0, CODE6GAM/devgam);
436     itab[(int)code[0]] = 0; /* black is black */
437     itab[(int)code[63]] = 255; /* and white is white */
438 greg 2.9 printf("/codetab [");
439 greg 2.1 for (i = 0; i < 128; i++) {
440     if (!(i & 0xf))
441     putchar('\n');
442     printf(" %3d", itab[i]);
443     }
444     printf("\n] def\n");
445 greg 2.9 printf("/nrept 0 def\n");
446 greg 2.11 printf("/readbyte { currentfile read not {stop} if } bind def\n");
447     printf("/decode { codetab exch get } bind def\n");
448     printf("/%s {\t%% scanbuffer\n", nam);
449     printf("\t/scanline exch def\n");
450 greg 2.1 printf("\t{ 0 1 %d { scanline exch\n", xmax-1);
451 greg 2.9 printf("\t\tnrept 0 le\n");
452     printf("\t\t\t{ { readbyte dup %d eq\n", RUNCHR);
453     printf("\t\t\t\t\t{ pop /nrept readbyte %d sub def\n", RSTRT-MINRUN+1);
454     printf("\t\t\t\t\t\t/reptv readbyte decode def\n");
455     printf("\t\t\t\t\t\treptv exit }\n");
456     printf("\t\t\t\t\t{ decode dup 0 lt {pop} {exit} ifelse }\n");
457     printf("\t\t\t\tifelse } loop }\n");
458     printf("\t\t\t{ /nrept nrept 1 sub def reptv }\n");
459     printf("\t\tifelse put\n");
460     printf("\t\t} for\n");
461     printf("\t} stopped {pop pop 0 string} {scanline} ifelse\n");
462 greg 2.8 printf("} bind def\n");
463 greg 2.1 }
464    
465    
466 schorsch 2.28 static void
467     ra2ps(void) /* convert Radiance scanlines to 6-bit */
468 greg 2.1 {
469 greg 2.9 register COLR *scanin;
470 greg 2.1 int y;
471     /* allocate scanline */
472     scanin = (COLR *)malloc(xmax*sizeof(COLR));
473     if (scanin == NULL)
474     quiterr("out of memory in ra2ps");
475     /* convert image */
476     for (y = ymax-1; y >= 0; y--) {
477     if (freadcolrs(scanin, xmax, stdin) < 0)
478     quiterr("error reading Radiance picture");
479 gregl 2.17 if (putprim == Cputprim || devgam != 1.) {
480 greg 2.15 if (bradj) /* adjust exposure */
481     shiftcolrs(scanin, xmax, bradj);
482     colrs_gambs(scanin, xmax); /* gamma compression */
483     } else
484     normcolrs(scanin, xmax, bradj);
485 greg 2.11 if (docolor) {
486 greg 2.15 (*putprim)(scanin, RED);
487     (*putprim)(scanin, GRN);
488     (*putprim)(scanin, BLU);
489 greg 2.11 } else
490 greg 2.15 (*putprim)(scanin, GRY);
491 greg 2.1 if (ferror(stdout))
492     quiterr("error writing PostScript file");
493     }
494     putchar('\n');
495     /* free scanline */
496 greg 2.24 free((void *)scanin);
497 greg 2.11 }
498    
499    
500 schorsch 2.28 static void
501     Aputprim( /* put out hex ASCII primary from scanline */
502     COLR *scn,
503     int pri
504     )
505 greg 2.15 {
506     static char hexdigit[] = "0123456789ABCDEF";
507     static int col = 0;
508     register int x, c;
509    
510     for (x = 0; x < xmax; x++) {
511     if (pri == GRY)
512     c = normbright(scn[x]);
513     else
514     c = scn[x][pri];
515     if (c > 255) c = 255;
516     putchar(hexdigit[c>>4]);
517     putchar(hexdigit[c&0xf]);
518     if ((col += 2) >= 72) {
519     putchar('\n');
520     col = 0;
521     }
522     }
523     }
524    
525    
526 schorsch 2.28 static void
527     Bputprim( /* put out binary primary from scanline */
528     COLR *scn,
529     int pri
530     )
531 greg 2.15 {
532     register int x, c;
533    
534     for (x = 0; x < xmax; x++) {
535     if (pri == GRY)
536     c = normbright(scn[x]);
537     else
538     c = scn[x][pri];
539     if (c > 255) c = 255;
540     putchar(c);
541     }
542     }
543    
544    
545 schorsch 2.28 static void
546     Cputprim( /* put out compressed primary from scanline */
547     COLR *scn,
548     int pri
549     )
550 greg 2.11 {
551     register int c;
552     register int x;
553     int lastc, cnt;
554    
555     lastc = -1; cnt = 0;
556     for (x = 0; x < xmax; x++) {
557     if (pri == GRY)
558     c = normbright(scn[x]) + 2;
559     else
560     c = scn[x][pri] + 2;
561     if (c > 255) c = 255;
562     c = code[c>>2];
563     if (c == lastc && cnt < MAXRUN)
564     cnt++;
565     else {
566     putrle(cnt, lastc);
567     lastc = c;
568     cnt = 1;
569     }
570     }
571     putrle(cnt, lastc);
572 greg 2.9 }
573    
574    
575 schorsch 2.28 static void
576     putrle( /* put out cnt of cod */
577     register int cnt,
578     register int cod
579     )
580 greg 2.9 {
581     static int col = 0;
582    
583     if (cnt >= MINRUN) {
584     col += 3;
585     putchar(RUNCHR);
586     putchar(RSTRT-MINRUN+cnt);
587     putchar(cod);
588     } else {
589     col += cnt;
590     while (cnt-- > 0)
591     putchar(cod);
592     }
593     if (col >= 72) {
594     putchar('\n');
595     col = 0;
596     }
597 greg 2.1 }