• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * jpegtran.c
3  *
4  * This file was part of the Independent JPEG Group's software:
5  * Copyright (C) 1995-2019, Thomas G. Lane, Guido Vollbeding.
6  * libjpeg-turbo Modifications:
7  * Copyright (C) 2010, 2014, 2017, 2019-2021, D. R. Commander.
8  * For conditions of distribution and use, see the accompanying README.ijg
9  * file.
10  *
11  * This file contains a command-line user interface for JPEG transcoding.
12  * It is very similar to cjpeg.c, and partly to djpeg.c, but provides
13  * lossless transcoding between different JPEG file formats.  It also
14  * provides some lossless and sort-of-lossless transformations of JPEG data.
15  */
16 
17 #include "cdjpeg.h"             /* Common decls for cjpeg/djpeg applications */
18 #include "transupp.h"           /* Support routines for jpegtran */
19 #include "jversion.h"           /* for version message */
20 #include "jconfigint.h"
21 
22 #ifdef USE_CCOMMAND             /* command-line reader for Macintosh */
23 #ifdef __MWERKS__
24 #include <SIOUX.h>              /* Metrowerks needs this */
25 #include <console.h>            /* ... and this */
26 #endif
27 #ifdef THINK_C
28 #include <console.h>            /* Think declares it here */
29 #endif
30 #endif
31 
32 
33 /*
34  * Argument-parsing code.
35  * The switch parser is designed to be useful with DOS-style command line
36  * syntax, ie, intermixed switches and file names, where only the switches
37  * to the left of a given file name affect processing of that file.
38  * The main program in this file doesn't actually use this capability...
39  */
40 
41 
42 static const char *progname;    /* program name for error messages */
43 static char *icc_filename;      /* for -icc switch */
44 static JDIMENSION max_scans;    /* for -maxscans switch */
45 static char *outfilename;       /* for -outfile switch */
46 static char *dropfilename;      /* for -drop switch */
47 static boolean report;          /* for -report switch */
48 static boolean strict;          /* for -strict switch */
49 static JCOPY_OPTION copyoption; /* -copy switch */
50 static jpeg_transform_info transformoption; /* image transformation options */
51 
52 
53 LOCAL(void)
usage(void)54 usage(void)
55 /* complain about bad command line */
56 {
57   fprintf(stderr, "usage: %s [switches] ", progname);
58 #ifdef TWO_FILE_COMMANDLINE
59   fprintf(stderr, "inputfile outputfile\n");
60 #else
61   fprintf(stderr, "[inputfile]\n");
62 #endif
63 
64   fprintf(stderr, "Switches (names may be abbreviated):\n");
65   fprintf(stderr, "  -copy none     Copy no extra markers from source file\n");
66   fprintf(stderr, "  -copy comments Copy only comment markers (default)\n");
67   fprintf(stderr, "  -copy icc      Copy only ICC profile markers\n");
68   fprintf(stderr, "  -copy all      Copy all extra markers\n");
69 #ifdef ENTROPY_OPT_SUPPORTED
70   fprintf(stderr, "  -optimize      Optimize Huffman table (smaller file, but slow compression)\n");
71 #endif
72 #ifdef C_PROGRESSIVE_SUPPORTED
73   fprintf(stderr, "  -progressive   Create progressive JPEG file\n");
74 #endif
75   fprintf(stderr, "Switches for modifying the image:\n");
76 #if TRANSFORMS_SUPPORTED
77   fprintf(stderr, "  -crop WxH+X+Y  Crop to a rectangular region\n");
78   fprintf(stderr, "  -drop +X+Y filename          Drop (insert) another image\n");
79   fprintf(stderr, "  -flip [horizontal|vertical]  Mirror image (left-right or top-bottom)\n");
80   fprintf(stderr, "  -grayscale     Reduce to grayscale (omit color data)\n");
81   fprintf(stderr, "  -perfect       Fail if there is non-transformable edge blocks\n");
82   fprintf(stderr, "  -rotate [90|180|270]         Rotate image (degrees clockwise)\n");
83 #endif
84 #if TRANSFORMS_SUPPORTED
85   fprintf(stderr, "  -transpose     Transpose image\n");
86   fprintf(stderr, "  -transverse    Transverse transpose image\n");
87   fprintf(stderr, "  -trim          Drop non-transformable edge blocks\n");
88   fprintf(stderr, "                 with -drop: Requantize drop file to match source file\n");
89   fprintf(stderr, "  -wipe WxH+X+Y  Wipe (gray out) a rectangular region\n");
90 #endif
91   fprintf(stderr, "Switches for advanced users:\n");
92 #ifdef C_ARITH_CODING_SUPPORTED
93   fprintf(stderr, "  -arithmetic    Use arithmetic coding\n");
94 #endif
95   fprintf(stderr, "  -icc FILE      Embed ICC profile contained in FILE\n");
96   fprintf(stderr, "  -restart N     Set restart interval in rows, or in blocks with B\n");
97   fprintf(stderr, "  -maxmemory N   Maximum memory to use (in kbytes)\n");
98   fprintf(stderr, "  -maxscans N    Maximum number of scans to allow in input file\n");
99   fprintf(stderr, "  -outfile name  Specify name for output file\n");
100   fprintf(stderr, "  -report        Report transformation progress\n");
101   fprintf(stderr, "  -strict        Treat all warnings as fatal\n");
102   fprintf(stderr, "  -verbose  or  -debug   Emit debug output\n");
103   fprintf(stderr, "  -version       Print version information and exit\n");
104   fprintf(stderr, "Switches for wizards:\n");
105 #ifdef C_MULTISCAN_FILES_SUPPORTED
106   fprintf(stderr, "  -scans FILE    Create multi-scan JPEG per script FILE\n");
107 #endif
108   exit(EXIT_FAILURE);
109 }
110 
111 
112 LOCAL(void)
select_transform(JXFORM_CODE transform)113 select_transform(JXFORM_CODE transform)
114 /* Silly little routine to detect multiple transform options,
115  * which we can't handle.
116  */
117 {
118 #if TRANSFORMS_SUPPORTED
119   if (transformoption.transform == JXFORM_NONE ||
120       transformoption.transform == transform) {
121     transformoption.transform = transform;
122   } else {
123     fprintf(stderr, "%s: can only do one image transformation at a time\n",
124             progname);
125     usage();
126   }
127 #else
128   fprintf(stderr, "%s: sorry, image transformation was not compiled\n",
129           progname);
130   exit(EXIT_FAILURE);
131 #endif
132 }
133 
134 
135 LOCAL(int)
parse_switches(j_compress_ptr cinfo,int argc,char ** argv,int last_file_arg_seen,boolean for_real)136 parse_switches(j_compress_ptr cinfo, int argc, char **argv,
137                int last_file_arg_seen, boolean for_real)
138 /* Parse optional switches.
139  * Returns argv[] index of first file-name argument (== argc if none).
140  * Any file names with indexes <= last_file_arg_seen are ignored;
141  * they have presumably been processed in a previous iteration.
142  * (Pass 0 for last_file_arg_seen on the first or only iteration.)
143  * for_real is FALSE on the first (dummy) pass; we may skip any expensive
144  * processing.
145  */
146 {
147   int argn;
148   char *arg;
149   boolean simple_progressive;
150   char *scansarg = NULL;        /* saves -scans parm if any */
151 
152   /* Set up default JPEG parameters. */
153   simple_progressive = FALSE;
154   icc_filename = NULL;
155   max_scans = 0;
156   outfilename = NULL;
157   report = FALSE;
158   strict = FALSE;
159   copyoption = JCOPYOPT_DEFAULT;
160   transformoption.transform = JXFORM_NONE;
161   transformoption.perfect = FALSE;
162   transformoption.trim = FALSE;
163   transformoption.force_grayscale = FALSE;
164   transformoption.crop = FALSE;
165   transformoption.slow_hflip = FALSE;
166   cinfo->err->trace_level = 0;
167 
168   /* Scan command line options, adjust parameters */
169 
170   for (argn = 1; argn < argc; argn++) {
171     arg = argv[argn];
172     if (*arg != '-') {
173       /* Not a switch, must be a file name argument */
174       if (argn <= last_file_arg_seen) {
175         outfilename = NULL;     /* -outfile applies to just one input file */
176         continue;               /* ignore this name if previously processed */
177       }
178       break;                    /* else done parsing switches */
179     }
180     arg++;                      /* advance past switch marker character */
181 
182     if (keymatch(arg, "arithmetic", 1)) {
183       /* Use arithmetic coding. */
184 #ifdef C_ARITH_CODING_SUPPORTED
185       cinfo->arith_code = TRUE;
186 #else
187       fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
188               progname);
189       exit(EXIT_FAILURE);
190 #endif
191 
192     } else if (keymatch(arg, "copy", 2)) {
193       /* Select which extra markers to copy. */
194       if (++argn >= argc)       /* advance to next argument */
195         usage();
196       if (keymatch(argv[argn], "none", 1)) {
197         copyoption = JCOPYOPT_NONE;
198       } else if (keymatch(argv[argn], "comments", 1)) {
199         copyoption = JCOPYOPT_COMMENTS;
200       } else if (keymatch(argv[argn], "icc", 1)) {
201         copyoption = JCOPYOPT_ICC;
202       } else if (keymatch(argv[argn], "all", 1)) {
203         copyoption = JCOPYOPT_ALL;
204       } else
205         usage();
206 
207     } else if (keymatch(arg, "crop", 2)) {
208       /* Perform lossless cropping. */
209 #if TRANSFORMS_SUPPORTED
210       if (++argn >= argc)       /* advance to next argument */
211         usage();
212       if (transformoption.crop /* reject multiple crop/drop/wipe requests */ ||
213           !jtransform_parse_crop_spec(&transformoption, argv[argn])) {
214         fprintf(stderr, "%s: bogus -crop argument '%s'\n",
215                 progname, argv[argn]);
216         exit(EXIT_FAILURE);
217       }
218 #else
219       select_transform(JXFORM_NONE);    /* force an error */
220 #endif
221 
222     } else if (keymatch(arg, "drop", 2)) {
223 #if TRANSFORMS_SUPPORTED
224       if (++argn >= argc)       /* advance to next argument */
225         usage();
226       if (transformoption.crop /* reject multiple crop/drop/wipe requests */ ||
227           !jtransform_parse_crop_spec(&transformoption, argv[argn]) ||
228           transformoption.crop_width_set != JCROP_UNSET ||
229           transformoption.crop_height_set != JCROP_UNSET) {
230         fprintf(stderr, "%s: bogus -drop argument '%s'\n",
231                 progname, argv[argn]);
232         exit(EXIT_FAILURE);
233       }
234       if (++argn >= argc)       /* advance to next argument */
235         usage();
236       dropfilename = argv[argn];
237       select_transform(JXFORM_DROP);
238 #else
239       select_transform(JXFORM_NONE);    /* force an error */
240 #endif
241 
242     } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
243       /* Enable debug printouts. */
244       /* On first -d, print version identification */
245       static boolean printed_version = FALSE;
246 
247       if (!printed_version) {
248         fprintf(stderr, "%s version %s (build %s)\n",
249                 PACKAGE_NAME, VERSION, BUILD);
250         fprintf(stderr, "%s\n\n", JCOPYRIGHT);
251         fprintf(stderr, "Emulating The Independent JPEG Group's software, version %s\n\n",
252                 JVERSION);
253         printed_version = TRUE;
254       }
255       cinfo->err->trace_level++;
256 
257     } else if (keymatch(arg, "version", 4)) {
258       fprintf(stderr, "%s version %s (build %s)\n",
259               PACKAGE_NAME, VERSION, BUILD);
260       exit(EXIT_SUCCESS);
261 
262     } else if (keymatch(arg, "flip", 1)) {
263       /* Mirror left-right or top-bottom. */
264       if (++argn >= argc)       /* advance to next argument */
265         usage();
266       if (keymatch(argv[argn], "horizontal", 1))
267         select_transform(JXFORM_FLIP_H);
268       else if (keymatch(argv[argn], "vertical", 1))
269         select_transform(JXFORM_FLIP_V);
270       else
271         usage();
272 
273     } else if (keymatch(arg, "grayscale", 1) ||
274                keymatch(arg, "greyscale", 1)) {
275       /* Force to grayscale. */
276 #if TRANSFORMS_SUPPORTED
277       transformoption.force_grayscale = TRUE;
278 #else
279       select_transform(JXFORM_NONE);    /* force an error */
280 #endif
281 
282     } else if (keymatch(arg, "icc", 1)) {
283       /* Set ICC filename. */
284       if (++argn >= argc)       /* advance to next argument */
285         usage();
286       icc_filename = argv[argn];
287 
288     } else if (keymatch(arg, "maxmemory", 3)) {
289       /* Maximum memory in Kb (or Mb with 'm'). */
290       long lval;
291       char ch = 'x';
292 
293       if (++argn >= argc)       /* advance to next argument */
294         usage();
295       if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
296         usage();
297       if (ch == 'm' || ch == 'M')
298         lval *= 1000L;
299       cinfo->mem->max_memory_to_use = lval * 1000L;
300 
301     } else if (keymatch(arg, "maxscans", 4)) {
302       if (++argn >= argc)       /* advance to next argument */
303         usage();
304       if (sscanf(argv[argn], "%u", &max_scans) != 1)
305         usage();
306 
307     } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
308       /* Enable entropy parm optimization. */
309 #ifdef ENTROPY_OPT_SUPPORTED
310       cinfo->optimize_coding = TRUE;
311 #else
312       fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
313               progname);
314       exit(EXIT_FAILURE);
315 #endif
316 
317     } else if (keymatch(arg, "outfile", 4)) {
318       /* Set output file name. */
319       if (++argn >= argc)       /* advance to next argument */
320         usage();
321       outfilename = argv[argn]; /* save it away for later use */
322 
323     } else if (keymatch(arg, "perfect", 2)) {
324       /* Fail if there is any partial edge MCUs that the transform can't
325        * handle. */
326       transformoption.perfect = TRUE;
327 
328     } else if (keymatch(arg, "progressive", 2)) {
329       /* Select simple progressive mode. */
330 #ifdef C_PROGRESSIVE_SUPPORTED
331       simple_progressive = TRUE;
332       /* We must postpone execution until num_components is known. */
333 #else
334       fprintf(stderr, "%s: sorry, progressive output was not compiled\n",
335               progname);
336       exit(EXIT_FAILURE);
337 #endif
338 
339     } else if (keymatch(arg, "report", 3)) {
340       report = TRUE;
341 
342     } else if (keymatch(arg, "restart", 1)) {
343       /* Restart interval in MCU rows (or in MCUs with 'b'). */
344       long lval;
345       char ch = 'x';
346 
347       if (++argn >= argc)       /* advance to next argument */
348         usage();
349       if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
350         usage();
351       if (lval < 0 || lval > 65535L)
352         usage();
353       if (ch == 'b' || ch == 'B') {
354         cinfo->restart_interval = (unsigned int)lval;
355         cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
356       } else {
357         cinfo->restart_in_rows = (int)lval;
358         /* restart_interval will be computed during startup */
359       }
360 
361     } else if (keymatch(arg, "rotate", 2)) {
362       /* Rotate 90, 180, or 270 degrees (measured clockwise). */
363       if (++argn >= argc)       /* advance to next argument */
364         usage();
365       if (keymatch(argv[argn], "90", 2))
366         select_transform(JXFORM_ROT_90);
367       else if (keymatch(argv[argn], "180", 3))
368         select_transform(JXFORM_ROT_180);
369       else if (keymatch(argv[argn], "270", 3))
370         select_transform(JXFORM_ROT_270);
371       else
372         usage();
373 
374     } else if (keymatch(arg, "scans", 1)) {
375       /* Set scan script. */
376 #ifdef C_MULTISCAN_FILES_SUPPORTED
377       if (++argn >= argc)       /* advance to next argument */
378         usage();
379       scansarg = argv[argn];
380       /* We must postpone reading the file in case -progressive appears. */
381 #else
382       fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",
383               progname);
384       exit(EXIT_FAILURE);
385 #endif
386 
387     } else if (keymatch(arg, "strict", 2)) {
388       strict = TRUE;
389 
390     } else if (keymatch(arg, "transpose", 1)) {
391       /* Transpose (across UL-to-LR axis). */
392       select_transform(JXFORM_TRANSPOSE);
393 
394     } else if (keymatch(arg, "transverse", 6)) {
395       /* Transverse transpose (across UR-to-LL axis). */
396       select_transform(JXFORM_TRANSVERSE);
397 
398     } else if (keymatch(arg, "trim", 3)) {
399       /* Trim off any partial edge MCUs that the transform can't handle. */
400       transformoption.trim = TRUE;
401 
402     } else if (keymatch(arg, "wipe", 1)) {
403 #if TRANSFORMS_SUPPORTED
404       if (++argn >= argc)       /* advance to next argument */
405         usage();
406       if (transformoption.crop /* reject multiple crop/drop/wipe requests */ ||
407           !jtransform_parse_crop_spec(&transformoption, argv[argn])) {
408         fprintf(stderr, "%s: bogus -wipe argument '%s'\n",
409                 progname, argv[argn]);
410         exit(EXIT_FAILURE);
411       }
412       select_transform(JXFORM_WIPE);
413 #else
414       select_transform(JXFORM_NONE);    /* force an error */
415 #endif
416 
417     } else {
418       usage();                  /* bogus switch */
419     }
420   }
421 
422   /* Post-switch-scanning cleanup */
423 
424   if (for_real) {
425 
426 #ifdef C_PROGRESSIVE_SUPPORTED
427     if (simple_progressive)     /* process -progressive; -scans can override */
428       jpeg_simple_progression(cinfo);
429 #endif
430 
431 #ifdef C_MULTISCAN_FILES_SUPPORTED
432     if (scansarg != NULL)       /* process -scans if it was present */
433       if (!read_scan_script(cinfo, scansarg))
434         usage();
435 #endif
436   }
437 
438   return argn;                  /* return index of next arg (file name) */
439 }
440 
441 
442 METHODDEF(void)
my_emit_message(j_common_ptr cinfo,int msg_level)443 my_emit_message(j_common_ptr cinfo, int msg_level)
444 {
445   if (msg_level < 0) {
446     /* Treat warning as fatal */
447     cinfo->err->error_exit(cinfo);
448   } else {
449     if (cinfo->err->trace_level >= msg_level)
450       cinfo->err->output_message(cinfo);
451   }
452 }
453 
454 
455 /*
456  * The main program.
457  */
458 
459 int
460 #ifdef GTEST
jpegtran(int argc,char ** argv)461 jpegtran(int argc, char **argv)
462 #else
463 main(int argc, char **argv)
464 #endif
465 {
466   struct jpeg_decompress_struct srcinfo;
467 #if TRANSFORMS_SUPPORTED
468   struct jpeg_decompress_struct dropinfo;
469   struct jpeg_error_mgr jdroperr;
470   FILE *drop_file;
471 #endif
472   struct jpeg_compress_struct dstinfo;
473   struct jpeg_error_mgr jsrcerr, jdsterr;
474   struct cdjpeg_progress_mgr src_progress, dst_progress;
475   jvirt_barray_ptr *src_coef_arrays;
476   jvirt_barray_ptr *dst_coef_arrays;
477   int file_index;
478   /* We assume all-in-memory processing and can therefore use only a
479    * single file pointer for sequential input and output operation.
480    */
481   FILE *fp;
482   FILE *icc_file;
483   JOCTET *icc_profile = NULL;
484   long icc_len = 0;
485 
486   /* On Mac, fetch a command line. */
487 #ifdef USE_CCOMMAND
488   argc = ccommand(&argv);
489 #endif
490 
491   progname = argv[0];
492   if (progname == NULL || progname[0] == 0)
493     progname = "jpegtran";      /* in case C library doesn't provide it */
494 
495   /* Initialize the JPEG decompression object with default error handling. */
496   srcinfo.err = jpeg_std_error(&jsrcerr);
497   jpeg_create_decompress(&srcinfo);
498   /* Initialize the JPEG compression object with default error handling. */
499   dstinfo.err = jpeg_std_error(&jdsterr);
500   jpeg_create_compress(&dstinfo);
501 
502   /* Scan command line to find file names.
503    * It is convenient to use just one switch-parsing routine, but the switch
504    * values read here are mostly ignored; we will rescan the switches after
505    * opening the input file.  Also note that most of the switches affect the
506    * destination JPEG object, so we parse into that and then copy over what
507    * needs to affect the source too.
508    */
509 
510   file_index = parse_switches(&dstinfo, argc, argv, 0, FALSE);
511   jsrcerr.trace_level = jdsterr.trace_level;
512   srcinfo.mem->max_memory_to_use = dstinfo.mem->max_memory_to_use;
513 
514   if (strict)
515     jsrcerr.emit_message = my_emit_message;
516 
517 #ifdef TWO_FILE_COMMANDLINE
518   /* Must have either -outfile switch or explicit output file name */
519   if (outfilename == NULL) {
520     if (file_index != argc - 2) {
521       fprintf(stderr, "%s: must name one input and one output file\n",
522               progname);
523       usage();
524     }
525     outfilename = argv[file_index + 1];
526   } else {
527     if (file_index != argc - 1) {
528       fprintf(stderr, "%s: must name one input and one output file\n",
529               progname);
530       usage();
531     }
532   }
533 #else
534   /* Unix style: expect zero or one file name */
535   if (file_index < argc - 1) {
536     fprintf(stderr, "%s: only one input file\n", progname);
537     usage();
538   }
539 #endif /* TWO_FILE_COMMANDLINE */
540 
541   /* Open the input file. */
542   if (file_index < argc) {
543     if ((fp = fopen(argv[file_index], READ_BINARY)) == NULL) {
544       fprintf(stderr, "%s: can't open %s for reading\n", progname,
545               argv[file_index]);
546       return EXIT_FAILURE;
547     }
548   } else {
549     /* default input file is stdin */
550     fp = read_stdin();
551   }
552 
553   if (icc_filename != NULL) {
554     if ((icc_file = fopen(icc_filename, READ_BINARY)) == NULL) {
555       fprintf(stderr, "%s: can't open %s\n", progname, icc_filename);
556       return EXIT_FAILURE;
557     }
558     if (fseek(icc_file, 0, SEEK_END) < 0 ||
559         (icc_len = ftell(icc_file)) < 1 ||
560         fseek(icc_file, 0, SEEK_SET) < 0) {
561       fprintf(stderr, "%s: can't determine size of %s\n", progname,
562               icc_filename);
563       return EXIT_FAILURE;
564     }
565     if ((icc_profile = (JOCTET *)malloc(icc_len)) == NULL) {
566       fprintf(stderr, "%s: can't allocate memory for ICC profile\n", progname);
567       fclose(icc_file);
568       return EXIT_FAILURE;
569     }
570     if (fread(icc_profile, icc_len, 1, icc_file) < 1) {
571       fprintf(stderr, "%s: can't read ICC profile from %s\n", progname,
572               icc_filename);
573       free(icc_profile);
574       fclose(icc_file);
575       return EXIT_FAILURE;
576     }
577     fclose(icc_file);
578     if (copyoption == JCOPYOPT_ALL)
579       copyoption = JCOPYOPT_ALL_EXCEPT_ICC;
580     if (copyoption == JCOPYOPT_ICC)
581       copyoption = JCOPYOPT_NONE;
582   }
583 
584   if (report) {
585     start_progress_monitor((j_common_ptr)&dstinfo, &dst_progress);
586     dst_progress.report = report;
587   }
588   if (report || max_scans != 0) {
589     start_progress_monitor((j_common_ptr)&srcinfo, &src_progress);
590     src_progress.report = report;
591     src_progress.max_scans = max_scans;
592   }
593 #if TRANSFORMS_SUPPORTED
594   /* Open the drop file. */
595   if (dropfilename != NULL) {
596     if ((drop_file = fopen(dropfilename, READ_BINARY)) == NULL) {
597       fprintf(stderr, "%s: can't open %s for reading\n", progname,
598               dropfilename);
599       return EXIT_FAILURE;
600     }
601     dropinfo.err = jpeg_std_error(&jdroperr);
602     jpeg_create_decompress(&dropinfo);
603     jpeg_stdio_src(&dropinfo, drop_file);
604   } else {
605     drop_file = NULL;
606   }
607 #endif
608 
609   /* Specify data source for decompression */
610   jpeg_stdio_src(&srcinfo, fp);
611 
612   /* Enable saving of extra markers that we want to copy */
613   jcopy_markers_setup(&srcinfo, copyoption);
614 
615   /* Read file header */
616   (void)jpeg_read_header(&srcinfo, TRUE);
617 
618 #if TRANSFORMS_SUPPORTED
619   if (dropfilename != NULL) {
620     (void)jpeg_read_header(&dropinfo, TRUE);
621     transformoption.crop_width = dropinfo.image_width;
622     transformoption.crop_width_set = JCROP_POS;
623     transformoption.crop_height = dropinfo.image_height;
624     transformoption.crop_height_set = JCROP_POS;
625     transformoption.drop_ptr = &dropinfo;
626   }
627 #endif
628 
629   /* Any space needed by a transform option must be requested before
630    * jpeg_read_coefficients so that memory allocation will be done right.
631    */
632 #if TRANSFORMS_SUPPORTED
633   /* Fail right away if -perfect is given and transformation is not perfect.
634    */
635   if (!jtransform_request_workspace(&srcinfo, &transformoption)) {
636     fprintf(stderr, "%s: transformation is not perfect\n", progname);
637     return EXIT_FAILURE;
638   }
639 #endif
640 
641   /* Read source file as DCT coefficients */
642   src_coef_arrays = jpeg_read_coefficients(&srcinfo);
643 
644 #if TRANSFORMS_SUPPORTED
645   if (dropfilename != NULL) {
646     transformoption.drop_coef_arrays = jpeg_read_coefficients(&dropinfo);
647   }
648 #endif
649 
650   /* Initialize destination compression parameters from source values */
651   jpeg_copy_critical_parameters(&srcinfo, &dstinfo);
652 
653   /* Adjust destination parameters if required by transform options;
654    * also find out which set of coefficient arrays will hold the output.
655    */
656 #if TRANSFORMS_SUPPORTED
657   dst_coef_arrays = jtransform_adjust_parameters(&srcinfo, &dstinfo,
658                                                  src_coef_arrays,
659                                                  &transformoption);
660 #else
661   dst_coef_arrays = src_coef_arrays;
662 #endif
663 
664   /* Close input file, if we opened it.
665    * Note: we assume that jpeg_read_coefficients consumed all input
666    * until JPEG_REACHED_EOI, and that jpeg_finish_decompress will
667    * only consume more while (!cinfo->inputctl->eoi_reached).
668    * We cannot call jpeg_finish_decompress here since we still need the
669    * virtual arrays allocated from the source object for processing.
670    */
671   if (fp != stdin)
672     fclose(fp);
673 
674   /* Open the output file. */
675   if (outfilename != NULL) {
676     if ((fp = fopen(outfilename, WRITE_BINARY)) == NULL) {
677       fprintf(stderr, "%s: can't open %s for writing\n", progname,
678               outfilename);
679       return EXIT_FAILURE;
680     }
681   } else {
682     /* default output file is stdout */
683     fp = write_stdout();
684   }
685 
686   /* Adjust default compression parameters by re-parsing the options */
687   file_index = parse_switches(&dstinfo, argc, argv, 0, TRUE);
688 
689   /* Specify data destination for compression */
690   jpeg_stdio_dest(&dstinfo, fp);
691 
692   /* Start compressor (note no image data is actually written here) */
693   jpeg_write_coefficients(&dstinfo, dst_coef_arrays);
694 
695   /* Copy to the output file any extra markers that we want to preserve */
696   jcopy_markers_execute(&srcinfo, &dstinfo, copyoption);
697 
698   if (icc_profile != NULL)
699     jpeg_write_icc_profile(&dstinfo, icc_profile, (unsigned int)icc_len);
700 
701   /* Execute image transformation, if any */
702 #if TRANSFORMS_SUPPORTED
703   jtransform_execute_transformation(&srcinfo, &dstinfo, src_coef_arrays,
704                                     &transformoption);
705 #endif
706 
707   /* Finish compression and release memory */
708   jpeg_finish_compress(&dstinfo);
709   jpeg_destroy_compress(&dstinfo);
710 #if TRANSFORMS_SUPPORTED
711   if (dropfilename != NULL) {
712     (void)jpeg_finish_decompress(&dropinfo);
713     jpeg_destroy_decompress(&dropinfo);
714   }
715 #endif
716   (void)jpeg_finish_decompress(&srcinfo);
717   jpeg_destroy_decompress(&srcinfo);
718 
719   /* Close output file, if we opened it */
720   if (fp != stdout)
721     fclose(fp);
722 #if TRANSFORMS_SUPPORTED
723   if (drop_file != NULL)
724     fclose(drop_file);
725 #endif
726 
727   if (report)
728     end_progress_monitor((j_common_ptr)&dstinfo);
729   if (report || max_scans != 0)
730     end_progress_monitor((j_common_ptr)&srcinfo);
731 
732   free(icc_profile);
733 
734   /* All done. */
735 #if TRANSFORMS_SUPPORTED
736   if (dropfilename != NULL)
737     return (jsrcerr.num_warnings + jdroperr.num_warnings +
738             jdsterr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
739 #endif
740   return (jsrcerr.num_warnings + jdsterr.num_warnings ?
741           EXIT_WARNING : EXIT_SUCCESS);
742 }
743