4 * This file was part of the Independent JPEG Group's software:
5 * Copyright (C) 1991-1997, Thomas G. Lane.
6 * libjpeg-turbo Modifications:
7 * Copyright (C) 2010-2011, 2013, D. R. Commander.
8 * For conditions of distribution and use, see the accompanying README file.
10 * This file contains a command-line user interface for the JPEG decompressor.
11 * It should work on any system with Unix- or MS-DOS-style command lines.
13 * Two different command line styles are permitted, depending on the
14 * compile-time switch TWO_FILE_COMMANDLINE:
15 * djpeg [options] inputfile outputfile
16 * djpeg [options] [inputfile]
17 * In the second style, output is always to standard output, which you'd
18 * normally redirect to a file or pipe to some other program. Input is
19 * either from a named file or from standard input (typically redirected).
20 * The second style is convenient on Unix but is unhelpful on systems that
21 * don't support pipes. Also, you MUST use the first style if your system
22 * doesn't do binary I/O to stdin/stdout.
23 * To simplify script writing, the "-outfile" switch is provided. The syntax
24 * djpeg [options] -outfile outputfile inputfile
25 * works regardless of which command line style is used.
28 #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
29 #include "jversion.h" /* for version message */
32 #include <ctype.h> /* to declare isprint() */
34 #ifdef USE_CCOMMAND /* command-line reader for Macintosh */
36 #include <SIOUX.h> /* Metrowerks needs this */
37 #include <console.h> /* ... and this */
40 #include <console.h> /* Think declares it here */
45 /* Create the add-on message string table. */
47 #define JMESSAGE(code,string) string ,
49 static const char * const cdjpeg_message_table[] = {
56 * This list defines the known output image formats
57 * (not all of which need be supported by a given version).
58 * You can change the default output format by defining DEFAULT_FMT;
59 * indeed, you had better do so if you undefine PPM_SUPPORTED.
63 FMT_BMP, /* BMP format (Windows flavor) */
64 FMT_GIF, /* GIF format */
65 FMT_OS2, /* BMP format (OS/2 flavor) */
66 FMT_PPM, /* PPM/PGM (PBMPLUS formats) */
67 FMT_RLE, /* RLE format */
68 FMT_TARGA, /* Targa format */
69 FMT_TIFF /* TIFF format */
72 #ifndef DEFAULT_FMT /* so can override from CFLAGS in Makefile */
73 #define DEFAULT_FMT FMT_PPM
76 static IMAGE_FORMATS requested_fmt;
80 * Argument-parsing code.
81 * The switch parser is designed to be useful with DOS-style command line
82 * syntax, ie, intermixed switches and file names, where only the switches
83 * to the left of a given file name affect processing of that file.
84 * The main program in this file doesn't actually use this capability...
88 static const char * progname; /* program name for error messages */
89 static char * outfilename; /* for -outfile switch */
90 boolean memsrc; /* for -memsrc switch */
91 #define INPUT_BUF_SIZE 4096
96 /* complain about bad command line */
98 fprintf(stderr, "usage: %s [switches] ", progname);
99 #ifdef TWO_FILE_COMMANDLINE
100 fprintf(stderr, "inputfile outputfile\n");
102 fprintf(stderr, "[inputfile]\n");
105 fprintf(stderr, "Switches (names may be abbreviated):\n");
106 fprintf(stderr, " -colors N Reduce image to no more than N colors\n");
107 fprintf(stderr, " -fast Fast, low-quality processing\n");
108 fprintf(stderr, " -grayscale Force grayscale output\n");
109 fprintf(stderr, " -rgb Force RGB output\n");
110 #ifdef IDCT_SCALING_SUPPORTED
111 fprintf(stderr, " -scale M/N Scale output image by fraction M/N, eg, 1/8\n");
114 fprintf(stderr, " -bmp Select BMP output format (Windows style)%s\n",
115 (DEFAULT_FMT == FMT_BMP ? " (default)" : ""));
118 fprintf(stderr, " -gif Select GIF output format%s\n",
119 (DEFAULT_FMT == FMT_GIF ? " (default)" : ""));
122 fprintf(stderr, " -os2 Select BMP output format (OS/2 style)%s\n",
123 (DEFAULT_FMT == FMT_OS2 ? " (default)" : ""));
126 fprintf(stderr, " -pnm Select PBMPLUS (PPM/PGM) output format%s\n",
127 (DEFAULT_FMT == FMT_PPM ? " (default)" : ""));
130 fprintf(stderr, " -rle Select Utah RLE output format%s\n",
131 (DEFAULT_FMT == FMT_RLE ? " (default)" : ""));
133 #ifdef TARGA_SUPPORTED
134 fprintf(stderr, " -targa Select Targa output format%s\n",
135 (DEFAULT_FMT == FMT_TARGA ? " (default)" : ""));
137 fprintf(stderr, "Switches for advanced users:\n");
138 #ifdef DCT_ISLOW_SUPPORTED
139 fprintf(stderr, " -dct int Use integer DCT method%s\n",
140 (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
142 #ifdef DCT_IFAST_SUPPORTED
143 fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",
144 (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
146 #ifdef DCT_FLOAT_SUPPORTED
147 fprintf(stderr, " -dct float Use floating-point DCT method%s\n",
148 (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
150 fprintf(stderr, " -dither fs Use F-S dithering (default)\n");
151 fprintf(stderr, " -dither none Don't use dithering in quantization\n");
152 fprintf(stderr, " -dither ordered Use ordered dither (medium speed, quality)\n");
153 #ifdef QUANT_2PASS_SUPPORTED
154 fprintf(stderr, " -map FILE Map to colors used in named image file\n");
156 fprintf(stderr, " -nosmooth Don't use high-quality upsampling\n");
157 #ifdef QUANT_1PASS_SUPPORTED
158 fprintf(stderr, " -onepass Use 1-pass quantization (fast, low quality)\n");
160 fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
161 fprintf(stderr, " -outfile name Specify name for output file\n");
162 #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
163 fprintf(stderr, " -memsrc Load input file into memory before decompressing\n");
166 fprintf(stderr, " -verbose or -debug Emit debug output\n");
172 parse_switches (j_decompress_ptr cinfo, int argc, char **argv,
173 int last_file_arg_seen, boolean for_real)
174 /* Parse optional switches.
175 * Returns argv[] index of first file-name argument (== argc if none).
176 * Any file names with indexes <= last_file_arg_seen are ignored;
177 * they have presumably been processed in a previous iteration.
178 * (Pass 0 for last_file_arg_seen on the first or only iteration.)
179 * for_real is FALSE on the first (dummy) pass; we may skip any expensive
186 /* Set up default JPEG parameters. */
187 requested_fmt = DEFAULT_FMT; /* set default output file format */
190 cinfo->err->trace_level = 0;
192 /* Scan command line options, adjust parameters */
194 for (argn = 1; argn < argc; argn++) {
197 /* Not a switch, must be a file name argument */
198 if (argn <= last_file_arg_seen) {
199 outfilename = NULL; /* -outfile applies to just one input file */
200 continue; /* ignore this name if previously processed */
202 break; /* else done parsing switches */
204 arg++; /* advance past switch marker character */
206 if (keymatch(arg, "bmp", 1)) {
207 /* BMP output format. */
208 requested_fmt = FMT_BMP;
210 } else if (keymatch(arg, "colors", 1) || keymatch(arg, "colours", 1) ||
211 keymatch(arg, "quantize", 1) || keymatch(arg, "quantise", 1)) {
212 /* Do color quantization. */
215 if (++argn >= argc) /* advance to next argument */
217 if (sscanf(argv[argn], "%d", &val) != 1)
219 cinfo->desired_number_of_colors = val;
220 cinfo->quantize_colors = TRUE;
222 } else if (keymatch(arg, "dct", 2)) {
223 /* Select IDCT algorithm. */
224 if (++argn >= argc) /* advance to next argument */
226 if (keymatch(argv[argn], "int", 1)) {
227 cinfo->dct_method = JDCT_ISLOW;
228 } else if (keymatch(argv[argn], "fast", 2)) {
229 cinfo->dct_method = JDCT_IFAST;
230 } else if (keymatch(argv[argn], "float", 2)) {
231 cinfo->dct_method = JDCT_FLOAT;
235 } else if (keymatch(arg, "dither", 2)) {
236 /* Select dithering algorithm. */
237 if (++argn >= argc) /* advance to next argument */
239 if (keymatch(argv[argn], "fs", 2)) {
240 cinfo->dither_mode = JDITHER_FS;
241 } else if (keymatch(argv[argn], "none", 2)) {
242 cinfo->dither_mode = JDITHER_NONE;
243 } else if (keymatch(argv[argn], "ordered", 2)) {
244 cinfo->dither_mode = JDITHER_ORDERED;
248 } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
249 /* Enable debug printouts. */
250 /* On first -d, print version identification */
251 static boolean printed_version = FALSE;
253 if (! printed_version) {
254 fprintf(stderr, "%s version %s (build %s)\n",
255 PACKAGE_NAME, VERSION, BUILD);
256 fprintf(stderr, "%s\n\n", JCOPYRIGHT);
257 fprintf(stderr, "Emulating The Independent JPEG Group's software, version %s\n\n",
259 printed_version = TRUE;
261 cinfo->err->trace_level++;
263 } else if (keymatch(arg, "fast", 1)) {
264 /* Select recommended processing options for quick-and-dirty output. */
265 cinfo->two_pass_quantize = FALSE;
266 cinfo->dither_mode = JDITHER_ORDERED;
267 if (! cinfo->quantize_colors) /* don't override an earlier -colors */
268 cinfo->desired_number_of_colors = 216;
269 cinfo->dct_method = JDCT_FASTEST;
270 cinfo->do_fancy_upsampling = FALSE;
272 } else if (keymatch(arg, "gif", 1)) {
273 /* GIF output format. */
274 requested_fmt = FMT_GIF;
276 } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
277 /* Force monochrome output. */
278 cinfo->out_color_space = JCS_GRAYSCALE;
280 } else if (keymatch(arg, "rgb", 2)) {
281 /* Force RGB output. */
282 cinfo->out_color_space = JCS_RGB;
284 } else if (keymatch(arg, "map", 3)) {
285 /* Quantize to a color map taken from an input file. */
286 if (++argn >= argc) /* advance to next argument */
288 if (for_real) { /* too expensive to do twice! */
289 #ifdef QUANT_2PASS_SUPPORTED /* otherwise can't quantize to supplied map */
292 if ((mapfile = fopen(argv[argn], READ_BINARY)) == NULL) {
293 fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
296 read_color_map(cinfo, mapfile);
298 cinfo->quantize_colors = TRUE;
300 ERREXIT(cinfo, JERR_NOT_COMPILED);
304 } else if (keymatch(arg, "maxmemory", 3)) {
305 /* Maximum memory in Kb (or Mb with 'm'). */
309 if (++argn >= argc) /* advance to next argument */
311 if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
313 if (ch == 'm' || ch == 'M')
315 cinfo->mem->max_memory_to_use = lval * 1000L;
317 } else if (keymatch(arg, "nosmooth", 3)) {
318 /* Suppress fancy upsampling */
319 cinfo->do_fancy_upsampling = FALSE;
321 } else if (keymatch(arg, "onepass", 3)) {
322 /* Use fast one-pass quantization. */
323 cinfo->two_pass_quantize = FALSE;
325 } else if (keymatch(arg, "os2", 3)) {
326 /* BMP output format (OS/2 flavor). */
327 requested_fmt = FMT_OS2;
329 } else if (keymatch(arg, "outfile", 4)) {
330 /* Set output file name. */
331 if (++argn >= argc) /* advance to next argument */
333 outfilename = argv[argn]; /* save it away for later use */
335 } else if (keymatch(arg, "memsrc", 2)) {
336 /* Use in-memory source manager */
337 #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
340 fprintf(stderr, "%s: sorry, in-memory source manager was not compiled in\n",
345 } else if (keymatch(arg, "pnm", 1) || keymatch(arg, "ppm", 1)) {
346 /* PPM/PGM output format. */
347 requested_fmt = FMT_PPM;
349 } else if (keymatch(arg, "rle", 1)) {
350 /* RLE output format. */
351 requested_fmt = FMT_RLE;
353 } else if (keymatch(arg, "scale", 1)) {
354 /* Scale the output image by a fraction M/N. */
355 if (++argn >= argc) /* advance to next argument */
357 if (sscanf(argv[argn], "%d/%d",
358 &cinfo->scale_num, &cinfo->scale_denom) != 2)
361 } else if (keymatch(arg, "targa", 1)) {
362 /* Targa output format. */
363 requested_fmt = FMT_TARGA;
366 usage(); /* bogus switch */
370 return argn; /* return index of next arg (file name) */
375 * Marker processor for COM and interesting APPn markers.
376 * This replaces the library's built-in processor, which just skips the marker.
377 * We want to print out the marker as text, to the extent possible.
378 * Note this code relies on a non-suspending data source.
382 jpeg_getc (j_decompress_ptr cinfo)
385 struct jpeg_source_mgr * datasrc = cinfo->src;
387 if (datasrc->bytes_in_buffer == 0) {
388 if (! (*datasrc->fill_input_buffer) (cinfo))
389 ERREXIT(cinfo, JERR_CANT_SUSPEND);
391 datasrc->bytes_in_buffer--;
392 return GETJOCTET(*datasrc->next_input_byte++);
397 print_text_marker (j_decompress_ptr cinfo)
399 boolean traceit = (cinfo->err->trace_level >= 1);
402 unsigned int lastch = 0;
404 length = jpeg_getc(cinfo) << 8;
405 length += jpeg_getc(cinfo);
406 length -= 2; /* discount the length word itself */
409 if (cinfo->unread_marker == JPEG_COM)
410 fprintf(stderr, "Comment, length %ld:\n", (long) length);
411 else /* assume it is an APPn otherwise */
412 fprintf(stderr, "APP%d, length %ld:\n",
413 cinfo->unread_marker - JPEG_APP0, (long) length);
416 while (--length >= 0) {
417 ch = jpeg_getc(cinfo);
419 /* Emit the character in a readable form.
420 * Nonprintables are converted to \nnn form,
421 * while \ is converted to \\.
422 * Newlines in CR, CR/LF, or LF form will be printed as one newline.
425 fprintf(stderr, "\n");
426 } else if (ch == '\n') {
428 fprintf(stderr, "\n");
429 } else if (ch == '\\') {
430 fprintf(stderr, "\\\\");
431 } else if (isprint(ch)) {
434 fprintf(stderr, "\\%03o", ch);
441 fprintf(stderr, "\n");
452 main (int argc, char **argv)
454 struct jpeg_decompress_struct cinfo;
455 struct jpeg_error_mgr jerr;
456 #ifdef PROGRESS_REPORT
457 struct cdjpeg_progress_mgr progress;
460 djpeg_dest_ptr dest_mgr = NULL;
463 unsigned char *inbuffer = NULL;
464 unsigned long insize = 0;
465 JDIMENSION num_scanlines;
467 /* On Mac, fetch a command line. */
469 argc = ccommand(&argv);
473 if (progname == NULL || progname[0] == 0)
474 progname = "djpeg"; /* in case C library doesn't provide it */
476 /* Initialize the JPEG decompression object with default error handling. */
477 cinfo.err = jpeg_std_error(&jerr);
478 jpeg_create_decompress(&cinfo);
479 /* Add some application-specific error messages (from cderror.h) */
480 jerr.addon_message_table = cdjpeg_message_table;
481 jerr.first_addon_message = JMSG_FIRSTADDONCODE;
482 jerr.last_addon_message = JMSG_LASTADDONCODE;
484 /* Insert custom marker processor for COM and APP12.
485 * APP12 is used by some digital camera makers for textual info,
486 * so we provide the ability to display it as text.
487 * If you like, additional APPn marker types can be selected for display,
488 * but don't try to override APP0 or APP14 this way (see libjpeg.txt).
490 jpeg_set_marker_processor(&cinfo, JPEG_COM, print_text_marker);
491 jpeg_set_marker_processor(&cinfo, JPEG_APP0+12, print_text_marker);
493 /* Now safe to enable signal catcher. */
494 #ifdef NEED_SIGNAL_CATCHER
495 enable_signal_catcher((j_common_ptr) &cinfo);
498 /* Scan command line to find file names. */
499 /* It is convenient to use just one switch-parsing routine, but the switch
500 * values read here are ignored; we will rescan the switches after opening
502 * (Exception: tracing level set here controls verbosity for COM markers
503 * found during jpeg_read_header...)
506 file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
508 #ifdef TWO_FILE_COMMANDLINE
509 /* Must have either -outfile switch or explicit output file name */
510 if (outfilename == NULL) {
511 if (file_index != argc-2) {
512 fprintf(stderr, "%s: must name one input and one output file\n",
516 outfilename = argv[file_index+1];
518 if (file_index != argc-1) {
519 fprintf(stderr, "%s: must name one input and one output file\n",
525 /* Unix style: expect zero or one file name */
526 if (file_index < argc-1) {
527 fprintf(stderr, "%s: only one input file\n", progname);
530 #endif /* TWO_FILE_COMMANDLINE */
532 /* Open the input file. */
533 if (file_index < argc) {
534 if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
535 fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
539 /* default input file is stdin */
540 input_file = read_stdin();
543 /* Open the output file. */
544 if (outfilename != NULL) {
545 if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
546 fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
550 /* default output file is stdout */
551 output_file = write_stdout();
554 #ifdef PROGRESS_REPORT
555 start_progress_monitor((j_common_ptr) &cinfo, &progress);
558 /* Specify data source for decompression */
559 #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
563 inbuffer = (unsigned char *)realloc(inbuffer, insize + INPUT_BUF_SIZE);
564 if (inbuffer == NULL) {
565 fprintf(stderr, "%s: memory allocation failure\n", progname);
568 nbytes = JFREAD(input_file, &inbuffer[insize], INPUT_BUF_SIZE);
569 if (nbytes < INPUT_BUF_SIZE && ferror(input_file)) {
570 if (file_index < argc)
571 fprintf(stderr, "%s: can't read from %s\n", progname,
574 fprintf(stderr, "%s: can't read from stdin\n", progname);
576 insize += (unsigned long)nbytes;
577 } while (nbytes == INPUT_BUF_SIZE);
578 fprintf(stderr, "Compressed size: %lu bytes\n", insize);
579 jpeg_mem_src(&cinfo, inbuffer, insize);
582 jpeg_stdio_src(&cinfo, input_file);
584 /* Read file header, set default decompression parameters */
585 (void) jpeg_read_header(&cinfo, TRUE);
587 /* Adjust default decompression parameters by re-parsing the options */
588 file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
590 /* Initialize the output module now to let it override any crucial
591 * option settings (for instance, GIF wants to force color quantization).
593 switch (requested_fmt) {
596 dest_mgr = jinit_write_bmp(&cinfo, FALSE);
599 dest_mgr = jinit_write_bmp(&cinfo, TRUE);
604 dest_mgr = jinit_write_gif(&cinfo);
609 dest_mgr = jinit_write_ppm(&cinfo);
614 dest_mgr = jinit_write_rle(&cinfo);
617 #ifdef TARGA_SUPPORTED
619 dest_mgr = jinit_write_targa(&cinfo);
623 ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT);
626 dest_mgr->output_file = output_file;
628 /* Start decompressor */
629 (void) jpeg_start_decompress(&cinfo);
631 /* Write output file header */
632 (*dest_mgr->start_output) (&cinfo, dest_mgr);
635 while (cinfo.output_scanline < cinfo.output_height) {
636 num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
637 dest_mgr->buffer_height);
638 (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
641 #ifdef PROGRESS_REPORT
642 /* Hack: count final pass as done in case finish_output does an extra pass.
643 * The library won't have updated completed_passes.
645 progress.pub.completed_passes = progress.pub.total_passes;
648 /* Finish decompression and release memory.
649 * I must do it in this order because output module has allocated memory
650 * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory.
652 (*dest_mgr->finish_output) (&cinfo, dest_mgr);
653 (void) jpeg_finish_decompress(&cinfo);
654 jpeg_destroy_decompress(&cinfo);
656 /* Close files, if we opened them */
657 if (input_file != stdin)
659 if (output_file != stdout)
662 #ifdef PROGRESS_REPORT
663 end_progress_monitor((j_common_ptr) &cinfo);
666 if (memsrc && inbuffer != NULL)
670 exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
671 return 0; /* suppress no-return-value warnings */