jpegtran.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. * mozjpeg Modifications:
  9. * Copyright (C) 2014, Mozilla Corporation.
  10. * For conditions of distribution and use, see the accompanying README file.
  11. *
  12. * This file contains a command-line user interface for JPEG transcoding.
  13. * It is very similar to cjpeg.c, and partly to djpeg.c, but provides
  14. * lossless transcoding between different JPEG file formats. It also
  15. * provides some lossless and sort-of-lossless transformations of JPEG data.
  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. #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. * Argument-parsing code.
  32. * The switch parser is designed to be useful with DOS-style command line
  33. * syntax, ie, intermixed switches and file names, where only the switches
  34. * to the left of a given file name affect processing of that file.
  35. * The main program in this file doesn't actually use this capability...
  36. */
  37. static const char *progname; /* program name for error messages */
  38. static char *icc_filename; /* for -icc switch */
  39. static char *outfilename; /* for -outfile switch */
  40. static boolean prefer_smallest; /* use smallest of input or result file (if no image-changing options supplied) */
  41. static JCOPY_OPTION copyoption; /* -copy switch */
  42. static jpeg_transform_info transformoption; /* image transformation options */
  43. boolean memsrc = FALSE; /* for -memsrc switch */
  44. #define INPUT_BUF_SIZE 4096
  45. LOCAL(void)
  46. usage(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. fprintf(stderr, "Switches (names may be abbreviated):\n");
  56. fprintf(stderr, " -copy none Copy no extra markers from source file\n");
  57. fprintf(stderr, " -copy comments Copy only comment markers (default)\n");
  58. fprintf(stderr, " -copy all Copy all extra markers\n");
  59. #ifdef ENTROPY_OPT_SUPPORTED
  60. fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression, enabled by default)\n");
  61. #endif
  62. #ifdef C_PROGRESSIVE_SUPPORTED
  63. fprintf(stderr, " -progressive Create progressive JPEG file (enabled by default)\n");
  64. #endif
  65. fprintf(stderr, " -revert Revert to standard defaults (instead of mozjpeg defaults)\n");
  66. fprintf(stderr, " -fastcrush Disable progressive scan optimization\n");
  67. fprintf(stderr, "Switches for modifying the image:\n");
  68. #if TRANSFORMS_SUPPORTED
  69. fprintf(stderr, " -crop WxH+X+Y Crop to a rectangular subarea\n");
  70. fprintf(stderr, " -grayscale Reduce to grayscale (omit color data)\n");
  71. fprintf(stderr, " -flip [horizontal|vertical] Mirror image (left-right or top-bottom)\n");
  72. fprintf(stderr, " -perfect Fail if there is non-transformable edge blocks\n");
  73. fprintf(stderr, " -rotate [90|180|270] Rotate image (degrees clockwise)\n");
  74. #endif
  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. #ifdef C_ARITH_CODING_SUPPORTED
  82. fprintf(stderr, " -arithmetic Use arithmetic coding\n");
  83. #endif
  84. fprintf(stderr, " -icc FILE Embed ICC profile contained in FILE\n");
  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. LOCAL(void)
  97. select_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. LOCAL(int)
  118. parse_switches(j_compress_ptr cinfo, int argc, char **argv,
  119. int last_file_arg_seen, boolean for_real)
  120. /* Parse optional switches.
  121. * Returns argv[] index of first file-name argument (== argc if none).
  122. * Any file names with indexes <= last_file_arg_seen are ignored;
  123. * they have presumably been processed in a previous iteration.
  124. * (Pass 0 for last_file_arg_seen on the first or only iteration.)
  125. * for_real is FALSE on the first (dummy) pass; we may skip any expensive
  126. * processing.
  127. */
  128. {
  129. int argn;
  130. char *arg;
  131. boolean simple_progressive;
  132. char *scansarg = NULL; /* saves -scans parm if any */
  133. /* Set up default JPEG parameters. */
  134. #ifdef C_PROGRESSIVE_SUPPORTED
  135. simple_progressive = cinfo->num_scans == 0 ? FALSE : TRUE;
  136. #else
  137. simple_progressive = FALSE;
  138. #endif
  139. icc_filename = NULL;
  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. prefer_smallest = TRUE;
  150. /* Scan command line options, adjust parameters */
  151. for (argn = 1; argn < argc; argn++) {
  152. arg = argv[argn];
  153. if (*arg != '-') {
  154. /* Not a switch, must be a file name argument */
  155. if (argn <= last_file_arg_seen) {
  156. outfilename = NULL; /* -outfile applies to just one input file */
  157. continue; /* ignore this name if previously processed */
  158. }
  159. break; /* else done parsing switches */
  160. }
  161. arg++; /* advance past switch marker character */
  162. if (keymatch(arg, "arithmetic", 1)) {
  163. /* Use arithmetic coding. */
  164. #ifdef C_ARITH_CODING_SUPPORTED
  165. cinfo->arith_code = TRUE;
  166. /* No table optimization required for AC */
  167. cinfo->optimize_coding = FALSE;
  168. prefer_smallest = FALSE;
  169. #else
  170. fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
  171. progname);
  172. exit(EXIT_FAILURE);
  173. #endif
  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. } else if (keymatch(arg, "crop", 2)) {
  187. /* Perform lossless cropping. */
  188. #if TRANSFORMS_SUPPORTED
  189. if (++argn >= argc) /* advance to next argument */
  190. usage();
  191. if (!jtransform_parse_crop_spec(&transformoption, argv[argn])) {
  192. fprintf(stderr, "%s: bogus -crop argument '%s'\n",
  193. progname, argv[argn]);
  194. exit(EXIT_FAILURE);
  195. }
  196. prefer_smallest = FALSE;
  197. #else
  198. select_transform(JXFORM_NONE); /* force an error */
  199. #endif
  200. } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
  201. /* Enable debug printouts. */
  202. /* On first -d, print version identification */
  203. static boolean printed_version = FALSE;
  204. if (!printed_version) {
  205. fprintf(stderr, "%s version %s (build %s)\n",
  206. PACKAGE_NAME, VERSION, BUILD);
  207. fprintf(stderr, "%s\n\n", JCOPYRIGHT);
  208. fprintf(stderr, "Emulating The Independent JPEG Group's software, version %s\n\n",
  209. JVERSION);
  210. printed_version = TRUE;
  211. }
  212. cinfo->err->trace_level++;
  213. } else if (keymatch(arg, "version", 4)) {
  214. fprintf(stderr, "%s version %s (build %s)\n",
  215. PACKAGE_NAME, VERSION, BUILD);
  216. exit(EXIT_SUCCESS);
  217. } else if (keymatch(arg, "flip", 1)) {
  218. /* Mirror left-right or top-bottom. */
  219. if (++argn >= argc) /* advance to next argument */
  220. usage();
  221. if (keymatch(argv[argn], "horizontal", 1))
  222. select_transform(JXFORM_FLIP_H);
  223. else if (keymatch(argv[argn], "vertical", 1))
  224. select_transform(JXFORM_FLIP_V);
  225. else
  226. usage();
  227. prefer_smallest = FALSE;
  228. } else if (keymatch(arg, "fastcrush", 4)) {
  229. jpeg_c_set_bool_param(cinfo, JBOOLEAN_OPTIMIZE_SCANS, FALSE);
  230. } else if (keymatch(arg, "grayscale", 1) || keymatch(arg, "greyscale",1)) {
  231. /* Force to grayscale. */
  232. #if TRANSFORMS_SUPPORTED
  233. transformoption.force_grayscale = TRUE;
  234. prefer_smallest = FALSE;
  235. #else
  236. select_transform(JXFORM_NONE); /* force an error */
  237. #endif
  238. } else if (keymatch(arg, "icc", 1)) {
  239. /* Set ICC filename. */
  240. if (++argn >= argc) /* advance to next argument */
  241. usage();
  242. icc_filename = argv[argn];
  243. } else if (keymatch(arg, "maxmemory", 3)) {
  244. /* Maximum memory in Kb (or Mb with 'm'). */
  245. long lval;
  246. char ch = 'x';
  247. if (++argn >= argc) /* advance to next argument */
  248. usage();
  249. if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
  250. usage();
  251. if (ch == 'm' || ch == 'M')
  252. lval *= 1000L;
  253. cinfo->mem->max_memory_to_use = lval * 1000L;
  254. } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
  255. /* Enable entropy parm optimization. */
  256. #ifdef ENTROPY_OPT_SUPPORTED
  257. cinfo->optimize_coding = TRUE;
  258. #else
  259. fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
  260. progname);
  261. exit(EXIT_FAILURE);
  262. #endif
  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. } else if (keymatch(arg, "perfect", 2)) {
  269. /* Fail if there is any partial edge MCUs that the transform can't
  270. * handle. */
  271. transformoption.perfect = TRUE;
  272. } else if (keymatch(arg, "progressive", 2)) {
  273. /* Select simple progressive mode. */
  274. #ifdef C_PROGRESSIVE_SUPPORTED
  275. simple_progressive = TRUE;
  276. prefer_smallest = FALSE;
  277. /* We must postpone execution until num_components is known. */
  278. #else
  279. fprintf(stderr, "%s: sorry, progressive output was not compiled\n",
  280. progname);
  281. exit(EXIT_FAILURE);
  282. #endif
  283. } else if (keymatch(arg, "restart", 1)) {
  284. /* Restart interval in MCU rows (or in MCUs with 'b'). */
  285. long lval;
  286. char ch = 'x';
  287. if (++argn >= argc) /* advance to next argument */
  288. usage();
  289. if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
  290. usage();
  291. if (lval < 0 || lval > 65535L)
  292. usage();
  293. if (ch == 'b' || ch == 'B') {
  294. cinfo->restart_interval = (unsigned int)lval;
  295. cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
  296. } else {
  297. cinfo->restart_in_rows = (int)lval;
  298. /* restart_interval will be computed during startup */
  299. }
  300. } else if (keymatch(arg, "revert", 3)) {
  301. /* revert to old JPEG default */
  302. jpeg_c_set_int_param(cinfo, JINT_COMPRESS_PROFILE, JCP_FASTEST);
  303. prefer_smallest = FALSE;
  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. prefer_smallest = FALSE;
  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. prefer_smallest = FALSE;
  323. scansarg = argv[argn];
  324. /* We must postpone reading the file in case -progressive appears. */
  325. #else
  326. fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",
  327. progname);
  328. exit(EXIT_FAILURE);
  329. #endif
  330. } else if (keymatch(arg, "transpose", 1)) {
  331. /* Transpose (across UL-to-LR axis). */
  332. select_transform(JXFORM_TRANSPOSE);
  333. prefer_smallest = FALSE;
  334. } else if (keymatch(arg, "transverse", 6)) {
  335. /* Transverse transpose (across UR-to-LL axis). */
  336. select_transform(JXFORM_TRANSVERSE);
  337. prefer_smallest = FALSE;
  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. prefer_smallest = FALSE;
  342. } else {
  343. usage(); /* bogus switch */
  344. }
  345. }
  346. /* Post-switch-scanning cleanup */
  347. if (for_real) {
  348. #ifdef C_PROGRESSIVE_SUPPORTED
  349. if (simple_progressive) /* process -progressive; -scans can override */
  350. jpeg_simple_progression(cinfo);
  351. #endif
  352. #ifdef C_MULTISCAN_FILES_SUPPORTED
  353. if (scansarg != NULL) /* process -scans if it was present */
  354. if (!read_scan_script(cinfo, scansarg))
  355. usage();
  356. #endif
  357. }
  358. return argn; /* return index of next arg (file name) */
  359. }
  360. /*
  361. * The main program.
  362. */
  363. int
  364. main(int argc, char **argv)
  365. {
  366. struct jpeg_decompress_struct srcinfo;
  367. struct jpeg_compress_struct dstinfo;
  368. struct jpeg_error_mgr jsrcerr, jdsterr;
  369. #ifdef PROGRESS_REPORT
  370. struct cdjpeg_progress_mgr progress;
  371. #endif
  372. jvirt_barray_ptr *src_coef_arrays;
  373. jvirt_barray_ptr *dst_coef_arrays;
  374. int file_index;
  375. /* We assume all-in-memory processing and can therefore use only a
  376. * single file pointer for sequential input and output operation.
  377. */
  378. FILE *fp;
  379. unsigned char *inbuffer = NULL;
  380. unsigned long insize = 0;
  381. unsigned char *outbuffer = NULL;
  382. unsigned long outsize = 0;
  383. FILE *icc_file;
  384. JOCTET *icc_profile = NULL;
  385. long icc_len = 0;
  386. /* On Mac, fetch a command line. */
  387. #ifdef USE_CCOMMAND
  388. argc = ccommand(&argv);
  389. #endif
  390. progname = argv[0];
  391. if (progname == NULL || progname[0] == 0)
  392. progname = "jpegtran"; /* in case C library doesn't provide it */
  393. /* Initialize the JPEG decompression object with default error handling. */
  394. srcinfo.err = jpeg_std_error(&jsrcerr);
  395. jpeg_create_decompress(&srcinfo);
  396. /* Initialize the JPEG compression object with default error handling. */
  397. dstinfo.err = jpeg_std_error(&jdsterr);
  398. jpeg_create_compress(&dstinfo);
  399. /* Scan command line to find file names.
  400. * It is convenient to use just one switch-parsing routine, but the switch
  401. * values read here are mostly ignored; we will rescan the switches after
  402. * opening the input file. Also note that most of the switches affect the
  403. * destination JPEG object, so we parse into that and then copy over what
  404. * needs to affects the source too.
  405. */
  406. file_index = parse_switches(&dstinfo, argc, argv, 0, FALSE);
  407. jsrcerr.trace_level = jdsterr.trace_level;
  408. srcinfo.mem->max_memory_to_use = dstinfo.mem->max_memory_to_use;
  409. #ifdef TWO_FILE_COMMANDLINE
  410. /* Must have either -outfile switch or explicit output file name */
  411. if (outfilename == NULL) {
  412. if (file_index != argc - 2) {
  413. fprintf(stderr, "%s: must name one input and one output file\n",
  414. progname);
  415. usage();
  416. }
  417. outfilename = argv[file_index + 1];
  418. } else {
  419. if (file_index != argc - 1) {
  420. fprintf(stderr, "%s: must name one input and one output file\n",
  421. progname);
  422. usage();
  423. }
  424. }
  425. #else
  426. /* Unix style: expect zero or one file name */
  427. if (file_index < argc - 1) {
  428. fprintf(stderr, "%s: only one input file\n", progname);
  429. usage();
  430. }
  431. #endif /* TWO_FILE_COMMANDLINE */
  432. /* Open the input file. */
  433. if (file_index < argc) {
  434. if ((fp = fopen(argv[file_index], READ_BINARY)) == NULL) {
  435. fprintf(stderr, "%s: can't open %s for reading\n", progname,
  436. argv[file_index]);
  437. exit(EXIT_FAILURE);
  438. }
  439. } else {
  440. /* default input file is stdin */
  441. fp = read_stdin();
  442. }
  443. if (icc_filename != NULL) {
  444. if ((icc_file = fopen(icc_filename, READ_BINARY)) == NULL) {
  445. fprintf(stderr, "%s: can't open %s\n", progname, icc_filename);
  446. exit(EXIT_FAILURE);
  447. }
  448. if (fseek(icc_file, 0, SEEK_END) < 0 ||
  449. (icc_len = ftell(icc_file)) < 1 ||
  450. fseek(icc_file, 0, SEEK_SET) < 0) {
  451. fprintf(stderr, "%s: can't determine size of %s\n", progname,
  452. icc_filename);
  453. exit(EXIT_FAILURE);
  454. }
  455. if ((icc_profile = (JOCTET *)malloc(icc_len)) == NULL) {
  456. fprintf(stderr, "%s: can't allocate memory for ICC profile\n", progname);
  457. fclose(icc_file);
  458. exit(EXIT_FAILURE);
  459. }
  460. if (fread(icc_profile, icc_len, 1, icc_file) < 1) {
  461. fprintf(stderr, "%s: can't read ICC profile from %s\n", progname,
  462. icc_filename);
  463. free(icc_profile);
  464. fclose(icc_file);
  465. exit(EXIT_FAILURE);
  466. }
  467. fclose(icc_file);
  468. if (copyoption == JCOPYOPT_ALL)
  469. copyoption = JCOPYOPT_ALL_EXCEPT_ICC;
  470. }
  471. #ifdef PROGRESS_REPORT
  472. start_progress_monitor((j_common_ptr)&dstinfo, &progress);
  473. #endif
  474. /* Specify data source for decompression */
  475. if (jpeg_c_int_param_supported(&dstinfo, JINT_COMPRESS_PROFILE) &&
  476. jpeg_c_get_int_param(&dstinfo, JINT_COMPRESS_PROFILE)
  477. == JCP_MAX_COMPRESSION)
  478. memsrc = TRUE; /* needed to revert to original */
  479. #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
  480. if (memsrc) {
  481. size_t nbytes;
  482. do {
  483. inbuffer = (unsigned char *)realloc(inbuffer, insize + INPUT_BUF_SIZE);
  484. if (inbuffer == NULL) {
  485. fprintf(stderr, "%s: memory allocation failure\n", progname);
  486. exit(EXIT_FAILURE);
  487. }
  488. nbytes = JFREAD(fp, &inbuffer[insize], INPUT_BUF_SIZE);
  489. if (nbytes < INPUT_BUF_SIZE && ferror(fp)) {
  490. if (file_index < argc)
  491. fprintf(stderr, "%s: can't read from %s\n", progname,
  492. argv[file_index]);
  493. else
  494. fprintf(stderr, "%s: can't read from stdin\n", progname);
  495. }
  496. insize += (unsigned long)nbytes;
  497. } while (nbytes == INPUT_BUF_SIZE);
  498. jpeg_mem_src(&srcinfo, inbuffer, insize);
  499. } else
  500. #endif
  501. jpeg_stdio_src(&srcinfo, fp);
  502. /* Enable saving of extra markers that we want to copy */
  503. jcopy_markers_setup(&srcinfo, copyoption);
  504. /* Read file header */
  505. (void)jpeg_read_header(&srcinfo, TRUE);
  506. /* Any space needed by a transform option must be requested before
  507. * jpeg_read_coefficients so that memory allocation will be done right.
  508. */
  509. #if TRANSFORMS_SUPPORTED
  510. /* Fail right away if -perfect is given and transformation is not perfect.
  511. */
  512. if (!jtransform_request_workspace(&srcinfo, &transformoption)) {
  513. fprintf(stderr, "%s: transformation is not perfect\n", progname);
  514. exit(EXIT_FAILURE);
  515. }
  516. #endif
  517. /* Read source file as DCT coefficients */
  518. src_coef_arrays = jpeg_read_coefficients(&srcinfo);
  519. /* Initialize destination compression parameters from source values */
  520. jpeg_copy_critical_parameters(&srcinfo, &dstinfo);
  521. /* Adjust destination parameters if required by transform options;
  522. * also find out which set of coefficient arrays will hold the output.
  523. */
  524. #if TRANSFORMS_SUPPORTED
  525. dst_coef_arrays = jtransform_adjust_parameters(&srcinfo, &dstinfo,
  526. src_coef_arrays,
  527. &transformoption);
  528. #else
  529. dst_coef_arrays = src_coef_arrays;
  530. #endif
  531. /* Close input file, if we opened it.
  532. * Note: we assume that jpeg_read_coefficients consumed all input
  533. * until JPEG_REACHED_EOI, and that jpeg_finish_decompress will
  534. * only consume more while (!cinfo->inputctl->eoi_reached).
  535. * We cannot call jpeg_finish_decompress here since we still need the
  536. * virtual arrays allocated from the source object for processing.
  537. */
  538. if (fp != stdin)
  539. fclose(fp);
  540. /* Open the output file. */
  541. if (outfilename != NULL) {
  542. if ((fp = fopen(outfilename, WRITE_BINARY)) == NULL) {
  543. fprintf(stderr, "%s: can't open %s for writing\n", progname,
  544. outfilename);
  545. exit(EXIT_FAILURE);
  546. }
  547. } else {
  548. /* default output file is stdout */
  549. fp = write_stdout();
  550. }
  551. /* Adjust default compression parameters by re-parsing the options */
  552. file_index = parse_switches(&dstinfo, argc, argv, 0, TRUE);
  553. /* Specify data destination for compression */
  554. #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
  555. if (jpeg_c_int_param_supported(&dstinfo, JINT_COMPRESS_PROFILE) &&
  556. jpeg_c_get_int_param(&dstinfo, JINT_COMPRESS_PROFILE)
  557. == JCP_MAX_COMPRESSION)
  558. jpeg_mem_dest(&dstinfo, &outbuffer, &outsize);
  559. else
  560. #endif
  561. jpeg_stdio_dest(&dstinfo, fp);
  562. /* Start compressor (note no image data is actually written here) */
  563. jpeg_write_coefficients(&dstinfo, dst_coef_arrays);
  564. /* Copy to the output file any extra markers that we want to preserve */
  565. jcopy_markers_execute(&srcinfo, &dstinfo, copyoption);
  566. if (icc_profile != NULL)
  567. jpeg_write_icc_profile(&dstinfo, icc_profile, (unsigned int)icc_len);
  568. /* Execute image transformation, if any */
  569. #if TRANSFORMS_SUPPORTED
  570. jtransform_execute_transformation(&srcinfo, &dstinfo, src_coef_arrays,
  571. &transformoption);
  572. #endif
  573. /* Finish compression and release memory */
  574. jpeg_finish_compress(&dstinfo);
  575. #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
  576. if (jpeg_c_int_param_supported(&dstinfo, JINT_COMPRESS_PROFILE) &&
  577. jpeg_c_get_int_param(&dstinfo, JINT_COMPRESS_PROFILE)
  578. == JCP_MAX_COMPRESSION) {
  579. size_t nbytes;
  580. unsigned char *buffer = outbuffer;
  581. unsigned long size = outsize;
  582. if (prefer_smallest && insize < size) {
  583. size = insize;
  584. buffer = inbuffer;
  585. }
  586. nbytes = JFWRITE(fp, buffer, size);
  587. if (nbytes < size && ferror(fp)) {
  588. if (file_index < argc)
  589. fprintf(stderr, "%s: can't write to %s\n", progname,
  590. argv[file_index]);
  591. else
  592. fprintf(stderr, "%s: can't write to stdout\n", progname);
  593. }
  594. }
  595. #endif
  596. jpeg_destroy_compress(&dstinfo);
  597. (void)jpeg_finish_decompress(&srcinfo);
  598. jpeg_destroy_decompress(&srcinfo);
  599. /* Close output file, if we opened it */
  600. if (fp != stdout)
  601. fclose(fp);
  602. #ifdef PROGRESS_REPORT
  603. end_progress_monitor((j_common_ptr)&dstinfo);
  604. #endif
  605. free(inbuffer);
  606. free(outbuffer);
  607. free(icc_profile);
  608. /* All done. */
  609. exit(jsrcerr.num_warnings + jdsterr.num_warnings ?
  610. EXIT_WARNING : EXIT_SUCCESS);
  611. return 0; /* suppress no-return-value warnings */
  612. }