OSDN Git Service

#xxxxx DTXViewerのプロジェクトを追加。
[dtxmania/dtxmania.git] / DTXViewerプロジェクト / @jpeglibソリューション / jpeg-9b / djpeg.c
1 /*
2  * djpeg.c
3  *
4  * Copyright (C) 1991-1997, Thomas G. Lane.
5  * Modified 2009-2015 by Guido Vollbeding.
6  * This file is part of the Independent JPEG Group's software.
7  * For conditions of distribution and use, see the accompanying README file.
8  *
9  * This file contains a command-line user interface for the JPEG decompressor.
10  * It should work on any system with Unix- or MS-DOS-style command lines.
11  *
12  * Two different command line styles are permitted, depending on the
13  * compile-time switch TWO_FILE_COMMANDLINE:
14  *      djpeg [options]  inputfile outputfile
15  *      djpeg [options]  [inputfile]
16  * In the second style, output is always to standard output, which you'd
17  * normally redirect to a file or pipe to some other program.  Input is
18  * either from a named file or from standard input (typically redirected).
19  * The second style is convenient on Unix but is unhelpful on systems that
20  * don't support pipes.  Also, you MUST use the first style if your system
21  * doesn't do binary I/O to stdin/stdout.
22  * To simplify script writing, the "-outfile" switch is provided.  The syntax
23  *      djpeg [options]  -outfile outputfile  inputfile
24  * works regardless of which command line style is used.
25  */
26
27 #include "cdjpeg.h"             /* Common decls for cjpeg/djpeg applications */
28 #include "jversion.h"           /* for version message */
29
30 #include <ctype.h>              /* to declare isprint() */
31
32 #ifdef USE_CCOMMAND             /* command-line reader for Macintosh */
33 #ifdef __MWERKS__
34 #include <SIOUX.h>              /* Metrowerks needs this */
35 #include <console.h>            /* ... and this */
36 #endif
37 #ifdef THINK_C
38 #include <console.h>            /* Think declares it here */
39 #endif
40 #endif
41
42
43 /* Create the add-on message string table. */
44
45 #define JMESSAGE(code,string)   string ,
46
47 static const char * const cdjpeg_message_table[] = {
48 #include "cderror.h"
49   NULL
50 };
51
52
53 /*
54  * This list defines the known output image formats
55  * (not all of which need be supported by a given version).
56  * You can change the default output format by defining DEFAULT_FMT;
57  * indeed, you had better do so if you undefine PPM_SUPPORTED.
58  */
59
60 typedef enum {
61         FMT_BMP,                /* BMP format (Windows flavor) */
62         FMT_GIF,                /* GIF format */
63         FMT_OS2,                /* BMP format (OS/2 flavor) */
64         FMT_PPM,                /* PPM/PGM (PBMPLUS formats) */
65         FMT_RLE,                /* RLE format */
66         FMT_TARGA,              /* Targa format */
67         FMT_TIFF                /* TIFF format */
68 } IMAGE_FORMATS;
69
70 #ifndef DEFAULT_FMT             /* so can override from CFLAGS in Makefile */
71 #define DEFAULT_FMT     FMT_PPM
72 #endif
73
74 static IMAGE_FORMATS requested_fmt;
75
76
77 /*
78  * Argument-parsing code.
79  * The switch parser is designed to be useful with DOS-style command line
80  * syntax, ie, intermixed switches and file names, where only the switches
81  * to the left of a given file name affect processing of that file.
82  * The main program in this file doesn't actually use this capability...
83  */
84
85
86 static const char * progname;   /* program name for error messages */
87 static char * outfilename;      /* for -outfile switch */
88
89
90 LOCAL(void)
91 usage (void)
92 /* complain about bad command line */
93 {
94   fprintf(stderr, "usage: %s [switches] ", progname);
95 #ifdef TWO_FILE_COMMANDLINE
96   fprintf(stderr, "inputfile outputfile\n");
97 #else
98   fprintf(stderr, "[inputfile]\n");
99 #endif
100
101   fprintf(stderr, "Switches (names may be abbreviated):\n");
102   fprintf(stderr, "  -colors N      Reduce image to no more than N colors\n");
103   fprintf(stderr, "  -fast          Fast, low-quality processing\n");
104   fprintf(stderr, "  -grayscale     Force grayscale output\n");
105   fprintf(stderr, "  -rgb           Force RGB output\n");
106 #ifdef IDCT_SCALING_SUPPORTED
107   fprintf(stderr, "  -scale M/N     Scale output image by fraction M/N, eg, 1/8\n");
108 #endif
109 #ifdef BMP_SUPPORTED
110   fprintf(stderr, "  -bmp           Select BMP output format (Windows style)%s\n",
111           (DEFAULT_FMT == FMT_BMP ? " (default)" : ""));
112 #endif
113 #ifdef GIF_SUPPORTED
114   fprintf(stderr, "  -gif           Select GIF output format%s\n",
115           (DEFAULT_FMT == FMT_GIF ? " (default)" : ""));
116 #endif
117 #ifdef BMP_SUPPORTED
118   fprintf(stderr, "  -os2           Select BMP output format (OS/2 style)%s\n",
119           (DEFAULT_FMT == FMT_OS2 ? " (default)" : ""));
120 #endif
121 #ifdef PPM_SUPPORTED
122   fprintf(stderr, "  -pnm           Select PBMPLUS (PPM/PGM) output format%s\n",
123           (DEFAULT_FMT == FMT_PPM ? " (default)" : ""));
124 #endif
125 #ifdef RLE_SUPPORTED
126   fprintf(stderr, "  -rle           Select Utah RLE output format%s\n",
127           (DEFAULT_FMT == FMT_RLE ? " (default)" : ""));
128 #endif
129 #ifdef TARGA_SUPPORTED
130   fprintf(stderr, "  -targa         Select Targa output format%s\n",
131           (DEFAULT_FMT == FMT_TARGA ? " (default)" : ""));
132 #endif
133   fprintf(stderr, "Switches for advanced users:\n");
134 #ifdef DCT_ISLOW_SUPPORTED
135   fprintf(stderr, "  -dct int       Use integer DCT method%s\n",
136           (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
137 #endif
138 #ifdef DCT_IFAST_SUPPORTED
139   fprintf(stderr, "  -dct fast      Use fast integer DCT (less accurate)%s\n",
140           (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
141 #endif
142 #ifdef DCT_FLOAT_SUPPORTED
143   fprintf(stderr, "  -dct float     Use floating-point DCT method%s\n",
144           (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
145 #endif
146   fprintf(stderr, "  -dither fs     Use F-S dithering (default)\n");
147   fprintf(stderr, "  -dither none   Don't use dithering in quantization\n");
148   fprintf(stderr, "  -dither ordered  Use ordered dither (medium speed, quality)\n");
149 #ifdef QUANT_2PASS_SUPPORTED
150   fprintf(stderr, "  -map FILE      Map to colors used in named image file\n");
151 #endif
152   fprintf(stderr, "  -nosmooth      Don't use high-quality upsampling\n");
153 #ifdef QUANT_1PASS_SUPPORTED
154   fprintf(stderr, "  -onepass       Use 1-pass quantization (fast, low quality)\n");
155 #endif
156   fprintf(stderr, "  -maxmemory N   Maximum memory to use (in kbytes)\n");
157   fprintf(stderr, "  -outfile name  Specify name for output file\n");
158   fprintf(stderr, "  -verbose  or  -debug   Emit debug output\n");
159   exit(EXIT_FAILURE);
160 }
161
162
163 LOCAL(int)
164 parse_switches (j_decompress_ptr cinfo, int argc, char **argv,
165                 int last_file_arg_seen, boolean for_real)
166 /* Parse optional switches.
167  * Returns argv[] index of first file-name argument (== argc if none).
168  * Any file names with indexes <= last_file_arg_seen are ignored;
169  * they have presumably been processed in a previous iteration.
170  * (Pass 0 for last_file_arg_seen on the first or only iteration.)
171  * for_real is FALSE on the first (dummy) pass; we may skip any expensive
172  * processing.
173  */
174 {
175   int argn;
176   char * arg;
177
178   /* Set up default JPEG parameters. */
179   requested_fmt = DEFAULT_FMT;  /* set default output file format */
180   outfilename = NULL;
181   cinfo->err->trace_level = 0;
182
183   /* Scan command line options, adjust parameters */
184
185   for (argn = 1; argn < argc; argn++) {
186     arg = argv[argn];
187     if (*arg != '-') {
188       /* Not a switch, must be a file name argument */
189       if (argn <= last_file_arg_seen) {
190         outfilename = NULL;     /* -outfile applies to just one input file */
191         continue;               /* ignore this name if previously processed */
192       }
193       break;                    /* else done parsing switches */
194     }
195     arg++;                      /* advance past switch marker character */
196
197     if (keymatch(arg, "bmp", 1)) {
198       /* BMP output format. */
199       requested_fmt = FMT_BMP;
200
201     } else if (keymatch(arg, "colors", 1) || keymatch(arg, "colours", 1) ||
202                keymatch(arg, "quantize", 1) || keymatch(arg, "quantise", 1)) {
203       /* Do color quantization. */
204       int val;
205
206       if (++argn >= argc)       /* advance to next argument */
207         usage();
208       if (sscanf(argv[argn], "%d", &val) != 1)
209         usage();
210       cinfo->desired_number_of_colors = val;
211       cinfo->quantize_colors = TRUE;
212
213     } else if (keymatch(arg, "dct", 2)) {
214       /* Select IDCT algorithm. */
215       if (++argn >= argc)       /* advance to next argument */
216         usage();
217       if (keymatch(argv[argn], "int", 1)) {
218         cinfo->dct_method = JDCT_ISLOW;
219       } else if (keymatch(argv[argn], "fast", 2)) {
220         cinfo->dct_method = JDCT_IFAST;
221       } else if (keymatch(argv[argn], "float", 2)) {
222         cinfo->dct_method = JDCT_FLOAT;
223       } else
224         usage();
225
226     } else if (keymatch(arg, "dither", 2)) {
227       /* Select dithering algorithm. */
228       if (++argn >= argc)       /* advance to next argument */
229         usage();
230       if (keymatch(argv[argn], "fs", 2)) {
231         cinfo->dither_mode = JDITHER_FS;
232       } else if (keymatch(argv[argn], "none", 2)) {
233         cinfo->dither_mode = JDITHER_NONE;
234       } else if (keymatch(argv[argn], "ordered", 2)) {
235         cinfo->dither_mode = JDITHER_ORDERED;
236       } else
237         usage();
238
239     } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
240       /* Enable debug printouts. */
241       /* On first -d, print version identification */
242       static boolean printed_version = FALSE;
243
244       if (! printed_version) {
245         fprintf(stderr, "Independent JPEG Group's DJPEG, version %s\n%s\n",
246                 JVERSION, JCOPYRIGHT);
247         printed_version = TRUE;
248       }
249       cinfo->err->trace_level++;
250
251     } else if (keymatch(arg, "fast", 1)) {
252       /* Select recommended processing options for quick-and-dirty output. */
253       cinfo->two_pass_quantize = FALSE;
254       cinfo->dither_mode = JDITHER_ORDERED;
255       if (! cinfo->quantize_colors) /* don't override an earlier -colors */
256         cinfo->desired_number_of_colors = 216;
257       cinfo->dct_method = JDCT_FASTEST;
258       cinfo->do_fancy_upsampling = FALSE;
259
260     } else if (keymatch(arg, "gif", 1)) {
261       /* GIF output format. */
262       requested_fmt = FMT_GIF;
263
264     } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
265       /* Force monochrome output. */
266       cinfo->out_color_space = JCS_GRAYSCALE;
267
268     } else if (keymatch(arg, "rgb", 3)) {
269       /* Force RGB output. */
270       cinfo->out_color_space = JCS_RGB;
271
272     } else if (keymatch(arg, "map", 3)) {
273       /* Quantize to a color map taken from an input file. */
274       if (++argn >= argc)       /* advance to next argument */
275         usage();
276       if (for_real) {           /* too expensive to do twice! */
277 #ifdef QUANT_2PASS_SUPPORTED    /* otherwise can't quantize to supplied map */
278         FILE * mapfile;
279
280         if ((mapfile = fopen(argv[argn], READ_BINARY)) == NULL) {
281           fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
282           exit(EXIT_FAILURE);
283         }
284         read_color_map(cinfo, mapfile);
285         fclose(mapfile);
286         cinfo->quantize_colors = TRUE;
287 #else
288         ERREXIT(cinfo, JERR_NOT_COMPILED);
289 #endif
290       }
291
292     } else if (keymatch(arg, "maxmemory", 3)) {
293       /* Maximum memory in Kb (or Mb with 'm'). */
294       long lval;
295       char ch = 'x';
296
297       if (++argn >= argc)       /* advance to next argument */
298         usage();
299       if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
300         usage();
301       if (ch == 'm' || ch == 'M')
302         lval *= 1000L;
303       cinfo->mem->max_memory_to_use = lval * 1000L;
304
305     } else if (keymatch(arg, "nosmooth", 3)) {
306       /* Suppress fancy upsampling. */
307       cinfo->do_fancy_upsampling = FALSE;
308
309     } else if (keymatch(arg, "onepass", 3)) {
310       /* Use fast one-pass quantization. */
311       cinfo->two_pass_quantize = FALSE;
312
313     } else if (keymatch(arg, "os2", 3)) {
314       /* BMP output format (OS/2 flavor). */
315       requested_fmt = FMT_OS2;
316
317     } else if (keymatch(arg, "outfile", 4)) {
318       /* Set output file name. */
319       if (++argn >= argc)       /* advance to next argument */
320         usage();
321       outfilename = argv[argn]; /* save it away for later use */
322
323     } else if (keymatch(arg, "pnm", 1) || keymatch(arg, "ppm", 1)) {
324       /* PPM/PGM output format. */
325       requested_fmt = FMT_PPM;
326
327     } else if (keymatch(arg, "rle", 1)) {
328       /* RLE output format. */
329       requested_fmt = FMT_RLE;
330
331     } else if (keymatch(arg, "scale", 1)) {
332       /* Scale the output image by a fraction M/N. */
333       if (++argn >= argc)       /* advance to next argument */
334         usage();
335       if (sscanf(argv[argn], "%u/%u",
336                  &cinfo->scale_num, &cinfo->scale_denom) < 1)
337         usage();
338
339     } else if (keymatch(arg, "targa", 1)) {
340       /* Targa output format. */
341       requested_fmt = FMT_TARGA;
342
343     } else {
344       usage();                  /* bogus switch */
345     }
346   }
347
348   return argn;                  /* return index of next arg (file name) */
349 }
350
351
352 /*
353  * Marker processor for COM and interesting APPn markers.
354  * This replaces the library's built-in processor, which just skips the marker.
355  * We want to print out the marker as text, to the extent possible.
356  * Note this code relies on a non-suspending data source.
357  */
358
359 LOCAL(unsigned int)
360 jpeg_getc (j_decompress_ptr cinfo)
361 /* Read next byte */
362 {
363   struct jpeg_source_mgr * datasrc = cinfo->src;
364
365   if (datasrc->bytes_in_buffer == 0) {
366     if (! (*datasrc->fill_input_buffer) (cinfo))
367       ERREXIT(cinfo, JERR_CANT_SUSPEND);
368   }
369   datasrc->bytes_in_buffer--;
370   return GETJOCTET(*datasrc->next_input_byte++);
371 }
372
373
374 METHODDEF(boolean)
375 print_text_marker (j_decompress_ptr cinfo)
376 {
377   boolean traceit = (cinfo->err->trace_level >= 1);
378   INT32 length;
379   unsigned int ch;
380   unsigned int lastch = 0;
381
382   length = jpeg_getc(cinfo) << 8;
383   length += jpeg_getc(cinfo);
384   length -= 2;                  /* discount the length word itself */
385
386   if (traceit) {
387     if (cinfo->unread_marker == JPEG_COM)
388       fprintf(stderr, "Comment, length %ld:\n", (long) length);
389     else                        /* assume it is an APPn otherwise */
390       fprintf(stderr, "APP%d, length %ld:\n",
391               cinfo->unread_marker - JPEG_APP0, (long) length);
392   }
393
394   while (--length >= 0) {
395     ch = jpeg_getc(cinfo);
396     if (traceit) {
397       /* Emit the character in a readable form.
398        * Nonprintables are converted to \nnn form,
399        * while \ is converted to \\.
400        * Newlines in CR, CR/LF, or LF form will be printed as one newline.
401        */
402       if (ch == '\r') {
403         fprintf(stderr, "\n");
404       } else if (ch == '\n') {
405         if (lastch != '\r')
406           fprintf(stderr, "\n");
407       } else if (ch == '\\') {
408         fprintf(stderr, "\\\\");
409       } else if (isprint(ch)) {
410         putc(ch, stderr);
411       } else {
412         fprintf(stderr, "\\%03o", ch);
413       }
414       lastch = ch;
415     }
416   }
417
418   if (traceit)
419     fprintf(stderr, "\n");
420
421   return TRUE;
422 }
423
424
425 /*
426  * The main program.
427  */
428
429 int
430 main (int argc, char **argv)
431 {
432   struct jpeg_decompress_struct cinfo;
433   struct jpeg_error_mgr jerr;
434 #ifdef PROGRESS_REPORT
435   struct cdjpeg_progress_mgr progress;
436 #endif
437   int file_index;
438   djpeg_dest_ptr dest_mgr = NULL;
439   FILE * input_file;
440   FILE * output_file;
441   JDIMENSION num_scanlines;
442
443   /* On Mac, fetch a command line. */
444 #ifdef USE_CCOMMAND
445   argc = ccommand(&argv);
446 #endif
447
448   progname = argv[0];
449   if (progname == NULL || progname[0] == 0)
450     progname = "djpeg";         /* in case C library doesn't provide it */
451
452   /* Initialize the JPEG decompression object with default error handling. */
453   cinfo.err = jpeg_std_error(&jerr);
454   jpeg_create_decompress(&cinfo);
455   /* Add some application-specific error messages (from cderror.h) */
456   jerr.addon_message_table = cdjpeg_message_table;
457   jerr.first_addon_message = JMSG_FIRSTADDONCODE;
458   jerr.last_addon_message = JMSG_LASTADDONCODE;
459
460   /* Insert custom marker processor for COM and APP12.
461    * APP12 is used by some digital camera makers for textual info,
462    * so we provide the ability to display it as text.
463    * If you like, additional APPn marker types can be selected for display,
464    * but don't try to override APP0 or APP14 this way (see libjpeg.doc).
465    */
466   jpeg_set_marker_processor(&cinfo, JPEG_COM, print_text_marker);
467   jpeg_set_marker_processor(&cinfo, JPEG_APP0+12, print_text_marker);
468
469   /* Now safe to enable signal catcher. */
470 #ifdef NEED_SIGNAL_CATCHER
471   enable_signal_catcher((j_common_ptr) &cinfo);
472 #endif
473
474   /* Scan command line to find file names. */
475   /* It is convenient to use just one switch-parsing routine, but the switch
476    * values read here are ignored; we will rescan the switches after opening
477    * the input file.
478    * (Exception: tracing level set here controls verbosity for COM markers
479    * found during jpeg_read_header...)
480    */
481
482   file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
483
484 #ifdef TWO_FILE_COMMANDLINE
485   /* Must have either -outfile switch or explicit output file name */
486   if (outfilename == NULL) {
487     if (file_index != argc-2) {
488       fprintf(stderr, "%s: must name one input and one output file\n",
489               progname);
490       usage();
491     }
492     outfilename = argv[file_index+1];
493   } else {
494     if (file_index != argc-1) {
495       fprintf(stderr, "%s: must name one input and one output file\n",
496               progname);
497       usage();
498     }
499   }
500 #else
501   /* Unix style: expect zero or one file name */
502   if (file_index < argc-1) {
503     fprintf(stderr, "%s: only one input file\n", progname);
504     usage();
505   }
506 #endif /* TWO_FILE_COMMANDLINE */
507
508   /* Open the input file. */
509   if (file_index < argc) {
510     if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
511       fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
512       exit(EXIT_FAILURE);
513     }
514   } else {
515     /* default input file is stdin */
516     input_file = read_stdin();
517   }
518
519   /* Open the output file. */
520   if (outfilename != NULL) {
521     if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
522       fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
523       exit(EXIT_FAILURE);
524     }
525   } else {
526     /* default output file is stdout */
527     output_file = write_stdout();
528   }
529
530 #ifdef PROGRESS_REPORT
531   start_progress_monitor((j_common_ptr) &cinfo, &progress);
532 #endif
533
534   /* Specify data source for decompression */
535   jpeg_stdio_src(&cinfo, input_file);
536
537   /* Read file header, set default decompression parameters */
538   (void) jpeg_read_header(&cinfo, TRUE);
539
540   /* Adjust default decompression parameters by re-parsing the options */
541   file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
542
543   /* Initialize the output module now to let it override any crucial
544    * option settings (for instance, GIF wants to force color quantization).
545    */
546   switch (requested_fmt) {
547 #ifdef BMP_SUPPORTED
548   case FMT_BMP:
549     dest_mgr = jinit_write_bmp(&cinfo, FALSE);
550     break;
551   case FMT_OS2:
552     dest_mgr = jinit_write_bmp(&cinfo, TRUE);
553     break;
554 #endif
555 #ifdef GIF_SUPPORTED
556   case FMT_GIF:
557     dest_mgr = jinit_write_gif(&cinfo);
558     break;
559 #endif
560 #ifdef PPM_SUPPORTED
561   case FMT_PPM:
562     dest_mgr = jinit_write_ppm(&cinfo);
563     break;
564 #endif
565 #ifdef RLE_SUPPORTED
566   case FMT_RLE:
567     dest_mgr = jinit_write_rle(&cinfo);
568     break;
569 #endif
570 #ifdef TARGA_SUPPORTED
571   case FMT_TARGA:
572     dest_mgr = jinit_write_targa(&cinfo);
573     break;
574 #endif
575   default:
576     ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT);
577     break;
578   }
579   dest_mgr->output_file = output_file;
580
581   /* Start decompressor */
582   (void) jpeg_start_decompress(&cinfo);
583
584   /* Write output file header */
585   (*dest_mgr->start_output) (&cinfo, dest_mgr);
586
587   /* Process data */
588   while (cinfo.output_scanline < cinfo.output_height) {
589     num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
590                                         dest_mgr->buffer_height);
591     (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
592   }
593
594 #ifdef PROGRESS_REPORT
595   /* Hack: count final pass as done in case finish_output does an extra pass.
596    * The library won't have updated completed_passes.
597    */
598   progress.pub.completed_passes = progress.pub.total_passes;
599 #endif
600
601   /* Finish decompression and release memory.
602    * I must do it in this order because output module has allocated memory
603    * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory.
604    */
605   (*dest_mgr->finish_output) (&cinfo, dest_mgr);
606   (void) jpeg_finish_decompress(&cinfo);
607   jpeg_destroy_decompress(&cinfo);
608
609   /* Close files, if we opened them */
610   if (input_file != stdin)
611     fclose(input_file);
612   if (output_file != stdout)
613     fclose(output_file);
614
615 #ifdef PROGRESS_REPORT
616   end_progress_monitor((j_common_ptr) &cinfo);
617 #endif
618
619   /* All done. */
620   exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
621   return 0;                     /* suppress no-return-value warnings */
622 }