• 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-2010, Thomas G. Lane, Guido Vollbeding.
6  * libjpeg-turbo Modifications:
7  * Copyright (C) 2010, 2014, 2017, 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 char *outfilename;       /* for -outfile switch */
45 static JCOPY_OPTION copyoption; /* -copy switch */
46 static jpeg_transform_info transformoption; /* image transformation options */
47 
48 
49 LOCAL(void)
usage(void)50 usage(void)
51 /* complain about bad command line */
52 {
53   fprintf(stderr, "usage: %s [switches] ", progname);
54 #ifdef TWO_FILE_COMMANDLINE
55   fprintf(stderr, "inputfile outputfile\n");
56 #else
57   fprintf(stderr, "[inputfile]\n");
58 #endif
59 
60   fprintf(stderr, "Switches (names may be abbreviated):\n");
61   fprintf(stderr, "  -copy none     Copy no extra markers from source file\n");
62   fprintf(stderr, "  -copy comments Copy only comment markers (default)\n");
63   fprintf(stderr, "  -copy all      Copy all extra markers\n");
64 #ifdef ENTROPY_OPT_SUPPORTED
65   fprintf(stderr, "  -optimize      Optimize Huffman table (smaller file, but slow compression)\n");
66 #endif
67 #ifdef C_PROGRESSIVE_SUPPORTED
68   fprintf(stderr, "  -progressive   Create progressive JPEG file\n");
69 #endif
70   fprintf(stderr, "Switches for modifying the image:\n");
71 #if TRANSFORMS_SUPPORTED
72   fprintf(stderr, "  -crop WxH+X+Y  Crop to a rectangular subarea\n");
73   fprintf(stderr, "  -grayscale     Reduce to grayscale (omit color data)\n");
74   fprintf(stderr, "  -flip [horizontal|vertical]  Mirror image (left-right or top-bottom)\n");
75   fprintf(stderr, "  -perfect       Fail if there is non-transformable edge blocks\n");
76   fprintf(stderr, "  -rotate [90|180|270]         Rotate image (degrees clockwise)\n");
77 #endif
78 #if TRANSFORMS_SUPPORTED
79   fprintf(stderr, "  -transpose     Transpose image\n");
80   fprintf(stderr, "  -transverse    Transverse transpose image\n");
81   fprintf(stderr, "  -trim          Drop non-transformable edge blocks\n");
82 #endif
83   fprintf(stderr, "Switches for advanced users:\n");
84 #ifdef C_ARITH_CODING_SUPPORTED
85   fprintf(stderr, "  -arithmetic    Use arithmetic coding\n");
86 #endif
87   fprintf(stderr, "  -icc FILE      Embed ICC profile contained in FILE\n");
88   fprintf(stderr, "  -restart N     Set restart interval in rows, or in blocks with B\n");
89   fprintf(stderr, "  -maxmemory N   Maximum memory to use (in kbytes)\n");
90   fprintf(stderr, "  -outfile name  Specify name for output file\n");
91   fprintf(stderr, "  -verbose  or  -debug   Emit debug output\n");
92   fprintf(stderr, "  -version       Print version information and exit\n");
93   fprintf(stderr, "Switches for wizards:\n");
94 #ifdef C_MULTISCAN_FILES_SUPPORTED
95   fprintf(stderr, "  -scans FILE    Create multi-scan JPEG per script FILE\n");
96 #endif
97   exit(EXIT_FAILURE);
98 }
99 
100 
101 LOCAL(void)
select_transform(JXFORM_CODE transform)102 select_transform(JXFORM_CODE transform)
103 /* Silly little routine to detect multiple transform options,
104  * which we can't handle.
105  */
106 {
107 #if TRANSFORMS_SUPPORTED
108   if (transformoption.transform == JXFORM_NONE ||
109       transformoption.transform == transform) {
110     transformoption.transform = transform;
111   } else {
112     fprintf(stderr, "%s: can only do one image transformation at a time\n",
113             progname);
114     usage();
115   }
116 #else
117   fprintf(stderr, "%s: sorry, image transformation was not compiled\n",
118           progname);
119   exit(EXIT_FAILURE);
120 #endif
121 }
122 
123 
124 LOCAL(int)
parse_switches(j_compress_ptr cinfo,int argc,char ** argv,int last_file_arg_seen,boolean for_real)125 parse_switches(j_compress_ptr cinfo, int argc, char **argv,
126                int last_file_arg_seen, boolean for_real)
127 /* Parse optional switches.
128  * Returns argv[] index of first file-name argument (== argc if none).
129  * Any file names with indexes <= last_file_arg_seen are ignored;
130  * they have presumably been processed in a previous iteration.
131  * (Pass 0 for last_file_arg_seen on the first or only iteration.)
132  * for_real is FALSE on the first (dummy) pass; we may skip any expensive
133  * processing.
134  */
135 {
136   int argn;
137   char *arg;
138   boolean simple_progressive;
139   char *scansarg = NULL;        /* saves -scans parm if any */
140 
141   /* Set up default JPEG parameters. */
142   simple_progressive = FALSE;
143   icc_filename = NULL;
144   outfilename = NULL;
145   copyoption = JCOPYOPT_DEFAULT;
146   transformoption.transform = JXFORM_NONE;
147   transformoption.perfect = FALSE;
148   transformoption.trim = FALSE;
149   transformoption.force_grayscale = FALSE;
150   transformoption.crop = FALSE;
151   transformoption.slow_hflip = FALSE;
152   cinfo->err->trace_level = 0;
153 
154   /* Scan command line options, adjust parameters */
155 
156   for (argn = 1; argn < argc; argn++) {
157     arg = argv[argn];
158     if (*arg != '-') {
159       /* Not a switch, must be a file name argument */
160       if (argn <= last_file_arg_seen) {
161         outfilename = NULL;     /* -outfile applies to just one input file */
162         continue;               /* ignore this name if previously processed */
163       }
164       break;                    /* else done parsing switches */
165     }
166     arg++;                      /* advance past switch marker character */
167 
168     if (keymatch(arg, "arithmetic", 1)) {
169       /* Use arithmetic coding. */
170 #ifdef C_ARITH_CODING_SUPPORTED
171       cinfo->arith_code = TRUE;
172 #else
173       fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
174               progname);
175       exit(EXIT_FAILURE);
176 #endif
177 
178     } else if (keymatch(arg, "copy", 2)) {
179       /* Select which extra markers to copy. */
180       if (++argn >= argc)       /* advance to next argument */
181         usage();
182       if (keymatch(argv[argn], "none", 1)) {
183         copyoption = JCOPYOPT_NONE;
184       } else if (keymatch(argv[argn], "comments", 1)) {
185         copyoption = JCOPYOPT_COMMENTS;
186       } else if (keymatch(argv[argn], "all", 1)) {
187         copyoption = JCOPYOPT_ALL;
188       } else
189         usage();
190 
191     } else if (keymatch(arg, "crop", 2)) {
192       /* Perform lossless cropping. */
193 #if TRANSFORMS_SUPPORTED
194       if (++argn >= argc)       /* advance to next argument */
195         usage();
196       if (!jtransform_parse_crop_spec(&transformoption, argv[argn])) {
197         fprintf(stderr, "%s: bogus -crop argument '%s'\n",
198                 progname, argv[argn]);
199         exit(EXIT_FAILURE);
200       }
201 #else
202       select_transform(JXFORM_NONE);    /* force an error */
203 #endif
204 
205     } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
206       /* Enable debug printouts. */
207       /* On first -d, print version identification */
208       static boolean printed_version = FALSE;
209 
210       if (!printed_version) {
211         fprintf(stderr, "%s version %s (build %s)\n",
212                 PACKAGE_NAME, VERSION, BUILD);
213         fprintf(stderr, "%s\n\n", JCOPYRIGHT);
214         fprintf(stderr, "Emulating The Independent JPEG Group's software, version %s\n\n",
215                 JVERSION);
216         printed_version = TRUE;
217       }
218       cinfo->err->trace_level++;
219 
220     } else if (keymatch(arg, "version", 4)) {
221       fprintf(stderr, "%s version %s (build %s)\n",
222               PACKAGE_NAME, VERSION, BUILD);
223       exit(EXIT_SUCCESS);
224 
225     } else if (keymatch(arg, "flip", 1)) {
226       /* Mirror left-right or top-bottom. */
227       if (++argn >= argc)       /* advance to next argument */
228         usage();
229       if (keymatch(argv[argn], "horizontal", 1))
230         select_transform(JXFORM_FLIP_H);
231       else if (keymatch(argv[argn], "vertical", 1))
232         select_transform(JXFORM_FLIP_V);
233       else
234         usage();
235 
236     } else if (keymatch(arg, "grayscale", 1) ||
237                keymatch(arg, "greyscale", 1)) {
238       /* Force to grayscale. */
239 #if TRANSFORMS_SUPPORTED
240       transformoption.force_grayscale = TRUE;
241 #else
242       select_transform(JXFORM_NONE);    /* force an error */
243 #endif
244 
245     } else if (keymatch(arg, "icc", 1)) {
246       /* Set ICC filename. */
247       if (++argn >= argc)       /* advance to next argument */
248         usage();
249       icc_filename = argv[argn];
250 
251     } else if (keymatch(arg, "maxmemory", 3)) {
252       /* Maximum memory in Kb (or Mb with 'm'). */
253       long lval;
254       char ch = 'x';
255 
256       if (++argn >= argc)       /* advance to next argument */
257         usage();
258       if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
259         usage();
260       if (ch == 'm' || ch == 'M')
261         lval *= 1000L;
262       cinfo->mem->max_memory_to_use = lval * 1000L;
263 
264     } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
265       /* Enable entropy parm optimization. */
266 #ifdef ENTROPY_OPT_SUPPORTED
267       cinfo->optimize_coding = TRUE;
268 #else
269       fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
270               progname);
271       exit(EXIT_FAILURE);
272 #endif
273 
274     } else if (keymatch(arg, "outfile", 4)) {
275       /* Set output file name. */
276       if (++argn >= argc)       /* advance to next argument */
277         usage();
278       outfilename = argv[argn]; /* save it away for later use */
279 
280     } else if (keymatch(arg, "perfect", 2)) {
281       /* Fail if there is any partial edge MCUs that the transform can't
282        * handle. */
283       transformoption.perfect = TRUE;
284 
285     } else if (keymatch(arg, "progressive", 2)) {
286       /* Select simple progressive mode. */
287 #ifdef C_PROGRESSIVE_SUPPORTED
288       simple_progressive = TRUE;
289       /* We must postpone execution until num_components is known. */
290 #else
291       fprintf(stderr, "%s: sorry, progressive output was not compiled\n",
292               progname);
293       exit(EXIT_FAILURE);
294 #endif
295 
296     } else if (keymatch(arg, "restart", 1)) {
297       /* Restart interval in MCU rows (or in MCUs with 'b'). */
298       long lval;
299       char ch = 'x';
300 
301       if (++argn >= argc)       /* advance to next argument */
302         usage();
303       if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
304         usage();
305       if (lval < 0 || lval > 65535L)
306         usage();
307       if (ch == 'b' || ch == 'B') {
308         cinfo->restart_interval = (unsigned int)lval;
309         cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
310       } else {
311         cinfo->restart_in_rows = (int)lval;
312         /* restart_interval will be computed during startup */
313       }
314 
315     } else if (keymatch(arg, "rotate", 2)) {
316       /* Rotate 90, 180, or 270 degrees (measured clockwise). */
317       if (++argn >= argc)       /* advance to next argument */
318         usage();
319       if (keymatch(argv[argn], "90", 2))
320         select_transform(JXFORM_ROT_90);
321       else if (keymatch(argv[argn], "180", 3))
322         select_transform(JXFORM_ROT_180);
323       else if (keymatch(argv[argn], "270", 3))
324         select_transform(JXFORM_ROT_270);
325       else
326         usage();
327 
328     } else if (keymatch(arg, "scans", 1)) {
329       /* Set scan script. */
330 #ifdef C_MULTISCAN_FILES_SUPPORTED
331       if (++argn >= argc)       /* advance to next argument */
332         usage();
333       scansarg = argv[argn];
334       /* We must postpone reading the file in case -progressive appears. */
335 #else
336       fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",
337               progname);
338       exit(EXIT_FAILURE);
339 #endif
340 
341     } else if (keymatch(arg, "transpose", 1)) {
342       /* Transpose (across UL-to-LR axis). */
343       select_transform(JXFORM_TRANSPOSE);
344 
345     } else if (keymatch(arg, "transverse", 6)) {
346       /* Transverse transpose (across UR-to-LL axis). */
347       select_transform(JXFORM_TRANSVERSE);
348 
349     } else if (keymatch(arg, "trim", 3)) {
350       /* Trim off any partial edge MCUs that the transform can't handle. */
351       transformoption.trim = TRUE;
352 
353     } else {
354       usage();                  /* bogus switch */
355     }
356   }
357 
358   /* Post-switch-scanning cleanup */
359 
360   if (for_real) {
361 
362 #ifdef C_PROGRESSIVE_SUPPORTED
363     if (simple_progressive)     /* process -progressive; -scans can override */
364       jpeg_simple_progression(cinfo);
365 #endif
366 
367 #ifdef C_MULTISCAN_FILES_SUPPORTED
368     if (scansarg != NULL)       /* process -scans if it was present */
369       if (!read_scan_script(cinfo, scansarg))
370         usage();
371 #endif
372   }
373 
374   return argn;                  /* return index of next arg (file name) */
375 }
376 
377 
378 /*
379  * The main program.
380  */
381 
382 int
main(int argc,char ** argv)383 main(int argc, char **argv)
384 {
385   struct jpeg_decompress_struct srcinfo;
386   struct jpeg_compress_struct dstinfo;
387   struct jpeg_error_mgr jsrcerr, jdsterr;
388 #ifdef PROGRESS_REPORT
389   struct cdjpeg_progress_mgr progress;
390 #endif
391   jvirt_barray_ptr *src_coef_arrays;
392   jvirt_barray_ptr *dst_coef_arrays;
393   int file_index;
394   /* We assume all-in-memory processing and can therefore use only a
395    * single file pointer for sequential input and output operation.
396    */
397   FILE *fp;
398   FILE *icc_file;
399   JOCTET *icc_profile = NULL;
400   long icc_len = 0;
401 
402   /* On Mac, fetch a command line. */
403 #ifdef USE_CCOMMAND
404   argc = ccommand(&argv);
405 #endif
406 
407   progname = argv[0];
408   if (progname == NULL || progname[0] == 0)
409     progname = "jpegtran";      /* in case C library doesn't provide it */
410 
411   /* Initialize the JPEG decompression object with default error handling. */
412   srcinfo.err = jpeg_std_error(&jsrcerr);
413   jpeg_create_decompress(&srcinfo);
414   /* Initialize the JPEG compression object with default error handling. */
415   dstinfo.err = jpeg_std_error(&jdsterr);
416   jpeg_create_compress(&dstinfo);
417 
418   /* Scan command line to find file names.
419    * It is convenient to use just one switch-parsing routine, but the switch
420    * values read here are mostly ignored; we will rescan the switches after
421    * opening the input file.  Also note that most of the switches affect the
422    * destination JPEG object, so we parse into that and then copy over what
423    * needs to affects the source too.
424    */
425 
426   file_index = parse_switches(&dstinfo, argc, argv, 0, FALSE);
427   jsrcerr.trace_level = jdsterr.trace_level;
428   srcinfo.mem->max_memory_to_use = dstinfo.mem->max_memory_to_use;
429 
430 #ifdef TWO_FILE_COMMANDLINE
431   /* Must have either -outfile switch or explicit output file name */
432   if (outfilename == NULL) {
433     if (file_index != argc - 2) {
434       fprintf(stderr, "%s: must name one input and one output file\n",
435               progname);
436       usage();
437     }
438     outfilename = argv[file_index + 1];
439   } else {
440     if (file_index != argc - 1) {
441       fprintf(stderr, "%s: must name one input and one output file\n",
442               progname);
443       usage();
444     }
445   }
446 #else
447   /* Unix style: expect zero or one file name */
448   if (file_index < argc - 1) {
449     fprintf(stderr, "%s: only one input file\n", progname);
450     usage();
451   }
452 #endif /* TWO_FILE_COMMANDLINE */
453 
454   /* Open the input file. */
455   if (file_index < argc) {
456     if ((fp = fopen(argv[file_index], READ_BINARY)) == NULL) {
457       fprintf(stderr, "%s: can't open %s for reading\n", progname,
458               argv[file_index]);
459       exit(EXIT_FAILURE);
460     }
461   } else {
462     /* default input file is stdin */
463     fp = read_stdin();
464   }
465 
466   if (icc_filename != NULL) {
467     if ((icc_file = fopen(icc_filename, READ_BINARY)) == NULL) {
468       fprintf(stderr, "%s: can't open %s\n", progname, icc_filename);
469       exit(EXIT_FAILURE);
470     }
471     if (fseek(icc_file, 0, SEEK_END) < 0 ||
472         (icc_len = ftell(icc_file)) < 1 ||
473         fseek(icc_file, 0, SEEK_SET) < 0) {
474       fprintf(stderr, "%s: can't determine size of %s\n", progname,
475               icc_filename);
476       exit(EXIT_FAILURE);
477     }
478     if ((icc_profile = (JOCTET *)malloc(icc_len)) == NULL) {
479       fprintf(stderr, "%s: can't allocate memory for ICC profile\n", progname);
480       fclose(icc_file);
481       exit(EXIT_FAILURE);
482     }
483     if (fread(icc_profile, icc_len, 1, icc_file) < 1) {
484       fprintf(stderr, "%s: can't read ICC profile from %s\n", progname,
485               icc_filename);
486       free(icc_profile);
487       fclose(icc_file);
488       exit(EXIT_FAILURE);
489     }
490     fclose(icc_file);
491     if (copyoption == JCOPYOPT_ALL)
492       copyoption = JCOPYOPT_ALL_EXCEPT_ICC;
493   }
494 
495 #ifdef PROGRESS_REPORT
496   start_progress_monitor((j_common_ptr)&dstinfo, &progress);
497 #endif
498 
499   /* Specify data source for decompression */
500   jpeg_stdio_src(&srcinfo, fp);
501 
502   /* Enable saving of extra markers that we want to copy */
503   jcopy_markers_setup(&srcinfo, copyoption);
504 
505   /* Read file header */
506   (void)jpeg_read_header(&srcinfo, TRUE);
507 
508   /* Any space needed by a transform option must be requested before
509    * jpeg_read_coefficients so that memory allocation will be done right.
510    */
511 #if TRANSFORMS_SUPPORTED
512   /* Fail right away if -perfect is given and transformation is not perfect.
513    */
514   if (!jtransform_request_workspace(&srcinfo, &transformoption)) {
515     fprintf(stderr, "%s: transformation is not perfect\n", progname);
516     exit(EXIT_FAILURE);
517   }
518 #endif
519 
520   /* Read source file as DCT coefficients */
521   src_coef_arrays = jpeg_read_coefficients(&srcinfo);
522 
523   /* Initialize destination compression parameters from source values */
524   jpeg_copy_critical_parameters(&srcinfo, &dstinfo);
525 
526   /* Adjust destination parameters if required by transform options;
527    * also find out which set of coefficient arrays will hold the output.
528    */
529 #if TRANSFORMS_SUPPORTED
530   dst_coef_arrays = jtransform_adjust_parameters(&srcinfo, &dstinfo,
531                                                  src_coef_arrays,
532                                                  &transformoption);
533 #else
534   dst_coef_arrays = src_coef_arrays;
535 #endif
536 
537   /* Close input file, if we opened it.
538    * Note: we assume that jpeg_read_coefficients consumed all input
539    * until JPEG_REACHED_EOI, and that jpeg_finish_decompress will
540    * only consume more while (!cinfo->inputctl->eoi_reached).
541    * We cannot call jpeg_finish_decompress here since we still need the
542    * virtual arrays allocated from the source object for processing.
543    */
544   if (fp != stdin)
545     fclose(fp);
546 
547   /* Open the output file. */
548   if (outfilename != NULL) {
549     if ((fp = fopen(outfilename, WRITE_BINARY)) == NULL) {
550       fprintf(stderr, "%s: can't open %s for writing\n", progname,
551               outfilename);
552       exit(EXIT_FAILURE);
553     }
554   } else {
555     /* default output file is stdout */
556     fp = write_stdout();
557   }
558 
559   /* Adjust default compression parameters by re-parsing the options */
560   file_index = parse_switches(&dstinfo, argc, argv, 0, TRUE);
561 
562   /* Specify data destination for compression */
563   jpeg_stdio_dest(&dstinfo, fp);
564 
565   /* Start compressor (note no image data is actually written here) */
566   jpeg_write_coefficients(&dstinfo, dst_coef_arrays);
567 
568   /* Copy to the output file any extra markers that we want to preserve */
569   jcopy_markers_execute(&srcinfo, &dstinfo, copyoption);
570 
571   if (icc_profile != NULL)
572     jpeg_write_icc_profile(&dstinfo, icc_profile, (unsigned int)icc_len);
573 
574   /* Execute image transformation, if any */
575 #if TRANSFORMS_SUPPORTED
576   jtransform_execute_transformation(&srcinfo, &dstinfo, src_coef_arrays,
577                                     &transformoption);
578 #endif
579 
580   /* Finish compression and release memory */
581   jpeg_finish_compress(&dstinfo);
582   jpeg_destroy_compress(&dstinfo);
583   (void)jpeg_finish_decompress(&srcinfo);
584   jpeg_destroy_decompress(&srcinfo);
585 
586   /* Close output file, if we opened it */
587   if (fp != stdout)
588     fclose(fp);
589 
590 #ifdef PROGRESS_REPORT
591   end_progress_monitor((j_common_ptr)&dstinfo);
592 #endif
593 
594   if (icc_profile != NULL)
595     free(icc_profile);
596 
597   /* All done. */
598   exit(jsrcerr.num_warnings + jdsterr.num_warnings ?
599        EXIT_WARNING : EXIT_SUCCESS);
600   return 0;                     /* suppress no-return-value warnings */
601 }
602