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