4 * Copyright (C) 1991-1997, Thomas G. Lane.
5 * Copyright (C) 2010-2011, D. R. Commander.
6 * This file is part of the Independent JPEG Group's software.
7 * For conditions of distribution and use, see the accompanying README file.
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.
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.
27 #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
28 #include "jversion.h" /* for version message */
31 #include <ctype.h> /* to declare isprint() */
33 #ifdef USE_CCOMMAND /* command-line reader for Macintosh */
35 #include <SIOUX.h> /* Metrowerks needs this */
36 #include <console.h> /* ... and this */
39 #include <console.h> /* Think declares it here */
44 /* Create the add-on message string table. */
46 #define JMESSAGE(code,string) string ,
48 static const char * const cdjpeg_message_table[] = {
55 * This list defines the known output image formats
56 * (not all of which need be supported by a given version).
57 * You can change the default output format by defining DEFAULT_FMT;
58 * indeed, you had better do so if you undefine PPM_SUPPORTED.
62 FMT_BMP, /* BMP format (Windows flavor) */
63 FMT_GIF, /* GIF format */
64 FMT_OS2, /* BMP format (OS/2 flavor) */
65 FMT_PPM, /* PPM/PGM (PBMPLUS formats) */
66 FMT_RLE, /* RLE format */
67 FMT_TARGA, /* Targa format */
68 FMT_TIFF /* TIFF format */
71 #ifndef DEFAULT_FMT /* so can override from CFLAGS in Makefile */
72 #define DEFAULT_FMT FMT_PPM
75 static IMAGE_FORMATS requested_fmt;
79 * Argument-parsing code.
80 * The switch parser is designed to be useful with DOS-style command line
81 * syntax, ie, intermixed switches and file names, where only the switches
82 * to the left of a given file name affect processing of that file.
83 * The main program in this file doesn't actually use this capability...
87 static const char * progname; /* program name for error messages */
88 static char * outfilename; /* for -outfile switch */
93 /* complain about bad command line */
95 fprintf(stderr, "usage: %s [switches] ", progname);
96 #ifdef TWO_FILE_COMMANDLINE
97 fprintf(stderr, "inputfile outputfile\n");
99 fprintf(stderr, "[inputfile]\n");
102 fprintf(stderr, "Switches (names may be abbreviated):\n");
103 fprintf(stderr, " -colors N Reduce image to no more than N colors\n");
104 fprintf(stderr, " -fast Fast, low-quality processing\n");
105 fprintf(stderr, " -grayscale Force grayscale output\n");
106 fprintf(stderr, " -rgb Force RGB output\n");
107 #ifdef IDCT_SCALING_SUPPORTED
108 fprintf(stderr, " -scale M/N Scale output image by fraction M/N, eg, 1/8\n");
111 fprintf(stderr, " -bmp Select BMP output format (Windows style)%s\n",
112 (DEFAULT_FMT == FMT_BMP ? " (default)" : ""));
115 fprintf(stderr, " -gif Select GIF output format%s\n",
116 (DEFAULT_FMT == FMT_GIF ? " (default)" : ""));
119 fprintf(stderr, " -os2 Select BMP output format (OS/2 style)%s\n",
120 (DEFAULT_FMT == FMT_OS2 ? " (default)" : ""));
123 fprintf(stderr, " -pnm Select PBMPLUS (PPM/PGM) output format%s\n",
124 (DEFAULT_FMT == FMT_PPM ? " (default)" : ""));
127 fprintf(stderr, " -rle Select Utah RLE output format%s\n",
128 (DEFAULT_FMT == FMT_RLE ? " (default)" : ""));
130 #ifdef TARGA_SUPPORTED
131 fprintf(stderr, " -targa Select Targa output format%s\n",
132 (DEFAULT_FMT == FMT_TARGA ? " (default)" : ""));
134 fprintf(stderr, "Switches for advanced users:\n");
135 #ifdef DCT_ISLOW_SUPPORTED
136 fprintf(stderr, " -dct int Use integer DCT method%s\n",
137 (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
139 #ifdef DCT_IFAST_SUPPORTED
140 fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",
141 (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
143 #ifdef DCT_FLOAT_SUPPORTED
144 fprintf(stderr, " -dct float Use floating-point DCT method%s\n",
145 (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
147 fprintf(stderr, " -dither fs Use F-S dithering (default)\n");
148 fprintf(stderr, " -dither none Don't use dithering in quantization\n");
149 fprintf(stderr, " -dither ordered Use ordered dither (medium speed, quality)\n");
150 #ifdef QUANT_2PASS_SUPPORTED
151 fprintf(stderr, " -map FILE Map to colors used in named image file\n");
153 fprintf(stderr, " -nosmooth Don't use high-quality upsampling\n");
154 #ifdef QUANT_1PASS_SUPPORTED
155 fprintf(stderr, " -onepass Use 1-pass quantization (fast, low quality)\n");
157 fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
158 fprintf(stderr, " -outfile name Specify name for output file\n");
159 fprintf(stderr, " -verbose or -debug Emit debug output\n");
165 parse_switches (j_decompress_ptr cinfo, int argc, char **argv,
166 int last_file_arg_seen, boolean for_real)
167 /* Parse optional switches.
168 * Returns argv[] index of first file-name argument (== argc if none).
169 * Any file names with indexes <= last_file_arg_seen are ignored;
170 * they have presumably been processed in a previous iteration.
171 * (Pass 0 for last_file_arg_seen on the first or only iteration.)
172 * for_real is FALSE on the first (dummy) pass; we may skip any expensive
179 /* Set up default JPEG parameters. */
180 requested_fmt = DEFAULT_FMT; /* set default output file format */
182 cinfo->err->trace_level = 0;
184 /* Scan command line options, adjust parameters */
186 for (argn = 1; argn < argc; argn++) {
189 /* Not a switch, must be a file name argument */
190 if (argn <= last_file_arg_seen) {
191 outfilename = NULL; /* -outfile applies to just one input file */
192 continue; /* ignore this name if previously processed */
194 break; /* else done parsing switches */
196 arg++; /* advance past switch marker character */
198 if (keymatch(arg, "bmp", 1)) {
199 /* BMP output format. */
200 requested_fmt = FMT_BMP;
202 } else if (keymatch(arg, "colors", 1) || keymatch(arg, "colours", 1) ||
203 keymatch(arg, "quantize", 1) || keymatch(arg, "quantise", 1)) {
204 /* Do color quantization. */
207 if (++argn >= argc) /* advance to next argument */
209 if (sscanf(argv[argn], "%d", &val) != 1)
211 cinfo->desired_number_of_colors = val;
212 cinfo->quantize_colors = TRUE;
214 } else if (keymatch(arg, "dct", 2)) {
215 /* Select IDCT algorithm. */
216 if (++argn >= argc) /* advance to next argument */
218 if (keymatch(argv[argn], "int", 1)) {
219 cinfo->dct_method = JDCT_ISLOW;
220 } else if (keymatch(argv[argn], "fast", 2)) {
221 cinfo->dct_method = JDCT_IFAST;
222 } else if (keymatch(argv[argn], "float", 2)) {
223 cinfo->dct_method = JDCT_FLOAT;
227 } else if (keymatch(arg, "dither", 2)) {
228 /* Select dithering algorithm. */
229 if (++argn >= argc) /* advance to next argument */
231 if (keymatch(argv[argn], "fs", 2)) {
232 cinfo->dither_mode = JDITHER_FS;
233 } else if (keymatch(argv[argn], "none", 2)) {
234 cinfo->dither_mode = JDITHER_NONE;
235 } else if (keymatch(argv[argn], "ordered", 2)) {
236 cinfo->dither_mode = JDITHER_ORDERED;
240 } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
241 /* Enable debug printouts. */
242 /* On first -d, print version identification */
243 static boolean printed_version = FALSE;
245 if (! printed_version) {
246 fprintf(stderr, "%s version %s (build %s)\n",
247 PACKAGE_NAME, VERSION, BUILD);
248 fprintf(stderr, "%s\n\n", JCOPYRIGHT);
249 fprintf(stderr, "Emulating The Independent JPEG Group's libjpeg, version %s\n\n",
251 printed_version = TRUE;
253 cinfo->err->trace_level++;
255 } else if (keymatch(arg, "fast", 1)) {
256 /* Select recommended processing options for quick-and-dirty output. */
257 cinfo->two_pass_quantize = FALSE;
258 cinfo->dither_mode = JDITHER_ORDERED;
259 if (! cinfo->quantize_colors) /* don't override an earlier -colors */
260 cinfo->desired_number_of_colors = 216;
261 cinfo->dct_method = JDCT_FASTEST;
262 cinfo->do_fancy_upsampling = FALSE;
264 } else if (keymatch(arg, "gif", 1)) {
265 /* GIF output format. */
266 requested_fmt = FMT_GIF;
268 } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
269 /* Force monochrome output. */
270 cinfo->out_color_space = JCS_GRAYSCALE;
272 } else if (keymatch(arg, "rgb", 2)) {
273 /* Force RGB output. */
274 cinfo->out_color_space = JCS_RGB;
276 } else if (keymatch(arg, "map", 3)) {
277 /* Quantize to a color map taken from an input file. */
278 if (++argn >= argc) /* advance to next argument */
280 if (for_real) { /* too expensive to do twice! */
281 #ifdef QUANT_2PASS_SUPPORTED /* otherwise can't quantize to supplied map */
284 if ((mapfile = fopen(argv[argn], READ_BINARY)) == NULL) {
285 fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
288 read_color_map(cinfo, mapfile);
290 cinfo->quantize_colors = TRUE;
292 ERREXIT(cinfo, JERR_NOT_COMPILED);
296 } else if (keymatch(arg, "maxmemory", 3)) {
297 /* Maximum memory in Kb (or Mb with 'm'). */
301 if (++argn >= argc) /* advance to next argument */
303 if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
305 if (ch == 'm' || ch == 'M')
307 cinfo->mem->max_memory_to_use = lval * 1000L;
309 } else if (keymatch(arg, "nosmooth", 3)) {
310 /* Suppress fancy upsampling */
311 cinfo->do_fancy_upsampling = FALSE;
313 } else if (keymatch(arg, "onepass", 3)) {
314 /* Use fast one-pass quantization. */
315 cinfo->two_pass_quantize = FALSE;
317 } else if (keymatch(arg, "os2", 3)) {
318 /* BMP output format (OS/2 flavor). */
319 requested_fmt = FMT_OS2;
321 } else if (keymatch(arg, "outfile", 4)) {
322 /* Set output file name. */
323 if (++argn >= argc) /* advance to next argument */
325 outfilename = argv[argn]; /* save it away for later use */
327 } else if (keymatch(arg, "pnm", 1) || keymatch(arg, "ppm", 1)) {
328 /* PPM/PGM output format. */
329 requested_fmt = FMT_PPM;
331 } else if (keymatch(arg, "rle", 1)) {
332 /* RLE output format. */
333 requested_fmt = FMT_RLE;
335 } else if (keymatch(arg, "scale", 1)) {
336 /* Scale the output image by a fraction M/N. */
337 if (++argn >= argc) /* advance to next argument */
339 if (sscanf(argv[argn], "%d/%d",
340 &cinfo->scale_num, &cinfo->scale_denom) != 2)
343 } else if (keymatch(arg, "targa", 1)) {
344 /* Targa output format. */
345 requested_fmt = FMT_TARGA;
348 usage(); /* bogus switch */
352 return argn; /* return index of next arg (file name) */
357 * Marker processor for COM and interesting APPn markers.
358 * This replaces the library's built-in processor, which just skips the marker.
359 * We want to print out the marker as text, to the extent possible.
360 * Note this code relies on a non-suspending data source.
364 jpeg_getc (j_decompress_ptr cinfo)
367 struct jpeg_source_mgr * datasrc = cinfo->src;
369 if (datasrc->bytes_in_buffer == 0) {
370 if (! (*datasrc->fill_input_buffer) (cinfo))
371 ERREXIT(cinfo, JERR_CANT_SUSPEND);
373 datasrc->bytes_in_buffer--;
374 return GETJOCTET(*datasrc->next_input_byte++);
379 print_text_marker (j_decompress_ptr cinfo)
381 boolean traceit = (cinfo->err->trace_level >= 1);
384 unsigned int lastch = 0;
386 length = jpeg_getc(cinfo) << 8;
387 length += jpeg_getc(cinfo);
388 length -= 2; /* discount the length word itself */
391 if (cinfo->unread_marker == JPEG_COM)
392 fprintf(stderr, "Comment, length %ld:\n", (long) length);
393 else /* assume it is an APPn otherwise */
394 fprintf(stderr, "APP%d, length %ld:\n",
395 cinfo->unread_marker - JPEG_APP0, (long) length);
398 while (--length >= 0) {
399 ch = jpeg_getc(cinfo);
401 /* Emit the character in a readable form.
402 * Nonprintables are converted to \nnn form,
403 * while \ is converted to \\.
404 * Newlines in CR, CR/LF, or LF form will be printed as one newline.
407 fprintf(stderr, "\n");
408 } else if (ch == '\n') {
410 fprintf(stderr, "\n");
411 } else if (ch == '\\') {
412 fprintf(stderr, "\\\\");
413 } else if (isprint(ch)) {
416 fprintf(stderr, "\\%03o", ch);
423 fprintf(stderr, "\n");
434 main (int argc, char **argv)
436 struct jpeg_decompress_struct cinfo;
437 struct jpeg_error_mgr jerr;
438 #ifdef PROGRESS_REPORT
439 struct cdjpeg_progress_mgr progress;
442 djpeg_dest_ptr dest_mgr = NULL;
445 JDIMENSION num_scanlines;
447 /* On Mac, fetch a command line. */
449 argc = ccommand(&argv);
453 if (progname == NULL || progname[0] == 0)
454 progname = "djpeg"; /* in case C library doesn't provide it */
456 /* Initialize the JPEG decompression object with default error handling. */
457 cinfo.err = jpeg_std_error(&jerr);
458 jpeg_create_decompress(&cinfo);
459 /* Add some application-specific error messages (from cderror.h) */
460 jerr.addon_message_table = cdjpeg_message_table;
461 jerr.first_addon_message = JMSG_FIRSTADDONCODE;
462 jerr.last_addon_message = JMSG_LASTADDONCODE;
464 /* Insert custom marker processor for COM and APP12.
465 * APP12 is used by some digital camera makers for textual info,
466 * so we provide the ability to display it as text.
467 * If you like, additional APPn marker types can be selected for display,
468 * but don't try to override APP0 or APP14 this way (see libjpeg.txt).
470 jpeg_set_marker_processor(&cinfo, JPEG_COM, print_text_marker);
471 jpeg_set_marker_processor(&cinfo, JPEG_APP0+12, print_text_marker);
473 /* Now safe to enable signal catcher. */
474 #ifdef NEED_SIGNAL_CATCHER
475 enable_signal_catcher((j_common_ptr) &cinfo);
478 /* Scan command line to find file names. */
479 /* It is convenient to use just one switch-parsing routine, but the switch
480 * values read here are ignored; we will rescan the switches after opening
482 * (Exception: tracing level set here controls verbosity for COM markers
483 * found during jpeg_read_header...)
486 file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
488 #ifdef TWO_FILE_COMMANDLINE
489 /* Must have either -outfile switch or explicit output file name */
490 if (outfilename == NULL) {
491 if (file_index != argc-2) {
492 fprintf(stderr, "%s: must name one input and one output file\n",
496 outfilename = argv[file_index+1];
498 if (file_index != argc-1) {
499 fprintf(stderr, "%s: must name one input and one output file\n",
505 /* Unix style: expect zero or one file name */
506 if (file_index < argc-1) {
507 fprintf(stderr, "%s: only one input file\n", progname);
510 #endif /* TWO_FILE_COMMANDLINE */
512 /* Open the input file. */
513 if (file_index < argc) {
514 if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
515 fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
519 /* default input file is stdin */
520 input_file = read_stdin();
523 /* Open the output file. */
524 if (outfilename != NULL) {
525 if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
526 fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
530 /* default output file is stdout */
531 output_file = write_stdout();
534 #ifdef PROGRESS_REPORT
535 start_progress_monitor((j_common_ptr) &cinfo, &progress);
538 /* Specify data source for decompression */
539 jpeg_stdio_src(&cinfo, input_file);
541 /* Read file header, set default decompression parameters */
542 (void) jpeg_read_header(&cinfo, TRUE);
544 /* Adjust default decompression parameters by re-parsing the options */
545 file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
547 /* Initialize the output module now to let it override any crucial
548 * option settings (for instance, GIF wants to force color quantization).
550 switch (requested_fmt) {
553 dest_mgr = jinit_write_bmp(&cinfo, FALSE);
556 dest_mgr = jinit_write_bmp(&cinfo, TRUE);
561 dest_mgr = jinit_write_gif(&cinfo);
566 dest_mgr = jinit_write_ppm(&cinfo);
571 dest_mgr = jinit_write_rle(&cinfo);
574 #ifdef TARGA_SUPPORTED
576 dest_mgr = jinit_write_targa(&cinfo);
580 ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT);
583 dest_mgr->output_file = output_file;
585 /* Start decompressor */
586 (void) jpeg_start_decompress(&cinfo);
588 /* Write output file header */
589 (*dest_mgr->start_output) (&cinfo, dest_mgr);
592 while (cinfo.output_scanline < cinfo.output_height) {
593 num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
594 dest_mgr->buffer_height);
595 (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
598 #ifdef PROGRESS_REPORT
599 /* Hack: count final pass as done in case finish_output does an extra pass.
600 * The library won't have updated completed_passes.
602 progress.pub.completed_passes = progress.pub.total_passes;
605 /* Finish decompression and release memory.
606 * I must do it in this order because output module has allocated memory
607 * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory.
609 (*dest_mgr->finish_output) (&cinfo, dest_mgr);
610 (void) jpeg_finish_decompress(&cinfo);
611 jpeg_destroy_decompress(&cinfo);
613 /* Close files, if we opened them */
614 if (input_file != stdin)
616 if (output_file != stdout)
619 #ifdef PROGRESS_REPORT
620 end_progress_monitor((j_common_ptr) &cinfo);
624 exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
625 return 0; /* suppress no-return-value warnings */