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