1 /*
2  * djpeg.c
3  *
4  * This file was part of the Independent JPEG Group's software:
5  * Copyright (C) 1991-1997, Thomas G. Lane.
6  * Modified 2013-2019 by Guido Vollbeding.
7  * libjpeg-turbo Modifications:
8  * Copyright (C) 2010-2011, 2013-2017, 2019-2020, D. R. Commander.
9  * Copyright (C) 2015, Google, Inc.
10  * For conditions of distribution and use, see the accompanying README.ijg
11  * file.
12  *
13  * This file contains a command-line user interface for the JPEG decompressor.
14  * It should work on any system with Unix- or MS-DOS-style command lines.
15  *
16  * Two different command line styles are permitted, depending on the
17  * compile-time switch TWO_FILE_COMMANDLINE:
18  *      djpeg [options]  inputfile outputfile
19  *      djpeg [options]  [inputfile]
20  * In the second style, output is always to standard output, which you'd
21  * normally redirect to a file or pipe to some other program.  Input is
22  * either from a named file or from standard input (typically redirected).
23  * The second style is convenient on Unix but is unhelpful on systems that
24  * don't support pipes.  Also, you MUST use the first style if your system
25  * doesn't do binary I/O to stdin/stdout.
26  * To simplify script writing, the "-outfile" switch is provided.  The syntax
27  *      djpeg [options]  -outfile outputfile  inputfile
28  * works regardless of which command line style is used.
29  */
30 
31 #include "cdjpeg.h"             /* Common decls for cjpeg/djpeg applications */
32 #include "jversion.h"           /* for version message */
33 #include "jconfigint.h"
34 
35 #ifndef HAVE_STDLIB_H           /* <stdlib.h> should declare free() */
36 extern void free(void *ptr);
37 #endif
38 
39 #include <ctype.h>              /* to declare isprint() */
40 
41 #ifdef USE_CCOMMAND             /* command-line reader for Macintosh */
42 #ifdef __MWERKS__
43 #include <SIOUX.h>              /* Metrowerks needs this */
44 #include <console.h>            /* ... and this */
45 #endif
46 #ifdef THINK_C
47 #include <console.h>            /* Think declares it here */
48 #endif
49 #endif
50 
51 
52 /* Create the add-on message string table. */
53 
54 #define JMESSAGE(code, string)  string,
55 
56 static const char * const cdjpeg_message_table[] = {
57 #include "cderror.h"
58   NULL
59 };
60 
61 
62 /*
63  * This list defines the known output image formats
64  * (not all of which need be supported by a given version).
65  * You can change the default output format by defining DEFAULT_FMT;
66  * indeed, you had better do so if you undefine PPM_SUPPORTED.
67  */
68 
69 typedef enum {
70   FMT_BMP,                      /* BMP format (Windows flavor) */
71   FMT_GIF,                      /* GIF format (LZW-compressed) */
72   FMT_GIF0,                     /* GIF format (uncompressed) */
73   FMT_OS2,                      /* BMP format (OS/2 flavor) */
74   FMT_PPM,                      /* PPM/PGM (PBMPLUS formats) */
75   FMT_TARGA,                    /* Targa format */
76   FMT_TIFF                      /* TIFF format */
77 } IMAGE_FORMATS;
78 
79 #ifndef DEFAULT_FMT             /* so can override from CFLAGS in Makefile */
80 #define DEFAULT_FMT     FMT_PPM
81 #endif
82 
83 static IMAGE_FORMATS requested_fmt;
84 
85 
86 /*
87  * Argument-parsing code.
88  * The switch parser is designed to be useful with DOS-style command line
89  * syntax, ie, intermixed switches and file names, where only the switches
90  * to the left of a given file name affect processing of that file.
91  * The main program in this file doesn't actually use this capability...
92  */
93 
94 
95 static const char *progname;    /* program name for error messages */
96 static char *icc_filename;      /* for -icc switch */
97 static JDIMENSION max_scans;    /* for -maxscans switch */
98 static char *outfilename;       /* for -outfile switch */
99 static boolean memsrc;          /* for -memsrc switch */
100 static boolean report;          /* for -report switch */
101 boolean skip, crop;
102 JDIMENSION skip_start, skip_end;
103 JDIMENSION crop_x, crop_y, crop_width, crop_height;
104 static boolean strict;          /* for -strict switch */
105 #define INPUT_BUF_SIZE  4096
106 
107 
108 LOCAL(void)
usage(void)109 usage(void)
110 /* complain about bad command line */
111 {
112   fprintf(stderr, "usage: %s [switches] ", progname);
113 #ifdef TWO_FILE_COMMANDLINE
114   fprintf(stderr, "inputfile outputfile\n");
115 #else
116   fprintf(stderr, "[inputfile]\n");
117 #endif
118 
119   fprintf(stderr, "Switches (names may be abbreviated):\n");
120   fprintf(stderr, "  -colors N      Reduce image to no more than N colors\n");
121   fprintf(stderr, "  -fast          Fast, low-quality processing\n");
122   fprintf(stderr, "  -grayscale     Force grayscale output\n");
123   fprintf(stderr, "  -rgb           Force RGB output\n");
124   fprintf(stderr, "  -rgb565        Force RGB565 output\n");
125 #ifdef IDCT_SCALING_SUPPORTED
126   fprintf(stderr, "  -scale M/N     Scale output image by fraction M/N, eg, 1/8\n");
127 #endif
128 #ifdef BMP_SUPPORTED
129   fprintf(stderr, "  -bmp           Select BMP output format (Windows style)%s\n",
130           (DEFAULT_FMT == FMT_BMP ? " (default)" : ""));
131 #endif
132 #ifdef GIF_SUPPORTED
133   fprintf(stderr, "  -gif           Select GIF output format (LZW-compressed)%s\n",
134           (DEFAULT_FMT == FMT_GIF ? " (default)" : ""));
135   fprintf(stderr, "  -gif0          Select GIF output format (uncompressed)%s\n",
136           (DEFAULT_FMT == FMT_GIF0 ? " (default)" : ""));
137 #endif
138 #ifdef BMP_SUPPORTED
139   fprintf(stderr, "  -os2           Select BMP output format (OS/2 style)%s\n",
140           (DEFAULT_FMT == FMT_OS2 ? " (default)" : ""));
141 #endif
142 #ifdef PPM_SUPPORTED
143   fprintf(stderr, "  -pnm           Select PBMPLUS (PPM/PGM) output format%s\n",
144           (DEFAULT_FMT == FMT_PPM ? " (default)" : ""));
145 #endif
146 #ifdef TARGA_SUPPORTED
147   fprintf(stderr, "  -targa         Select Targa output format%s\n",
148           (DEFAULT_FMT == FMT_TARGA ? " (default)" : ""));
149 #endif
150   fprintf(stderr, "Switches for advanced users:\n");
151 #ifdef DCT_ISLOW_SUPPORTED
152   fprintf(stderr, "  -dct int       Use accurate integer DCT method%s\n",
153           (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
154 #endif
155 #ifdef DCT_IFAST_SUPPORTED
156   fprintf(stderr, "  -dct fast      Use less accurate integer DCT method [legacy feature]%s\n",
157           (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
158 #endif
159 #ifdef DCT_FLOAT_SUPPORTED
160   fprintf(stderr, "  -dct float     Use floating-point DCT method [legacy feature]%s\n",
161           (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
162 #endif
163   fprintf(stderr, "  -dither fs     Use F-S dithering (default)\n");
164   fprintf(stderr, "  -dither none   Don't use dithering in quantization\n");
165   fprintf(stderr, "  -dither ordered  Use ordered dither (medium speed, quality)\n");
166   fprintf(stderr, "  -icc FILE      Extract ICC profile to FILE\n");
167 #ifdef QUANT_2PASS_SUPPORTED
168   fprintf(stderr, "  -map FILE      Map to colors used in named image file\n");
169 #endif
170   fprintf(stderr, "  -nosmooth      Don't use high-quality upsampling\n");
171 #ifdef QUANT_1PASS_SUPPORTED
172   fprintf(stderr, "  -onepass       Use 1-pass quantization (fast, low quality)\n");
173 #endif
174   fprintf(stderr, "  -maxmemory N   Maximum memory to use (in kbytes)\n");
175   fprintf(stderr, "  -maxscans N    Maximum number of scans to allow in input file\n");
176   fprintf(stderr, "  -outfile name  Specify name for output file\n");
177 #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
178   fprintf(stderr, "  -memsrc        Load input file into memory before decompressing\n");
179 #endif
180   fprintf(stderr, "  -report        Report decompression progress\n");
181   fprintf(stderr, "  -skip Y0,Y1    Decompress all rows except those between Y0 and Y1 (inclusive)\n");
182   fprintf(stderr, "  -crop WxH+X+Y  Decompress only a rectangular subregion of the image\n");
183   fprintf(stderr, "                 [requires PBMPLUS (PPM/PGM), GIF, or Targa output format]\n");
184   fprintf(stderr, "  -strict        Treat all warnings as fatal\n");
185   fprintf(stderr, "  -verbose  or  -debug   Emit debug output\n");
186   fprintf(stderr, "  -version       Print version information and exit\n");
187   exit(EXIT_FAILURE);
188 }
189 
190 
191 LOCAL(int)
parse_switches(j_decompress_ptr cinfo,int argc,char ** argv,int last_file_arg_seen,boolean for_real)192 parse_switches(j_decompress_ptr cinfo, int argc, char **argv,
193                int last_file_arg_seen, boolean for_real)
194 /* Parse optional switches.
195  * Returns argv[] index of first file-name argument (== argc if none).
196  * Any file names with indexes <= last_file_arg_seen are ignored;
197  * they have presumably been processed in a previous iteration.
198  * (Pass 0 for last_file_arg_seen on the first or only iteration.)
199  * for_real is FALSE on the first (dummy) pass; we may skip any expensive
200  * processing.
201  */
202 {
203   int argn;
204   char *arg;
205 
206   /* Set up default JPEG parameters. */
207   requested_fmt = DEFAULT_FMT;  /* set default output file format */
208   icc_filename = NULL;
209   max_scans = 0;
210   outfilename = NULL;
211   memsrc = FALSE;
212   report = FALSE;
213   skip = FALSE;
214   crop = FALSE;
215   strict = FALSE;
216   cinfo->err->trace_level = 0;
217 
218   /* Scan command line options, adjust parameters */
219 
220   for (argn = 1; argn < argc; argn++) {
221     arg = argv[argn];
222     if (*arg != '-') {
223       /* Not a switch, must be a file name argument */
224       if (argn <= last_file_arg_seen) {
225         outfilename = NULL;     /* -outfile applies to just one input file */
226         continue;               /* ignore this name if previously processed */
227       }
228       break;                    /* else done parsing switches */
229     }
230     arg++;                      /* advance past switch marker character */
231 
232     if (keymatch(arg, "bmp", 1)) {
233       /* BMP output format (Windows flavor). */
234       requested_fmt = FMT_BMP;
235 
236     } else if (keymatch(arg, "colors", 1) || keymatch(arg, "colours", 1) ||
237                keymatch(arg, "quantize", 1) || keymatch(arg, "quantise", 1)) {
238       /* Do color quantization. */
239       int val;
240 
241       if (++argn >= argc)       /* advance to next argument */
242         usage();
243       if (sscanf(argv[argn], "%d", &val) != 1)
244         usage();
245       cinfo->desired_number_of_colors = val;
246       cinfo->quantize_colors = TRUE;
247 
248     } else if (keymatch(arg, "dct", 2)) {
249       /* Select IDCT algorithm. */
250       if (++argn >= argc)       /* advance to next argument */
251         usage();
252       if (keymatch(argv[argn], "int", 1)) {
253         cinfo->dct_method = JDCT_ISLOW;
254       } else if (keymatch(argv[argn], "fast", 2)) {
255         cinfo->dct_method = JDCT_IFAST;
256       } else if (keymatch(argv[argn], "float", 2)) {
257         cinfo->dct_method = JDCT_FLOAT;
258       } else
259         usage();
260 
261     } else if (keymatch(arg, "dither", 2)) {
262       /* Select dithering algorithm. */
263       if (++argn >= argc)       /* advance to next argument */
264         usage();
265       if (keymatch(argv[argn], "fs", 2)) {
266         cinfo->dither_mode = JDITHER_FS;
267       } else if (keymatch(argv[argn], "none", 2)) {
268         cinfo->dither_mode = JDITHER_NONE;
269       } else if (keymatch(argv[argn], "ordered", 2)) {
270         cinfo->dither_mode = JDITHER_ORDERED;
271       } else
272         usage();
273 
274     } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
275       /* Enable debug printouts. */
276       /* On first -d, print version identification */
277       static boolean printed_version = FALSE;
278 
279       if (!printed_version) {
280         fprintf(stderr, "%s version %s (build %s)\n",
281                 PACKAGE_NAME, VERSION, BUILD);
282         fprintf(stderr, "%s\n\n", JCOPYRIGHT);
283         fprintf(stderr, "Emulating The Independent JPEG Group's software, version %s\n\n",
284                 JVERSION);
285         printed_version = TRUE;
286       }
287       cinfo->err->trace_level++;
288 
289     } else if (keymatch(arg, "version", 4)) {
290       fprintf(stderr, "%s version %s (build %s)\n",
291               PACKAGE_NAME, VERSION, BUILD);
292       exit(EXIT_SUCCESS);
293 
294     } else if (keymatch(arg, "fast", 1)) {
295       /* Select recommended processing options for quick-and-dirty output. */
296       cinfo->two_pass_quantize = FALSE;
297       cinfo->dither_mode = JDITHER_ORDERED;
298       if (!cinfo->quantize_colors) /* don't override an earlier -colors */
299         cinfo->desired_number_of_colors = 216;
300       cinfo->dct_method = JDCT_FASTEST;
301       cinfo->do_fancy_upsampling = FALSE;
302 
303     } else if (keymatch(arg, "gif", 1)) {
304       /* GIF output format (LZW-compressed). */
305       requested_fmt = FMT_GIF;
306 
307     } else if (keymatch(arg, "gif0", 4)) {
308       /* GIF output format (uncompressed). */
309       requested_fmt = FMT_GIF0;
310 
311     } else if (keymatch(arg, "grayscale", 2) ||
312                keymatch(arg, "greyscale", 2)) {
313       /* Force monochrome output. */
314       cinfo->out_color_space = JCS_GRAYSCALE;
315 
316     } else if (keymatch(arg, "rgb", 2)) {
317       /* Force RGB output. */
318       cinfo->out_color_space = JCS_RGB;
319 
320     } else if (keymatch(arg, "rgb565", 2)) {
321       /* Force RGB565 output. */
322       cinfo->out_color_space = JCS_RGB565;
323 
324     } else if (keymatch(arg, "icc", 1)) {
325       /* Set ICC filename. */
326       if (++argn >= argc)       /* advance to next argument */
327         usage();
328       icc_filename = argv[argn];
329       jpeg_save_markers(cinfo, JPEG_APP0 + 2, 0xFFFF);
330 
331     } else if (keymatch(arg, "map", 3)) {
332       /* Quantize to a color map taken from an input file. */
333       if (++argn >= argc)       /* advance to next argument */
334         usage();
335       if (for_real) {           /* too expensive to do twice! */
336 #ifdef QUANT_2PASS_SUPPORTED    /* otherwise can't quantize to supplied map */
337         FILE *mapfile;
338 
339         if ((mapfile = fopen(argv[argn], READ_BINARY)) == NULL) {
340           fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
341           exit(EXIT_FAILURE);
342         }
343         read_color_map(cinfo, mapfile);
344         fclose(mapfile);
345         cinfo->quantize_colors = TRUE;
346 #else
347         ERREXIT(cinfo, JERR_NOT_COMPILED);
348 #endif
349       }
350 
351     } else if (keymatch(arg, "maxmemory", 3)) {
352       /* Maximum memory in Kb (or Mb with 'm'). */
353       long lval;
354       char ch = 'x';
355 
356       if (++argn >= argc)       /* advance to next argument */
357         usage();
358       if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
359         usage();
360       if (ch == 'm' || ch == 'M')
361         lval *= 1000L;
362       cinfo->mem->max_memory_to_use = lval * 1000L;
363 
364     } else if (keymatch(arg, "maxscans", 4)) {
365       if (++argn >= argc)       /* advance to next argument */
366         usage();
367       if (sscanf(argv[argn], "%u", &max_scans) != 1)
368         usage();
369 
370     } else if (keymatch(arg, "nosmooth", 3)) {
371       /* Suppress fancy upsampling */
372       cinfo->do_fancy_upsampling = FALSE;
373 
374     } else if (keymatch(arg, "onepass", 3)) {
375       /* Use fast one-pass quantization. */
376       cinfo->two_pass_quantize = FALSE;
377 
378     } else if (keymatch(arg, "os2", 3)) {
379       /* BMP output format (OS/2 flavor). */
380       requested_fmt = FMT_OS2;
381 
382     } else if (keymatch(arg, "outfile", 4)) {
383       /* Set output file name. */
384       if (++argn >= argc)       /* advance to next argument */
385         usage();
386       outfilename = argv[argn]; /* save it away for later use */
387 
388     } else if (keymatch(arg, "memsrc", 2)) {
389       /* Use in-memory source manager */
390 #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
391       memsrc = TRUE;
392 #else
393       fprintf(stderr, "%s: sorry, in-memory source manager was not compiled in\n",
394               progname);
395       exit(EXIT_FAILURE);
396 #endif
397 
398     } else if (keymatch(arg, "pnm", 1) || keymatch(arg, "ppm", 1)) {
399       /* PPM/PGM output format. */
400       requested_fmt = FMT_PPM;
401 
402     } else if (keymatch(arg, "report", 2)) {
403       report = TRUE;
404 
405     } else if (keymatch(arg, "scale", 2)) {
406       /* Scale the output image by a fraction M/N. */
407       if (++argn >= argc)       /* advance to next argument */
408         usage();
409       if (sscanf(argv[argn], "%u/%u",
410                  &cinfo->scale_num, &cinfo->scale_denom) != 2)
411         usage();
412 
413     } else if (keymatch(arg, "skip", 2)) {
414       if (++argn >= argc)
415         usage();
416       if (sscanf(argv[argn], "%u,%u", &skip_start, &skip_end) != 2 ||
417           skip_start > skip_end)
418         usage();
419       skip = TRUE;
420 
421     } else if (keymatch(arg, "crop", 2)) {
422       char c;
423       if (++argn >= argc)
424         usage();
425       if (sscanf(argv[argn], "%u%c%u+%u+%u", &crop_width, &c, &crop_height,
426                  &crop_x, &crop_y) != 5 ||
427           (c != 'X' && c != 'x') || crop_width < 1 || crop_height < 1)
428         usage();
429       crop = TRUE;
430 
431     } else if (keymatch(arg, "strict", 2)) {
432       strict = TRUE;
433 
434     } else if (keymatch(arg, "targa", 1)) {
435       /* Targa output format. */
436       requested_fmt = FMT_TARGA;
437 
438     } else {
439       usage();                  /* bogus switch */
440     }
441   }
442 
443   return argn;                  /* return index of next arg (file name) */
444 }
445 
446 
447 /*
448  * Marker processor for COM and interesting APPn markers.
449  * This replaces the library's built-in processor, which just skips the marker.
450  * We want to print out the marker as text, to the extent possible.
451  * Note this code relies on a non-suspending data source.
452  */
453 
454 LOCAL(unsigned int)
jpeg_getc(j_decompress_ptr cinfo)455 jpeg_getc(j_decompress_ptr cinfo)
456 /* Read next byte */
457 {
458   struct jpeg_source_mgr *datasrc = cinfo->src;
459 
460   if (datasrc->bytes_in_buffer == 0) {
461     if (!(*datasrc->fill_input_buffer) (cinfo))
462       ERREXIT(cinfo, JERR_CANT_SUSPEND);
463   }
464   datasrc->bytes_in_buffer--;
465   return *datasrc->next_input_byte++;
466 }
467 
468 
469 METHODDEF(boolean)
print_text_marker(j_decompress_ptr cinfo)470 print_text_marker(j_decompress_ptr cinfo)
471 {
472   boolean traceit = (cinfo->err->trace_level >= 1);
473   long length;
474   unsigned int ch;
475   unsigned int lastch = 0;
476 
477   length = jpeg_getc(cinfo) << 8;
478   length += jpeg_getc(cinfo);
479   length -= 2;                  /* discount the length word itself */
480 
481   if (traceit) {
482     if (cinfo->unread_marker == JPEG_COM)
483       fprintf(stderr, "Comment, length %ld:\n", (long)length);
484     else                        /* assume it is an APPn otherwise */
485       fprintf(stderr, "APP%d, length %ld:\n",
486               cinfo->unread_marker - JPEG_APP0, (long)length);
487   }
488 
489   while (--length >= 0) {
490     ch = jpeg_getc(cinfo);
491     if (traceit) {
492       /* Emit the character in a readable form.
493        * Nonprintables are converted to \nnn form,
494        * while \ is converted to \\.
495        * Newlines in CR, CR/LF, or LF form will be printed as one newline.
496        */
497       if (ch == '\r') {
498         fprintf(stderr, "\n");
499       } else if (ch == '\n') {
500         if (lastch != '\r')
501           fprintf(stderr, "\n");
502       } else if (ch == '\\') {
503         fprintf(stderr, "\\\\");
504       } else if (isprint(ch)) {
505         putc(ch, stderr);
506       } else {
507         fprintf(stderr, "\\%03o", ch);
508       }
509       lastch = ch;
510     }
511   }
512 
513   if (traceit)
514     fprintf(stderr, "\n");
515 
516   return TRUE;
517 }
518 
519 
520 METHODDEF(void)
my_emit_message(j_common_ptr cinfo,int msg_level)521 my_emit_message(j_common_ptr cinfo, int msg_level)
522 {
523   if (msg_level < 0) {
524     /* Treat warning as fatal */
525     cinfo->err->error_exit(cinfo);
526   } else {
527     if (cinfo->err->trace_level >= msg_level)
528       cinfo->err->output_message(cinfo);
529   }
530 }
531 
532 
533 /*
534  * The main program.
535  */
536 
537 int
538 #ifdef GTEST
djpeg(int argc,char ** argv)539 djpeg(int argc, char **argv)
540 #else
541 main(int argc, char **argv)
542 #endif
543 {
544   struct jpeg_decompress_struct cinfo;
545   struct jpeg_error_mgr jerr;
546   struct cdjpeg_progress_mgr progress;
547   int file_index;
548   djpeg_dest_ptr dest_mgr = NULL;
549   FILE *input_file;
550   FILE *output_file;
551   unsigned char *inbuffer = NULL;
552 #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
553   unsigned long insize = 0;
554 #endif
555   JDIMENSION num_scanlines;
556 
557   /* On Mac, fetch a command line. */
558 #ifdef USE_CCOMMAND
559   argc = ccommand(&argv);
560 #endif
561 
562   progname = argv[0];
563   if (progname == NULL || progname[0] == 0)
564     progname = "djpeg";         /* in case C library doesn't provide it */
565 
566   /* Initialize the JPEG decompression object with default error handling. */
567   cinfo.err = jpeg_std_error(&jerr);
568   jpeg_create_decompress(&cinfo);
569   /* Add some application-specific error messages (from cderror.h) */
570   jerr.addon_message_table = cdjpeg_message_table;
571   jerr.first_addon_message = JMSG_FIRSTADDONCODE;
572   jerr.last_addon_message = JMSG_LASTADDONCODE;
573 
574   /* Insert custom marker processor for COM and APP12.
575    * APP12 is used by some digital camera makers for textual info,
576    * so we provide the ability to display it as text.
577    * If you like, additional APPn marker types can be selected for display,
578    * but don't try to override APP0 or APP14 this way (see libjpeg.txt).
579    */
580   jpeg_set_marker_processor(&cinfo, JPEG_COM, print_text_marker);
581   jpeg_set_marker_processor(&cinfo, JPEG_APP0 + 12, print_text_marker);
582 
583   /* Scan command line to find file names. */
584   /* It is convenient to use just one switch-parsing routine, but the switch
585    * values read here are ignored; we will rescan the switches after opening
586    * the input file.
587    * (Exception: tracing level set here controls verbosity for COM markers
588    * found during jpeg_read_header...)
589    */
590 
591   file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
592 
593   if (strict)
594     jerr.emit_message = my_emit_message;
595 
596 #ifdef TWO_FILE_COMMANDLINE
597   /* Must have either -outfile switch or explicit output file name */
598   if (outfilename == NULL) {
599     if (file_index != argc - 2) {
600       fprintf(stderr, "%s: must name one input and one output file\n",
601               progname);
602       usage();
603     }
604     outfilename = argv[file_index + 1];
605   } else {
606     if (file_index != argc - 1) {
607       fprintf(stderr, "%s: must name one input and one output file\n",
608               progname);
609       usage();
610     }
611   }
612 #else
613   /* Unix style: expect zero or one file name */
614   if (file_index < argc - 1) {
615     fprintf(stderr, "%s: only one input file\n", progname);
616     usage();
617   }
618 #endif /* TWO_FILE_COMMANDLINE */
619 
620   /* Open the input file. */
621   if (file_index < argc) {
622     if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
623       fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
624       return EXIT_FAILURE;
625     }
626   } else {
627     /* default input file is stdin */
628     input_file = read_stdin();
629   }
630 
631   /* Open the output file. */
632   if (outfilename != NULL) {
633     if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
634       fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
635       return EXIT_FAILURE;
636     }
637   } else {
638     /* default output file is stdout */
639     output_file = write_stdout();
640   }
641 
642   if (report || max_scans != 0) {
643     start_progress_monitor((j_common_ptr)&cinfo, &progress);
644     progress.report = report;
645     progress.max_scans = max_scans;
646   }
647 
648   /* Specify data source for decompression */
649 #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
650   if (memsrc) {
651     size_t nbytes;
652     do {
653       inbuffer = (unsigned char *)realloc(inbuffer, insize + INPUT_BUF_SIZE);
654       if (inbuffer == NULL) {
655         fprintf(stderr, "%s: memory allocation failure\n", progname);
656         return EXIT_FAILURE;
657       }
658       nbytes = JFREAD(input_file, &inbuffer[insize], INPUT_BUF_SIZE);
659       if (nbytes < INPUT_BUF_SIZE && ferror(input_file)) {
660         if (file_index < argc)
661           fprintf(stderr, "%s: can't read from %s\n", progname,
662                   argv[file_index]);
663         else
664           fprintf(stderr, "%s: can't read from stdin\n", progname);
665       }
666       insize += (unsigned long)nbytes;
667     } while (nbytes == INPUT_BUF_SIZE);
668     fprintf(stderr, "Compressed size:  %lu bytes\n", insize);
669     jpeg_mem_src(&cinfo, inbuffer, insize);
670   } else
671 #endif
672     jpeg_stdio_src(&cinfo, input_file);
673 
674   /* Read file header, set default decompression parameters */
675   (void)jpeg_read_header(&cinfo, TRUE);
676 
677   /* Adjust default decompression parameters by re-parsing the options */
678   file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
679 
680   /* Initialize the output module now to let it override any crucial
681    * option settings (for instance, GIF wants to force color quantization).
682    */
683   switch (requested_fmt) {
684 #ifdef BMP_SUPPORTED
685   case FMT_BMP:
686     dest_mgr = jinit_write_bmp(&cinfo, FALSE, TRUE);
687     break;
688   case FMT_OS2:
689     dest_mgr = jinit_write_bmp(&cinfo, TRUE, TRUE);
690     break;
691 #endif
692 #ifdef GIF_SUPPORTED
693   case FMT_GIF:
694     dest_mgr = jinit_write_gif(&cinfo, TRUE);
695     break;
696   case FMT_GIF0:
697     dest_mgr = jinit_write_gif(&cinfo, FALSE);
698     break;
699 #endif
700 #ifdef PPM_SUPPORTED
701   case FMT_PPM:
702     dest_mgr = jinit_write_ppm(&cinfo);
703     break;
704 #endif
705 #ifdef TARGA_SUPPORTED
706   case FMT_TARGA:
707     dest_mgr = jinit_write_targa(&cinfo);
708     break;
709 #endif
710   default:
711     ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT);
712     break;
713   }
714   dest_mgr->output_file = output_file;
715 
716   /* Start decompressor */
717   (void)jpeg_start_decompress(&cinfo);
718 
719   /* Skip rows */
720   if (skip) {
721     JDIMENSION tmp;
722 
723     /* Check for valid skip_end.  We cannot check this value until after
724      * jpeg_start_decompress() is called.  Note that we have already verified
725      * that skip_start <= skip_end.
726      */
727     if (skip_end > cinfo.output_height - 1) {
728       fprintf(stderr, "%s: skip region exceeds image height %d\n", progname,
729               cinfo.output_height);
730       return EXIT_FAILURE;
731     }
732 
733     /* Write output file header.  This is a hack to ensure that the destination
734      * manager creates an output image of the proper size.
735      */
736     tmp = cinfo.output_height;
737     cinfo.output_height -= (skip_end - skip_start + 1);
738     (*dest_mgr->start_output) (&cinfo, dest_mgr);
739     cinfo.output_height = tmp;
740 
741     /* Process data */
742     while (cinfo.output_scanline < skip_start) {
743       num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
744                                           dest_mgr->buffer_height);
745       (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
746     }
747     if ((tmp = jpeg_skip_scanlines(&cinfo, skip_end - skip_start + 1)) !=
748         skip_end - skip_start + 1) {
749       fprintf(stderr, "%s: jpeg_skip_scanlines() returned %d rather than %d\n",
750               progname, tmp, skip_end - skip_start + 1);
751       return EXIT_FAILURE;
752     }
753     while (cinfo.output_scanline < cinfo.output_height) {
754       num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
755                                           dest_mgr->buffer_height);
756       (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
757     }
758 
759   /* Decompress a subregion */
760   } else if (crop) {
761     JDIMENSION tmp;
762 
763     /* Check for valid crop dimensions.  We cannot check these values until
764      * after jpeg_start_decompress() is called.
765      */
766     if (crop_x + crop_width > cinfo.output_width ||
767         crop_y + crop_height > cinfo.output_height) {
768       fprintf(stderr, "%s: crop dimensions exceed image dimensions %d x %d\n",
769               progname, cinfo.output_width, cinfo.output_height);
770       return EXIT_FAILURE;
771     }
772 
773     jpeg_crop_scanline(&cinfo, &crop_x, &crop_width);
774     if (dest_mgr->calc_buffer_dimensions)
775       (*dest_mgr->calc_buffer_dimensions) (&cinfo, dest_mgr);
776     else
777       ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT);
778 
779     /* Write output file header.  This is a hack to ensure that the destination
780      * manager creates an output image of the proper size.
781      */
782     tmp = cinfo.output_height;
783     cinfo.output_height = crop_height;
784     (*dest_mgr->start_output) (&cinfo, dest_mgr);
785     cinfo.output_height = tmp;
786 
787     /* Process data */
788     if ((tmp = jpeg_skip_scanlines(&cinfo, crop_y)) != crop_y) {
789       fprintf(stderr, "%s: jpeg_skip_scanlines() returned %d rather than %d\n",
790               progname, tmp, crop_y);
791       return EXIT_FAILURE;
792     }
793     while (cinfo.output_scanline < crop_y + crop_height) {
794       num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
795                                           dest_mgr->buffer_height);
796       (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
797     }
798     if ((tmp =
799          jpeg_skip_scanlines(&cinfo,
800                              cinfo.output_height - crop_y - crop_height)) !=
801         cinfo.output_height - crop_y - crop_height) {
802       fprintf(stderr, "%s: jpeg_skip_scanlines() returned %d rather than %d\n",
803               progname, tmp, cinfo.output_height - crop_y - crop_height);
804       return EXIT_FAILURE;
805     }
806 
807   /* Normal full-image decompress */
808   } else {
809     /* Write output file header */
810     (*dest_mgr->start_output) (&cinfo, dest_mgr);
811 
812     /* Process data */
813     while (cinfo.output_scanline < cinfo.output_height) {
814       num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
815                                           dest_mgr->buffer_height);
816       (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
817     }
818   }
819 
820   /* Hack: count final pass as done in case finish_output does an extra pass.
821    * The library won't have updated completed_passes.
822    */
823   if (report || max_scans != 0)
824     progress.pub.completed_passes = progress.pub.total_passes;
825 
826   if (icc_filename != NULL) {
827     FILE *icc_file;
828     JOCTET *icc_profile;
829     unsigned int icc_len;
830 
831     if ((icc_file = fopen(icc_filename, WRITE_BINARY)) == NULL) {
832       fprintf(stderr, "%s: can't open %s\n", progname, icc_filename);
833       return EXIT_FAILURE;
834     }
835     if (jpeg_read_icc_profile(&cinfo, &icc_profile, &icc_len)) {
836       if (fwrite(icc_profile, icc_len, 1, icc_file) < 1) {
837         fprintf(stderr, "%s: can't read ICC profile from %s\n", progname,
838                 icc_filename);
839         free(icc_profile);
840         fclose(icc_file);
841         return EXIT_FAILURE;
842       }
843       free(icc_profile);
844       fclose(icc_file);
845     } else if (cinfo.err->msg_code != JWRN_BOGUS_ICC)
846       fprintf(stderr, "%s: no ICC profile data in JPEG file\n", progname);
847   }
848 
849   /* Finish decompression and release memory.
850    * I must do it in this order because output module has allocated memory
851    * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory.
852    */
853   (*dest_mgr->finish_output) (&cinfo, dest_mgr);
854   (void)jpeg_finish_decompress(&cinfo);
855   jpeg_destroy_decompress(&cinfo);
856 
857   /* Close files, if we opened them */
858   if (input_file != stdin)
859     fclose(input_file);
860   if (output_file != stdout)
861     fclose(output_file);
862 
863   if (report || max_scans != 0)
864     end_progress_monitor((j_common_ptr)&cinfo);
865 
866   if (memsrc)
867     free(inbuffer);
868 
869   /* All done. */
870   return (jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
871 }
872