1 /*
2  * cjpeg.c
3  *
4  * This file was part of the Independent JPEG Group's software:
5  * Copyright (C) 1991-1998, Thomas G. Lane.
6  * Modified 2003-2011 by Guido Vollbeding.
7  * libjpeg-turbo Modifications:
8  * Copyright (C) 2010, 2013-2014, 2017, 2019-2021, D. R. Commander.
9  * For conditions of distribution and use, see the accompanying README.ijg
10  * file.
11  *
12  * This file contains a command-line user interface for the JPEG compressor.
13  * It should work on any system with Unix- or MS-DOS-style command lines.
14  *
15  * Two different command line styles are permitted, depending on the
16  * compile-time switch TWO_FILE_COMMANDLINE:
17  *      cjpeg [options]  inputfile outputfile
18  *      cjpeg [options]  [inputfile]
19  * In the second style, output is always to standard output, which you'd
20  * normally redirect to a file or pipe to some other program.  Input is
21  * either from a named file or from standard input (typically redirected).
22  * The second style is convenient on Unix but is unhelpful on systems that
23  * don't support pipes.  Also, you MUST use the first style if your system
24  * doesn't do binary I/O to stdin/stdout.
25  * To simplify script writing, the "-outfile" switch is provided.  The syntax
26  *      cjpeg [options]  -outfile outputfile  inputfile
27  * works regardless of which command line style is used.
28  */
29 
30 #ifdef CJPEG_FUZZER
31 #define JPEG_INTERNALS
32 #endif
33 #include "cdjpeg.h"             /* Common decls for cjpeg/djpeg applications */
34 #include "jversion.h"           /* for version message */
35 #include "jconfigint.h"
36 
37 #ifndef HAVE_STDLIB_H           /* <stdlib.h> should declare malloc(),free() */
38 extern void *malloc(size_t size);
39 extern void free(void *ptr);
40 #endif
41 
42 #ifdef USE_CCOMMAND             /* command-line reader for Macintosh */
43 #ifdef __MWERKS__
44 #include <SIOUX.h>              /* Metrowerks needs this */
45 #include <console.h>            /* ... and this */
46 #endif
47 #ifdef THINK_C
48 #include <console.h>            /* Think declares it here */
49 #endif
50 #endif
51 
52 
53 /* Create the add-on message string table. */
54 
55 #define JMESSAGE(code, string)  string,
56 
57 static const char * const cdjpeg_message_table[] = {
58 #include "cderror.h"
59   NULL
60 };
61 
62 
63 /*
64  * This routine determines what format the input file is,
65  * and selects the appropriate input-reading module.
66  *
67  * To determine which family of input formats the file belongs to,
68  * we may look only at the first byte of the file, since C does not
69  * guarantee that more than one character can be pushed back with ungetc.
70  * Looking at additional bytes would require one of these approaches:
71  *     1) assume we can fseek() the input file (fails for piped input);
72  *     2) assume we can push back more than one character (works in
73  *        some C implementations, but unportable);
74  *     3) provide our own buffering (breaks input readers that want to use
75  *        stdio directly);
76  * or  4) don't put back the data, and modify the input_init methods to assume
77  *        they start reading after the start of file.
78  * #1 is attractive for MS-DOS but is untenable on Unix.
79  *
80  * The most portable solution for file types that can't be identified by their
81  * first byte is to make the user tell us what they are.  This is also the
82  * only approach for "raw" file types that contain only arbitrary values.
83  * We presently apply this method for Targa files.  Most of the time Targa
84  * files start with 0x00, so we recognize that case.  Potentially, however,
85  * a Targa file could start with any byte value (byte 0 is the length of the
86  * seldom-used ID field), so we provide a switch to force Targa input mode.
87  */
88 
89 static boolean is_targa;        /* records user -targa switch */
90 
91 
92 LOCAL(cjpeg_source_ptr)
select_file_type(j_compress_ptr cinfo,FILE * infile)93 select_file_type(j_compress_ptr cinfo, FILE *infile)
94 {
95   int c;
96 
97   if (is_targa) {
98 #ifdef TARGA_SUPPORTED
99     return jinit_read_targa(cinfo);
100 #else
101     ERREXIT(cinfo, JERR_TGA_NOTCOMP);
102 #endif
103   }
104 
105   if ((c = getc(infile)) == EOF)
106     ERREXIT(cinfo, JERR_INPUT_EMPTY);
107   if (ungetc(c, infile) == EOF)
108     ERREXIT(cinfo, JERR_UNGETC_FAILED);
109 
110   switch (c) {
111 #ifdef BMP_SUPPORTED
112   case 'B':
113     return jinit_read_bmp(cinfo, TRUE);
114 #endif
115 #ifdef GIF_SUPPORTED
116   case 'G':
117     return jinit_read_gif(cinfo);
118 #endif
119 #ifdef PPM_SUPPORTED
120   case 'P':
121     return jinit_read_ppm(cinfo);
122 #endif
123 #ifdef TARGA_SUPPORTED
124   case 0x00:
125     return jinit_read_targa(cinfo);
126 #endif
127   default:
128     ERREXIT(cinfo, JERR_UNKNOWN_FORMAT);
129     break;
130   }
131 
132   return NULL;                  /* suppress compiler warnings */
133 }
134 
135 
136 /*
137  * Argument-parsing code.
138  * The switch parser is designed to be useful with DOS-style command line
139  * syntax, ie, intermixed switches and file names, where only the switches
140  * to the left of a given file name affect processing of that file.
141  * The main program in this file doesn't actually use this capability...
142  */
143 
144 
145 static const char *progname;    /* program name for error messages */
146 static char *icc_filename;      /* for -icc switch */
147 static char *outfilename;       /* for -outfile switch */
148 boolean memdst;                 /* for -memdst switch */
149 boolean report;                 /* for -report switch */
150 
151 
152 #ifdef CJPEG_FUZZER
153 
154 #include <setjmp.h>
155 
156 struct my_error_mgr {
157   struct jpeg_error_mgr pub;
158   jmp_buf setjmp_buffer;
159 };
160 
my_error_exit(j_common_ptr cinfo)161 void my_error_exit(j_common_ptr cinfo)
162 {
163   struct my_error_mgr *myerr = (struct my_error_mgr *)cinfo->err;
164 
165   longjmp(myerr->setjmp_buffer, 1);
166 }
167 
my_emit_message(j_common_ptr cinfo,int msg_level)168 static void my_emit_message(j_common_ptr cinfo, int msg_level)
169 {
170   if (msg_level < 0)
171     cinfo->err->num_warnings++;
172 }
173 
174 #define HANDLE_ERROR() { \
175   if (cinfo.global_state > CSTATE_START) { \
176     if (memdst && outbuffer) \
177       (*cinfo.dest->term_destination) (&cinfo); \
178     jpeg_abort_compress(&cinfo); \
179   } \
180   jpeg_destroy_compress(&cinfo); \
181   if (input_file != stdin && input_file != NULL) \
182     fclose(input_file); \
183   if (memdst) \
184     free(outbuffer); \
185   return EXIT_FAILURE; \
186 }
187 
188 #endif
189 
190 
191 LOCAL(void)
usage(void)192 usage(void)
193 /* complain about bad command line */
194 {
195   fprintf(stderr, "usage: %s [switches] ", progname);
196 #ifdef TWO_FILE_COMMANDLINE
197   fprintf(stderr, "inputfile outputfile\n");
198 #else
199   fprintf(stderr, "[inputfile]\n");
200 #endif
201 
202   fprintf(stderr, "Switches (names may be abbreviated):\n");
203   fprintf(stderr, "  -quality N[,...]   Compression quality (0..100; 5-95 is most useful range,\n");
204   fprintf(stderr, "                     default is 75)\n");
205   fprintf(stderr, "  -grayscale     Create monochrome JPEG file\n");
206   fprintf(stderr, "  -rgb           Create RGB JPEG file\n");
207 #ifdef ENTROPY_OPT_SUPPORTED
208   fprintf(stderr, "  -optimize      Optimize Huffman table (smaller file, but slow compression)\n");
209 #endif
210 #ifdef C_PROGRESSIVE_SUPPORTED
211   fprintf(stderr, "  -progressive   Create progressive JPEG file\n");
212 #endif
213 #ifdef TARGA_SUPPORTED
214   fprintf(stderr, "  -targa         Input file is Targa format (usually not needed)\n");
215 #endif
216   fprintf(stderr, "Switches for advanced users:\n");
217 #ifdef C_ARITH_CODING_SUPPORTED
218   fprintf(stderr, "  -arithmetic    Use arithmetic coding\n");
219 #endif
220 #ifdef DCT_ISLOW_SUPPORTED
221   fprintf(stderr, "  -dct int       Use accurate integer DCT method%s\n",
222           (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
223 #endif
224 #ifdef DCT_IFAST_SUPPORTED
225   fprintf(stderr, "  -dct fast      Use less accurate integer DCT method [legacy feature]%s\n",
226           (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
227 #endif
228 #ifdef DCT_FLOAT_SUPPORTED
229   fprintf(stderr, "  -dct float     Use floating-point DCT method [legacy feature]%s\n",
230           (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
231 #endif
232   fprintf(stderr, "  -icc FILE      Embed ICC profile contained in FILE\n");
233   fprintf(stderr, "  -restart N     Set restart interval in rows, or in blocks with B\n");
234 #ifdef INPUT_SMOOTHING_SUPPORTED
235   fprintf(stderr, "  -smooth N      Smooth dithered input (N=1..100 is strength)\n");
236 #endif
237   fprintf(stderr, "  -maxmemory N   Maximum memory to use (in kbytes)\n");
238   fprintf(stderr, "  -outfile name  Specify name for output file\n");
239 #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
240   fprintf(stderr, "  -memdst        Compress to memory instead of file (useful for benchmarking)\n");
241 #endif
242   fprintf(stderr, "  -report        Report compression progress\n");
243   fprintf(stderr, "  -verbose  or  -debug   Emit debug output\n");
244   fprintf(stderr, "  -version       Print version information and exit\n");
245   fprintf(stderr, "Switches for wizards:\n");
246   fprintf(stderr, "  -baseline      Force baseline quantization tables\n");
247   fprintf(stderr, "  -qtables FILE  Use quantization tables given in FILE\n");
248   fprintf(stderr, "  -qslots N[,...]    Set component quantization tables\n");
249   fprintf(stderr, "  -sample HxV[,...]  Set component sampling factors\n");
250 #ifdef C_MULTISCAN_FILES_SUPPORTED
251   fprintf(stderr, "  -scans FILE    Create multi-scan JPEG per script FILE\n");
252 #endif
253   exit(EXIT_FAILURE);
254 }
255 
256 
257 LOCAL(int)
parse_switches(j_compress_ptr cinfo,int argc,char ** argv,int last_file_arg_seen,boolean for_real)258 parse_switches(j_compress_ptr cinfo, int argc, char **argv,
259                int last_file_arg_seen, boolean for_real)
260 /* Parse optional switches.
261  * Returns argv[] index of first file-name argument (== argc if none).
262  * Any file names with indexes <= last_file_arg_seen are ignored;
263  * they have presumably been processed in a previous iteration.
264  * (Pass 0 for last_file_arg_seen on the first or only iteration.)
265  * for_real is FALSE on the first (dummy) pass; we may skip any expensive
266  * processing.
267  */
268 {
269   int argn;
270   char *arg;
271   boolean force_baseline;
272   boolean simple_progressive;
273   char *qualityarg = NULL;      /* saves -quality parm if any */
274   char *qtablefile = NULL;      /* saves -qtables filename if any */
275   char *qslotsarg = NULL;       /* saves -qslots parm if any */
276   char *samplearg = NULL;       /* saves -sample parm if any */
277   char *scansarg = NULL;        /* saves -scans parm if any */
278 
279   /* Set up default JPEG parameters. */
280 
281   force_baseline = FALSE;       /* by default, allow 16-bit quantizers */
282   simple_progressive = FALSE;
283   is_targa = FALSE;
284   icc_filename = NULL;
285   outfilename = NULL;
286   memdst = FALSE;
287   report = FALSE;
288   cinfo->err->trace_level = 0;
289 
290   /* Scan command line options, adjust parameters */
291 
292   for (argn = 1; argn < argc; argn++) {
293     arg = argv[argn];
294     if (*arg != '-') {
295       /* Not a switch, must be a file name argument */
296       if (argn <= last_file_arg_seen) {
297         outfilename = NULL;     /* -outfile applies to just one input file */
298         continue;               /* ignore this name if previously processed */
299       }
300       break;                    /* else done parsing switches */
301     }
302     arg++;                      /* advance past switch marker character */
303 
304     if (keymatch(arg, "arithmetic", 1)) {
305       /* Use arithmetic coding. */
306 #ifdef C_ARITH_CODING_SUPPORTED
307       cinfo->arith_code = TRUE;
308 #else
309       fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
310               progname);
311       exit(EXIT_FAILURE);
312 #endif
313 
314     } else if (keymatch(arg, "baseline", 1)) {
315       /* Force baseline-compatible output (8-bit quantizer values). */
316       force_baseline = TRUE;
317 
318     } else if (keymatch(arg, "dct", 2)) {
319       /* Select DCT algorithm. */
320       if (++argn >= argc)       /* advance to next argument */
321         usage();
322       if (keymatch(argv[argn], "int", 1)) {
323         cinfo->dct_method = JDCT_ISLOW;
324       } else if (keymatch(argv[argn], "fast", 2)) {
325         cinfo->dct_method = JDCT_IFAST;
326       } else if (keymatch(argv[argn], "float", 2)) {
327         cinfo->dct_method = JDCT_FLOAT;
328       } else
329         usage();
330 
331     } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
332       /* Enable debug printouts. */
333       /* On first -d, print version identification */
334       static boolean printed_version = FALSE;
335 
336       if (!printed_version) {
337         fprintf(stderr, "%s version %s (build %s)\n",
338                 PACKAGE_NAME, VERSION, BUILD);
339         fprintf(stderr, "%s\n\n", JCOPYRIGHT);
340         fprintf(stderr, "Emulating The Independent JPEG Group's software, version %s\n\n",
341                 JVERSION);
342         printed_version = TRUE;
343       }
344       cinfo->err->trace_level++;
345 
346     } else if (keymatch(arg, "version", 4)) {
347       fprintf(stderr, "%s version %s (build %s)\n",
348               PACKAGE_NAME, VERSION, BUILD);
349       exit(EXIT_SUCCESS);
350 
351     } else if (keymatch(arg, "grayscale", 2) ||
352                keymatch(arg, "greyscale", 2)) {
353       /* Force a monochrome JPEG file to be generated. */
354       jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
355 
356     } else if (keymatch(arg, "rgb", 3)) {
357       /* Force an RGB JPEG file to be generated. */
358       jpeg_set_colorspace(cinfo, JCS_RGB);
359 
360     } else if (keymatch(arg, "icc", 1)) {
361       /* Set ICC filename. */
362       if (++argn >= argc)       /* advance to next argument */
363         usage();
364       icc_filename = argv[argn];
365 
366     } else if (keymatch(arg, "maxmemory", 3)) {
367       /* Maximum memory in Kb (or Mb with 'm'). */
368       long lval;
369       char ch = 'x';
370 
371       if (++argn >= argc)       /* advance to next argument */
372         usage();
373       if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
374         usage();
375       if (ch == 'm' || ch == 'M')
376         lval *= 1000L;
377       cinfo->mem->max_memory_to_use = lval * 1000L;
378 
379     } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
380       /* Enable entropy parm optimization. */
381 #ifdef ENTROPY_OPT_SUPPORTED
382       cinfo->optimize_coding = TRUE;
383 #else
384       fprintf(stderr, "%s: sorry, entropy optimization was not compiled in\n",
385               progname);
386       exit(EXIT_FAILURE);
387 #endif
388 
389     } else if (keymatch(arg, "outfile", 4)) {
390       /* Set output file name. */
391       if (++argn >= argc)       /* advance to next argument */
392         usage();
393       outfilename = argv[argn]; /* save it away for later use */
394 
395     } else if (keymatch(arg, "progressive", 1)) {
396       /* Select simple progressive mode. */
397 #ifdef C_PROGRESSIVE_SUPPORTED
398       simple_progressive = TRUE;
399       /* We must postpone execution until num_components is known. */
400 #else
401       fprintf(stderr, "%s: sorry, progressive output was not compiled in\n",
402               progname);
403       exit(EXIT_FAILURE);
404 #endif
405 
406     } else if (keymatch(arg, "memdst", 2)) {
407       /* Use in-memory destination manager */
408 #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
409       memdst = TRUE;
410 #else
411       fprintf(stderr, "%s: sorry, in-memory destination manager was not compiled in\n",
412               progname);
413       exit(EXIT_FAILURE);
414 #endif
415 
416     } else if (keymatch(arg, "quality", 1)) {
417       /* Quality ratings (quantization table scaling factors). */
418       if (++argn >= argc)       /* advance to next argument */
419         usage();
420       qualityarg = argv[argn];
421 
422     } else if (keymatch(arg, "qslots", 2)) {
423       /* Quantization table slot numbers. */
424       if (++argn >= argc)       /* advance to next argument */
425         usage();
426       qslotsarg = argv[argn];
427       /* Must delay setting qslots until after we have processed any
428        * colorspace-determining switches, since jpeg_set_colorspace sets
429        * default quant table numbers.
430        */
431 
432     } else if (keymatch(arg, "qtables", 2)) {
433       /* Quantization tables fetched from file. */
434       if (++argn >= argc)       /* advance to next argument */
435         usage();
436       qtablefile = argv[argn];
437       /* We postpone actually reading the file in case -quality comes later. */
438 
439     } else if (keymatch(arg, "report", 3)) {
440       report = TRUE;
441 
442     } else if (keymatch(arg, "restart", 1)) {
443       /* Restart interval in MCU rows (or in MCUs with 'b'). */
444       long lval;
445       char ch = 'x';
446 
447       if (++argn >= argc)       /* advance to next argument */
448         usage();
449       if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
450         usage();
451       if (lval < 0 || lval > 65535L)
452         usage();
453       if (ch == 'b' || ch == 'B') {
454         cinfo->restart_interval = (unsigned int)lval;
455         cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
456       } else {
457         cinfo->restart_in_rows = (int)lval;
458         /* restart_interval will be computed during startup */
459       }
460 
461     } else if (keymatch(arg, "sample", 2)) {
462       /* Set sampling factors. */
463       if (++argn >= argc)       /* advance to next argument */
464         usage();
465       samplearg = argv[argn];
466       /* Must delay setting sample factors until after we have processed any
467        * colorspace-determining switches, since jpeg_set_colorspace sets
468        * default sampling factors.
469        */
470 
471     } else if (keymatch(arg, "scans", 4)) {
472       /* Set scan script. */
473 #ifdef C_MULTISCAN_FILES_SUPPORTED
474       if (++argn >= argc)       /* advance to next argument */
475         usage();
476       scansarg = argv[argn];
477       /* We must postpone reading the file in case -progressive appears. */
478 #else
479       fprintf(stderr, "%s: sorry, multi-scan output was not compiled in\n",
480               progname);
481       exit(EXIT_FAILURE);
482 #endif
483 
484     } else if (keymatch(arg, "smooth", 2)) {
485       /* Set input smoothing factor. */
486       int val;
487 
488       if (++argn >= argc)       /* advance to next argument */
489         usage();
490       if (sscanf(argv[argn], "%d", &val) != 1)
491         usage();
492       if (val < 0 || val > 100)
493         usage();
494       cinfo->smoothing_factor = val;
495 
496     } else if (keymatch(arg, "targa", 1)) {
497       /* Input file is Targa format. */
498       is_targa = TRUE;
499 
500     } else {
501       usage();                  /* bogus switch */
502     }
503   }
504 
505   /* Post-switch-scanning cleanup */
506 
507   if (for_real) {
508 
509     /* Set quantization tables for selected quality. */
510     /* Some or all may be overridden if -qtables is present. */
511     if (qualityarg != NULL)     /* process -quality if it was present */
512       if (!set_quality_ratings(cinfo, qualityarg, force_baseline))
513         usage();
514 
515     if (qtablefile != NULL)     /* process -qtables if it was present */
516       if (!read_quant_tables(cinfo, qtablefile, force_baseline))
517         usage();
518 
519     if (qslotsarg != NULL)      /* process -qslots if it was present */
520       if (!set_quant_slots(cinfo, qslotsarg))
521         usage();
522 
523     if (samplearg != NULL)      /* process -sample if it was present */
524       if (!set_sample_factors(cinfo, samplearg))
525         usage();
526 
527 #ifdef C_PROGRESSIVE_SUPPORTED
528     if (simple_progressive)     /* process -progressive; -scans can override */
529       jpeg_simple_progression(cinfo);
530 #endif
531 
532 #ifdef C_MULTISCAN_FILES_SUPPORTED
533     if (scansarg != NULL)       /* process -scans if it was present */
534       if (!read_scan_script(cinfo, scansarg))
535         usage();
536 #endif
537   }
538 
539   return argn;                  /* return index of next arg (file name) */
540 }
541 
542 
543 /*
544  * The main program.
545  */
546 
547 int
main(int argc,char ** argv)548 main(int argc, char **argv)
549 {
550   struct jpeg_compress_struct cinfo;
551 #ifdef CJPEG_FUZZER
552   struct my_error_mgr myerr;
553   struct jpeg_error_mgr &jerr = myerr.pub;
554 #else
555   struct jpeg_error_mgr jerr;
556 #endif
557   struct cdjpeg_progress_mgr progress;
558   int file_index;
559   cjpeg_source_ptr src_mgr;
560   FILE *input_file = NULL;
561   FILE *icc_file;
562   JOCTET *icc_profile = NULL;
563   long icc_len = 0;
564   FILE *output_file = NULL;
565   unsigned char *outbuffer = NULL;
566   unsigned long outsize = 0;
567   JDIMENSION num_scanlines;
568 
569   /* On Mac, fetch a command line. */
570 #ifdef USE_CCOMMAND
571   argc = ccommand(&argv);
572 #endif
573 
574   progname = argv[0];
575   if (progname == NULL || progname[0] == 0)
576     progname = "cjpeg";         /* in case C library doesn't provide it */
577 
578   /* Initialize the JPEG compression object with default error handling. */
579   cinfo.err = jpeg_std_error(&jerr);
580   jpeg_create_compress(&cinfo);
581   /* Add some application-specific error messages (from cderror.h) */
582   jerr.addon_message_table = cdjpeg_message_table;
583   jerr.first_addon_message = JMSG_FIRSTADDONCODE;
584   jerr.last_addon_message = JMSG_LASTADDONCODE;
585 
586   /* Initialize JPEG parameters.
587    * Much of this may be overridden later.
588    * In particular, we don't yet know the input file's color space,
589    * but we need to provide some value for jpeg_set_defaults() to work.
590    */
591 
592   cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
593   jpeg_set_defaults(&cinfo);
594 
595   /* Scan command line to find file names.
596    * It is convenient to use just one switch-parsing routine, but the switch
597    * values read here are ignored; we will rescan the switches after opening
598    * the input file.
599    */
600 
601   file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
602 
603 #ifdef TWO_FILE_COMMANDLINE
604   if (!memdst) {
605     /* Must have either -outfile switch or explicit output file name */
606     if (outfilename == NULL) {
607       if (file_index != argc - 2) {
608         fprintf(stderr, "%s: must name one input and one output file\n",
609                 progname);
610         usage();
611       }
612       outfilename = argv[file_index + 1];
613     } else {
614       if (file_index != argc - 1) {
615         fprintf(stderr, "%s: must name one input and one output file\n",
616                 progname);
617         usage();
618       }
619     }
620   }
621 #else
622   /* Unix style: expect zero or one file name */
623   if (file_index < argc - 1) {
624     fprintf(stderr, "%s: only one input file\n", progname);
625     usage();
626   }
627 #endif /* TWO_FILE_COMMANDLINE */
628 
629   /* Open the input file. */
630   if (file_index < argc) {
631     if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
632       fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
633       exit(EXIT_FAILURE);
634     }
635   } else {
636     /* default input file is stdin */
637     input_file = read_stdin();
638   }
639 
640   /* Open the output file. */
641   if (outfilename != NULL) {
642     if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
643       fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
644       exit(EXIT_FAILURE);
645     }
646   } else if (!memdst) {
647     /* default output file is stdout */
648     output_file = write_stdout();
649   }
650 
651   if (icc_filename != NULL) {
652     if ((icc_file = fopen(icc_filename, READ_BINARY)) == NULL) {
653       fprintf(stderr, "%s: can't open %s\n", progname, icc_filename);
654       exit(EXIT_FAILURE);
655     }
656     if (fseek(icc_file, 0, SEEK_END) < 0 ||
657         (icc_len = ftell(icc_file)) < 1 ||
658         fseek(icc_file, 0, SEEK_SET) < 0) {
659       fprintf(stderr, "%s: can't determine size of %s\n", progname,
660               icc_filename);
661       exit(EXIT_FAILURE);
662     }
663     if ((icc_profile = (JOCTET *)malloc(icc_len)) == NULL) {
664       fprintf(stderr, "%s: can't allocate memory for ICC profile\n", progname);
665       fclose(icc_file);
666       exit(EXIT_FAILURE);
667     }
668     if (fread(icc_profile, icc_len, 1, icc_file) < 1) {
669       fprintf(stderr, "%s: can't read ICC profile from %s\n", progname,
670               icc_filename);
671       free(icc_profile);
672       fclose(icc_file);
673       exit(EXIT_FAILURE);
674     }
675     fclose(icc_file);
676   }
677 
678 #ifdef CJPEG_FUZZER
679   jerr.error_exit = my_error_exit;
680   jerr.emit_message = my_emit_message;
681   if (setjmp(myerr.setjmp_buffer))
682     HANDLE_ERROR()
683 #endif
684 
685   if (report) {
686     start_progress_monitor((j_common_ptr)&cinfo, &progress);
687     progress.report = report;
688   }
689 
690   /* Figure out the input file format, and set up to read it. */
691   src_mgr = select_file_type(&cinfo, input_file);
692   src_mgr->input_file = input_file;
693 #ifdef CJPEG_FUZZER
694   src_mgr->max_pixels = 1048576;
695 #endif
696 
697   /* Read the input file header to obtain file size & colorspace. */
698   (*src_mgr->start_input) (&cinfo, src_mgr);
699 
700   /* Now that we know input colorspace, fix colorspace-dependent defaults */
701   jpeg_default_colorspace(&cinfo);
702 
703   /* Adjust default compression parameters by re-parsing the options */
704   file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
705 
706   /* Specify data destination for compression */
707 #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
708   if (memdst)
709     jpeg_mem_dest(&cinfo, &outbuffer, &outsize);
710   else
711 #endif
712     jpeg_stdio_dest(&cinfo, output_file);
713 
714 #ifdef CJPEG_FUZZER
715   if (setjmp(myerr.setjmp_buffer))
716     HANDLE_ERROR()
717 #endif
718 
719   /* Start compressor */
720   jpeg_start_compress(&cinfo, TRUE);
721 
722   if (icc_profile != NULL)
723     jpeg_write_icc_profile(&cinfo, icc_profile, (unsigned int)icc_len);
724 
725   /* Process data */
726   while (cinfo.next_scanline < cinfo.image_height) {
727     num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
728     (void)jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
729   }
730 
731   /* Finish compression and release memory */
732   (*src_mgr->finish_input) (&cinfo, src_mgr);
733   jpeg_finish_compress(&cinfo);
734   jpeg_destroy_compress(&cinfo);
735 
736   /* Close files, if we opened them */
737   if (input_file != stdin)
738     fclose(input_file);
739   if (output_file != stdout && output_file != NULL)
740     fclose(output_file);
741 
742   if (report)
743     end_progress_monitor((j_common_ptr)&cinfo);
744 
745   if (memdst) {
746 #ifndef CJPEG_FUZZER
747     fprintf(stderr, "Compressed size:  %lu bytes\n", outsize);
748 #endif
749     free(outbuffer);
750   }
751 
752   free(icc_profile);
753 
754   /* All done. */
755   return (jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
756 }
757