Debian Codegraph @

texk/xdvipsk/thirdparty/libtiff/tools/fax2ps.c

raw
1 /*
2 * Copyright (c) 1991-1997 Sam Leffler
3 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
4 *
5 * Permission to use, copy, modify, distribute, and sell this software and
6 * its documentation for any purpose is hereby granted without fee, provided
7 * that (i) the above copyright notices and this permission notice appear in
8 * all copies of the software and related documentation, and (ii) the names of
9 * Sam Leffler and Silicon Graphics may not be used in any advertising or
10 * publicity relating to the software without the specific, prior written
11 * permission of Sam Leffler and Silicon Graphics.
12 *
13 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
14 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
15 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
16 *
17 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
18 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
19 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
21 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
22 * OF THIS SOFTWARE.
23 */
24 #include "libport.h"
25 #include "tif_config.h"
26
27 #include <math.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <time.h>
32
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36
37 #ifdef HAVE_FCNTL_H
38 #include <fcntl.h>
39 #endif
40
41 #ifdef HAVE_IO_H
42 #include <io.h>
43 #endif
44
45 #include "tiffio.h"
46 #include "tiffiop.h"
47
48 #ifndef EXIT_SUCCESS
49 #define EXIT_SUCCESS 0
50 #endif
51 #ifndef EXIT_FAILURE
52 #define EXIT_FAILURE 1
53 #endif
54
55 float defxres = 204.; /* default x resolution (pixels/inch) */
56 float defyres = 98.; /* default y resolution (lines/inch) */
57 const float half = 0.5;
58 const float points = 72.0;
59 float pageWidth = 0; /* image page width (inches) */
60 float pageHeight = 0; /* image page length (inches) */
61 int scaleToPage = 0; /* if true, scale raster to page dimensions */
62 int totalPages = 0; /* total # pages printed */
63 int row; /* current output row */
64 int maxline = 512; /* max output line of PostScript */
65
66 /*
67 * Turn a bit-mapped scanline into the appropriate sequence
68 * of PostScript characters to be rendered.
69 *
70 * Original version written by Bret D. Whissel,
71 * Florida State University Meteorology Department
72 * March 13-15, 1995.
73 */
74 static void printruns(unsigned char *buf, uint32_t *runs, uint32_t *erun,
75 uint32_t lastx)
76 {
77 static struct
78 {
79 char white, black;
80 unsigned short width;
81 } WBarr[] = {{'d', 'n', 512}, {'e', 'o', 256}, {'f', 'p', 128},
82 {'g', 'q', 64}, {'h', 'r', 32}, {'i', 's', 16},
83 {'j', 't', 8}, {'k', 'u', 4}, {'l', 'v', 2},
84 {'m', 'w', 1}};
85 static char *svalue =
86 " !\"#$&'*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abc";
87 int colormode = 1; /* 0 for white, 1 for black */
88 uint32_t runlength = 0;
89 int n = maxline;
90 uint32_t x = 0;
91 int l;
92
93 (void)buf;
94 printf("%d m(", row++);
95 while (runs < erun)
96 {
97 if (runlength <= 0)
98 {
99 colormode ^= 1;
100 runlength = *runs++;
101 if (x + runlength > lastx)
102 runlength = runs[-1] = lastx - x;
103 x += runlength;
104 if (!colormode && runs == erun)
105 break; /* don't bother printing the final white run */
106 }
107 /*
108 * If a runlength is greater than 6 pixels, then spit out
109 * black or white characters until the runlength drops to
110 * 6 or less. Once a runlength is <= 6, then combine black
111 * and white runlengths until a 6-pixel pattern is obtained.
112 * Then write out the special character. Six-pixel patterns
113 * were selected since 64 patterns is the largest power of
114 * two less than the 92 "easily printable" PostScript
115 * characters (i.e., no escape codes or octal chars).
116 */
117 l = 0;
118 while (runlength > 6)
119 { /* Run is greater than six... */
120 if (runlength >= WBarr[l].width)
121 {
122 if (n == 0)
123 {
124 putchar('\n');
125 n = maxline;
126 }
127 putchar(colormode ? WBarr[l].black : WBarr[l].white), n--;
128 runlength -= WBarr[l].width;
129 }
130 else
131 l++;
132 }
133 while (runlength > 0 && runlength <= 6)
134 {
135 uint32_t bitsleft = 6;
136 int t = 0;
137 while (bitsleft)
138 {
139 if (runlength <= bitsleft)
140 {
141 if (colormode)
142 t |= ((1 << runlength) - 1) << (bitsleft - runlength);
143 bitsleft -= runlength;
144 runlength = 0;
145 if (bitsleft)
146 {
147 if (runs >= erun)
148 break;
149 colormode ^= 1;
150 runlength = *runs++;
151 if (x + runlength > lastx)
152 runlength = runs[-1] = lastx - x;
153 x += runlength;
154 }
155 }
156 else
157 { /* runlength exceeds bits left */
158 if (colormode)
159 t |= ((1 << bitsleft) - 1);
160 runlength -= bitsleft;
161 bitsleft = 0;
162 }
163 }
164 if (n == 0)
165 {
166 putchar('\n');
167 n = maxline;
168 }
169 putchar(svalue[t]), n--;
170 }
171 }
172 printf(")s\n");
173 }
174
175 /*
176 * Create a special PostScript font for printing FAX documents. By taking
177 * advantage of the font-cacheing mechanism, a substantial speed-up in
178 * rendering time is realized.
179 */
180 static void emitFont(FILE *fd)
181 {
182 static const char *fontPrologue[] = {
183 "/newfont 10 dict def newfont begin /FontType 3 def /FontMatrix [1",
184 "0 0 1 0 0] def /FontBBox [0 0 512 1] def /Encoding 256 array def",
185 "0 1 31{Encoding exch /255 put}for 120 1 255{Encoding exch /255",
186 "put}for Encoding 37 /255 put Encoding 40 /255 put Encoding 41 /255",
187 "put Encoding 92 /255 put /count 0 def /ls{Encoding exch count 3",
188 "string cvs cvn put /count count 1 add def}def 32 1 36{ls}for",
189 "38 1 39{ls}for 42 1 91{ls}for 93 1 99{ls}for /count 100",
190 "def 100 1 119{ls}for /CharDict 5 dict def CharDict begin /white",
191 "{dup 255 eq{pop}{1 dict begin 100 sub neg 512 exch bitshift",
192 "/cw exch def cw 0 0 0 cw 1 setcachedevice end}ifelse}def /black",
193 "{dup 255 eq{pop}{1 dict begin 110 sub neg 512 exch bitshift",
194 "/cw exch def cw 0 0 0 cw 1 setcachedevice 0 0 moveto cw 0 rlineto",
195 "0 1 rlineto cw neg 0 rlineto closepath fill end}ifelse}def /numbuild",
196 "{dup 255 eq{pop}{6 0 0 0 6 1 setcachedevice 0 1 5{0 moveto",
197 "dup 32 and 32 eq{1 0 rlineto 0 1 rlineto -1 0 rlineto closepath",
198 "fill newpath}if 1 bitshift}for pop}ifelse}def /.notdef {}",
199 "def /255 {}def end /BuildChar{exch begin dup 110 ge{Encoding",
200 "exch get 3 string cvs cvi CharDict /black get}{dup 100 ge {Encoding",
201 "exch get 3 string cvs cvi CharDict /white get}{Encoding exch get",
202 "3 string cvs cvi CharDict /numbuild get}ifelse}ifelse exec end",
203 "}def end /Bitfont newfont definefont 1 scalefont setfont",
204 NULL};
205 int i;
206 for (i = 0; fontPrologue[i] != NULL; i++)
207 fprintf(fd, "%s\n", fontPrologue[i]);
208 }
209
210 void printTIF(TIFF *tif, uint16_t pageNumber)
211 {
212 uint32_t w, h;
213 uint16_t unit, compression;
214 float xres, yres, scale = 1.0;
215 tstrip_t s, ns;
216 time_t creation_time;
217
218 TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
219 TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
220 if (!TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression) ||
221 compression < COMPRESSION_CCITTRLE ||
222 compression > COMPRESSION_CCITT_T6)
223 return;
224 if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres) || !xres)
225 {
226 TIFFWarning(TIFFFileName(tif), "No x-resolution, assuming %g dpi",
227 defxres);
228 xres = defxres;
229 }
230 if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres) || !yres)
231 {
232 TIFFWarning(TIFFFileName(tif), "No y-resolution, assuming %g lpi",
233 defyres);
234 yres = defyres; /* XXX */
235 }
236 if (TIFFGetField(tif, TIFFTAG_RESOLUTIONUNIT, &unit) &&
237 unit == RESUNIT_CENTIMETER)
238 {
239 xres *= 2.54F;
240 yres *= 2.54F;
241 }
242 if (pageWidth == 0)
243 pageWidth = w / xres;
244 if (pageHeight == 0)
245 pageHeight = h / yres;
246
247 printf("%%!PS-Adobe-3.0\n");
248 printf("%%%%Creator: fax2ps\n");
249 #ifdef notdef
250 printf("%%%%Title: %s\n", file);
251 #endif
252 creation_time = time(0);
253 printf("%%%%CreationDate: %s", ctime(&creation_time));
254 printf("%%%%Origin: 0 0\n");
255 printf("%%%%BoundingBox: 0 0 %u %u\n", (int)(pageWidth * points),
256 (int)(pageHeight * points)); /* XXX */
257 printf("%%%%Pages: (atend)\n");
258 printf("%%%%EndComments\n");
259 printf("%%%%BeginProlog\n");
260 emitFont(stdout);
261 printf("/d{bind def}def\n"); /* bind and def proc */
262 printf("/m{0 exch moveto}d\n");
263 printf("/s{show}d\n");
264 printf("/p{showpage}d \n"); /* end page */
265 printf("%%%%EndProlog\n");
266 printf("%%%%Page: \"%u\" %u\n", pageNumber, pageNumber);
267 printf("/$pageTop save def gsave\n");
268 if (scaleToPage)
269 scale = pageHeight / (h / yres) < pageWidth / (w / xres)
270 ? pageHeight / (h / yres)
271 : pageWidth / (w / xres);
272 printf("%g %g translate\n", points * (pageWidth - scale * w / xres) * half,
273 points *
274 (scale * h / yres + (pageHeight - scale * h / yres) * half));
275 printf("%g %g scale\n", points / xres * scale, -points / yres * scale);
276 printf("0 setgray\n");
277 TIFFSetField(tif, TIFFTAG_FAXFILLFUNC, printruns);
278 ns = TIFFNumberOfStrips(tif);
279 row = 0;
280 for (s = 0; s < ns; s++)
281 (void)TIFFReadEncodedStrip(tif, s, (tdata_t)NULL, (tsize_t)-1);
282 printf("p\n");
283 printf("grestore $pageTop restore\n");
284 totalPages++;
285 }
286
287 #define GetPageNumber(tif) TIFFGetField(tif, TIFFTAG_PAGENUMBER, &pn, &ptotal)
288
289 int findPage(TIFF *tif, uint16_t pageNumber)
290 {
291 uint16_t pn = (uint16_t)-1;
292 uint16_t ptotal = (uint16_t)-1;
293 if (GetPageNumber(tif))
294 {
295 while (pn != (pageNumber - 1) && TIFFReadDirectory(tif) &&
296 GetPageNumber(tif))
297 ;
298 return (pn == (pageNumber - 1));
299 }
300 else
301 return (TIFFSetDirectory(tif, (tdir_t)(pageNumber - 1)));
302 }
303
304 void fax2ps(TIFF *tif, uint16_t npages, uint16_t *pages, char *filename)
305 {
306 if (npages > 0)
307 {
308 uint16_t pn, ptotal;
309 int i;
310
311 if (!GetPageNumber(tif))
312 fprintf(stderr, "%s: No page numbers, counting directories.\n",
313 filename);
314 for (i = 0; i < npages; i++)
315 {
316 if (findPage(tif, pages[i]))
317 printTIF(tif, pages[i]);
318 else
319 fprintf(stderr, "%s: No page number %d\n", filename, pages[i]);
320 }
321 }
322 else
323 {
324 uint16_t pageNumber = 0;
325 do
326 printTIF(tif, pageNumber++);
327 while (TIFFReadDirectory(tif));
328 }
329 }
330
331 #undef GetPageNumber
332
333 static int pcompar(const void *va, const void *vb)
334 {
335 const uint16_t *pa = (const uint16_t *)va;
336 const uint16_t *pb = (const uint16_t *)vb;
337 return ((int32_t)*pa - (int32_t)*pb);
338 }
339
340 static void usage(int code);
341
342 int main(int argc, char **argv)
343 {
344 #if !HAVE_DECL_OPTARG
345 extern int optind;
346 extern char *optarg;
347 #endif
348 uint16_t *pages = NULL, npages = 0, pageNumber;
349 int c, dowarnings = 0; /* if 1, enable library warnings */
350 TIFF *tif;
351
352 while ((c = getopt(argc, argv, "l:p:x:y:W:H:wSh")) != -1)
353 switch (c)
354 {
355 case 'H': /* page height */
356 pageHeight = (float)atof(optarg);
357 break;
358 case 'S': /* scale to page */
359 scaleToPage = 1;
360 break;
361 case 'W': /* page width */
362 pageWidth = (float)atof(optarg);
363 break;
364 case 'p': /* print specific page */
365 pageNumber = (uint16_t)atoi(optarg);
366 if (pages)
367 pages = (uint16_t *)realloc(pages, (npages + 1) *
368 sizeof(uint16_t));
369 else
370 pages = (uint16_t *)malloc(sizeof(uint16_t));
371 if (pages == NULL)
372 {
373 fprintf(stderr, "Out of memory\n");
374 exit(EXIT_FAILURE);
375 }
376 pages[npages++] = pageNumber;
377 break;
378 case 'w':
379 dowarnings = 1;
380 break;
381 case 'x':
382 defxres = (float)atof(optarg);
383 break;
384 case 'y':
385 defyres = (float)atof(optarg);
386 break;
387 case 'l':
388 maxline = atoi(optarg);
389 break;
390 case 'h':
391 free(pages);
392 usage(EXIT_SUCCESS);
393 break;
394 case '?':
395 free(pages);
396 usage(EXIT_FAILURE);
397 }
398 if (npages > 0)
399 qsort(pages, npages, sizeof(uint16_t), pcompar);
400 if (!dowarnings)
401 TIFFSetWarningHandler(0);
402 if (optind < argc)
403 {
404 do
405 {
406 tif = TIFFOpen(argv[optind], "r");
407 if (tif)
408 {
409 fax2ps(tif, npages, pages, argv[optind]);
410 TIFFClose(tif);
411 }
412 else
413 fprintf(stderr, "%s: Can not open, or not a TIFF file.\n",
414 argv[optind]);
415 } while (++optind < argc);
416 }
417 else
418 {
419 int n;
420 FILE *fd;
421 char buf[16 * 1024];
422
423 fd = tmpfile();
424 if (fd == NULL)
425 {
426 fprintf(stderr, "Could not obtain temporary file.\n");
427 free(pages);
428 exit(EXIT_FAILURE);
429 }
430 #if defined(HAVE_SETMODE) && defined(O_BINARY)
431 setmode(fileno(stdin), O_BINARY);
432 #endif
433 while ((n = read(fileno(stdin), buf, sizeof(buf))) > 0)
434 {
435 if (write(fileno(fd), buf, n) != n)
436 {
437 fclose(fd);
438 fprintf(stderr, "Could not copy stdin to temporary file.\n");
439 free(pages);
440 exit(EXIT_FAILURE);
441 }
442 }
443 _TIFF_lseek_f(fileno(fd), 0, SEEK_SET);
444 #if defined(_WIN32) && defined(USE_WIN32_FILEIO)
445 tif = TIFFFdOpen(_get_osfhandle(fileno(fd)), "temp", "r");
446 #else
447 tif = TIFFFdOpen(fileno(fd), "temp", "r");
448 #endif
449 if (tif)
450 {
451 fax2ps(tif, npages, pages, "<stdin>");
452 TIFFClose(tif);
453 }
454 else
455 fprintf(stderr, "Can not open, or not a TIFF file.\n");
456 fclose(fd);
457 }
458 printf("%%%%Trailer\n");
459 printf("%%%%Pages: %u\n", totalPages);
460 printf("%%%%EOF\n");
461
462 free(pages);
463 return (EXIT_SUCCESS);
464 }
465
466 static const char usage_info[] =
467 "Convert a TIFF facsimile to compressed PostScript\n\n"
468 "usage: fax2ps [options] [input.tif ...]\n"
469 "where options are:\n"
470 " -w suppress warning messages\n"
471 " -l chars set maximum output line length for generated PostScript\n"
472 " -p page# select page to print (can use multiple times)\n"
473 " -x xres set default horizontal resolution of input data (dpi)\n"
474 " -y yres set default vertical resolution of input data (lpi)\n"
475 " -S scale output to page size\n"
476 " -W width set output page width (inches), default is 8.5\n"
477 " -H height set output page height (inches), default is 11\n";
478
479 static void usage(int code)
480 {
481 FILE *out = (code == EXIT_SUCCESS) ? stdout : stderr;
482
483 fprintf(out, "%s\n\n", TIFFGetVersion());
484 fprintf(out, "%s", usage_info);
485 exit(code);
486 }