jpegtran.c 19 KB

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