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

# Content
1 #ifndef lint
2 static const char RCSid[] = "$Id: ra_ps.c,v 2.29 2018/03/20 18:45:04 greg Exp $";
3 #endif
4 /*
5 * Radiance picture to PostScript file translator -- one way!
6 */
7
8 #include <stdio.h>
9 #include <string.h>
10 #include <math.h>
11 #include <ctype.h>
12
13 #include "platform.h"
14 #include "rtio.h"
15 #include "color.h"
16 #include "resolu.h"
17
18 #define UPPER(c) ((c)&~0x20) /* ASCII trick */
19
20 #define CODE6GAM 1.47 /* gamma for 6-bit codes */
21 #define DEFGGAM 1.0 /* greyscale device gamma */
22 #define DEFCGAM 1.8 /* color device gamma */
23
24 #define GRY -1 /* artificial index for grey */
25
26 #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
34 #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 char code[] = /* 6-bit code lookup table */
40 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@+";
41
42 int wrongformat = 0; /* input in wrong format? */
43 double pixaspect = 1.0; /* pixel aspect ratio */
44
45 double devgam = 0.; /* device gamma response */
46 double hmarg = DEFMARG,
47 vmarg = DEFMARG; /* horizontal and vertical margins */
48 double width = DEFWIDTH,
49 height = DEFHEIGHT; /* default paper width and height */
50 double dpi = 0; /* print density (0 if unknown) */
51 int docolor = 1; /* produce color image? */
52 int bradj = 0; /* brightness adjustment */
53 int ncopies = 1; /* number of copies */
54
55 char *progname;
56 int xmax, ymax; /* input image dimensions */
57
58 typedef void putprimf_t(COLR *scn, int pri);
59
60 static gethfunc headline;
61 static putprimf_t Aputprim, Bputprim, Cputprim;
62
63 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
73
74 putprimf_t *putprim = Aputprim; /* function for writing scanline */
75
76
77 static int
78 headline( /* check header line */
79 char *s,
80 void *p
81 )
82 {
83 char fmt[MAXFMTLEN];
84
85 if (isformat(s)) {
86 formatval(fmt, s);
87 wrongformat = strcmp(fmt, COLRFMT);
88 } else if (isaspect(s))
89 pixaspect *= aspectval(s);
90 return(0);
91 }
92
93 int
94 main(int argc, char *argv[])
95 {
96 int i;
97 double d;
98
99 progname = argv[0];
100
101 for (i = 1; i < argc; i++)
102 if (argv[i][0] == '-')
103 switch (argv[i][1]) {
104 case 'b': /* produce b&w PostScript */
105 docolor = 0;
106 break;
107 case 'c': /* produce color PostScript */
108 docolor = 1;
109 break;
110 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 case 'd': /* print density */
120 dpi = atof(argv[++i]);
121 break;
122 case 'g': /* device gamma adjustment */
123 devgam = atof(argv[++i]);
124 break;
125 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 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 case 'n': /* number of copies */
152 ncopies = atoi(argv[++i]);
153 break;
154 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 fprintf(stderr, "%s: can't open output \"%s\"\n",
169 progname, argv[i+1]);
170 exit(1);
171 }
172 SET_FILE_BINARY(stdin);
173 /* get our header */
174 getheader(stdin, headline, NULL);
175 if (wrongformat || fgetresolu(&xmax, &ymax, stdin) < 0)
176 quiterr("bad picture format");
177 /* gamma compression */
178 if (devgam <= 0.05)
179 devgam = docolor ? DEFCGAM : DEFGGAM;
180 if (putprim == Cputprim)
181 setcolrgam(CODE6GAM);
182 else if (devgam != 1.)
183 setcolrgam(devgam);
184 /* write header */
185 PSheader(argc, argv);
186 /* convert file */
187 ra2ps();
188 /* write trailer */
189 PStrailer();
190 exit(0);
191 userr:
192 fprintf(stderr,
193 "Usage: %s [-b|c][-A|B|C][-e +/-stops][-p paper][-m[h|v] margin][-d dpi][-g gamma] [input [output]]\n",
194 progname);
195 exit(1);
196 }
197
198
199 static double
200 unit2inch( /* determine unit */
201 register char *s
202 )
203 {
204 static struct unit {char n; float f;} u[] = {
205 {'i', 1.},
206 {'m', 1./25.4},
207 {'c', 1./2.54},
208 {'\0',0} };
209 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 static int
221 matchid( /* see if name matches id (case insensitive) */
222 char *name,
223 register char *id
224 )
225 {
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 static void
241 parsepaper( /* determine paper size from name */
242 char *ps
243 )
244 {
245 static struct psize {char n[12]; float w,h;} p[] = {
246 {"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 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 if ((width >= 1.) & (height >= 1.))
279 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 fprintf(stderr, "Or use WWxHH size specification\n");
293 exit(1);
294 }
295
296
297 static void
298 quiterr( /* print message and exit */
299 char *err
300 )
301 {
302 if (err != NULL) {
303 fprintf(stderr, "%s: %s\n", progname, err);
304 exit(1);
305 }
306 exit(0);
307 }
308
309
310 static void
311 PSheader( /* print PostScript header */
312 int ac,
313 char **av
314 )
315 {
316 char *rstr;
317 int landscape, rotate, n;
318 double pwidth, pheight;
319 double iwidth, iheight;
320 /* EPS comments */
321 puts("%!PS-Adobe-2.0 EPSF-2.0");
322 printf("%%%%Title: "); printargs(ac, av, stdout);
323 printf("%%%%Creator: %s\n", progname);
324 printf("%%%%Pages: %d\n", ncopies);
325 if ( (landscape = xmax > pixaspect*ymax) )
326 puts("%%Orientation: Landscape");
327 else
328 puts("%%Orientation: Portrait");
329 if ( (rotate = (PWIDTH > PHEIGHT) ^ landscape) ) {
330 pwidth = PHEIGHT;
331 pheight = PWIDTH;
332 } else {
333 pwidth = PWIDTH;
334 pheight = PHEIGHT;
335 }
336 if (dpi > 100 && (pixaspect >= 0.99) & (pixaspect <= 1.01))
337 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 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 puts("gsave save");
368 puts("17 dict begin");
369 /* define image reader */
370 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 } else
375 printf("/gryline %d string def\n", xmax);
376 /* use compressed encoding? */
377 if (putprim == Cputprim)
378 PSprocdef("read6bitRLE");
379 /* set up transformation matrix */
380 printf("%f %f translate\n", HMARGIN, VMARGIN);
381 if (rotate) {
382 printf("%f 0 translate\n", PWIDTH);
383 puts("90 rotate");
384 }
385 printf("%f %f translate\n", (pwidth-iwidth)*.5, (pheight-iheight)*.5);
386 printf("%f %f scale\n", iwidth, iheight);
387 puts("%%EndProlog");
388 /* start image procedure */
389 printf("%d %d 8 [%d 0 0 %d 0 %d]\n", xmax, ymax, xmax, -ymax, ymax);
390 if (putprim == Cputprim) {
391 if (docolor) {
392 puts("{redline read6bitRLE}");
393 puts("{grnline read6bitRLE}");
394 puts("{bluline read6bitRLE}");
395 puts("true 3 colorimage");
396 } 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 }
409
410
411 static void
412 PStrailer(void) /* print PostScript trailer */
413 {
414 puts("%%Trailer");
415 if (ncopies > 1)
416 printf("/#copies %d def\n", ncopies);
417 puts("showpage");
418 puts("end");
419 puts("restore grestore");
420 puts("%%EOF");
421 }
422
423
424 static void
425 PSprocdef( /* define PS procedure to read image */
426 char *nam
427 )
428 {
429 short itab[128];
430 register int i;
431 /* assign code values */
432 for (i = 0; i < 128; i++) /* clear */
433 itab[i] = -1;
434 for (i = 1; i < 63; i++) /* assign greys */
435 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 printf("/codetab [");
439 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 printf("/nrept 0 def\n");
446 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 printf("\t{ 0 1 %d { scanline exch\n", xmax-1);
451 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 printf("} bind def\n");
463 }
464
465
466 static void
467 ra2ps(void) /* convert Radiance scanlines to 6-bit */
468 {
469 register COLR *scanin;
470 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 if (putprim == Cputprim || devgam != 1.) {
480 if (bradj) /* adjust exposure */
481 shiftcolrs(scanin, xmax, bradj);
482 colrs_gambs(scanin, xmax); /* gamma compression */
483 } else
484 normcolrs(scanin, xmax, bradj);
485 if (docolor) {
486 (*putprim)(scanin, RED);
487 (*putprim)(scanin, GRN);
488 (*putprim)(scanin, BLU);
489 } else
490 (*putprim)(scanin, GRY);
491 if (ferror(stdout))
492 quiterr("error writing PostScript file");
493 }
494 putchar('\n');
495 /* free scanline */
496 free((void *)scanin);
497 }
498
499
500 static void
501 Aputprim( /* put out hex ASCII primary from scanline */
502 COLR *scn,
503 int pri
504 )
505 {
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 static void
527 Bputprim( /* put out binary primary from scanline */
528 COLR *scn,
529 int pri
530 )
531 {
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 static void
546 Cputprim( /* put out compressed primary from scanline */
547 COLR *scn,
548 int pri
549 )
550 {
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 }
573
574
575 static void
576 putrle( /* put out cnt of cod */
577 register int cnt,
578 register int cod
579 )
580 {
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 }