cjpeg.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. /*
  2. * cjpeg.c
  3. *
  4. * This file was part of the Independent JPEG Group's software:
  5. * Copyright (C) 1991-1998, Thomas G. Lane.
  6. * Modified 2003-2011 by Guido Vollbeding.
  7. * libjpeg-turbo Modifications:
  8. * Copyright (C) 2010, 2013-2014, 2017, D. R. Commander.
  9. * mozjpeg Modifications:
  10. * Copyright (C) 2014, Mozilla Corporation.
  11. * For conditions of distribution and use, see the accompanying README file.
  12. *
  13. * This file contains a command-line user interface for the JPEG compressor.
  14. * It should work on any system with Unix- or MS-DOS-style command lines.
  15. *
  16. * Two different command line styles are permitted, depending on the
  17. * compile-time switch TWO_FILE_COMMANDLINE:
  18. * cjpeg [options] inputfile outputfile
  19. * cjpeg [options] [inputfile]
  20. * In the second style, output is always to standard output, which you'd
  21. * normally redirect to a file or pipe to some other program. Input is
  22. * either from a named file or from standard input (typically redirected).
  23. * The second style is convenient on Unix but is unhelpful on systems that
  24. * don't support pipes. Also, you MUST use the first style if your system
  25. * doesn't do binary I/O to stdin/stdout.
  26. * To simplify script writing, the "-outfile" switch is provided. The syntax
  27. * cjpeg [options] -outfile outputfile inputfile
  28. * works regardless of which command line style is used.
  29. */
  30. #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
  31. #include "jversion.h" /* for version message */
  32. #include "jconfigint.h"
  33. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  34. extern void *malloc(size_t size);
  35. extern void free(void *ptr);
  36. #endif
  37. #ifdef USE_CCOMMAND /* command-line reader for Macintosh */
  38. #ifdef __MWERKS__
  39. #include <SIOUX.h> /* Metrowerks needs this */
  40. #include <console.h> /* ... and this */
  41. #endif
  42. #ifdef THINK_C
  43. #include <console.h> /* Think declares it here */
  44. #endif
  45. #endif
  46. /* Create the add-on message string table. */
  47. #define JMESSAGE(code, string) string,
  48. static const char * const cdjpeg_message_table[] = {
  49. #include "cderror.h"
  50. NULL
  51. };
  52. /*
  53. * This routine determines what format the input file is,
  54. * and selects the appropriate input-reading module.
  55. *
  56. * To determine which family of input formats the file belongs to,
  57. * we may look only at the first byte of the file, since C does not
  58. * guarantee that more than one character can be pushed back with ungetc.
  59. * Looking at additional bytes would require one of these approaches:
  60. * 1) assume we can fseek() the input file (fails for piped input);
  61. * 2) assume we can push back more than one character (works in
  62. * some C implementations, but unportable);
  63. * 3) provide our own buffering (breaks input readers that want to use
  64. * stdio directly, such as the RLE library);
  65. * or 4) don't put back the data, and modify the input_init methods to assume
  66. * they start reading after the start of file (also breaks RLE library).
  67. * #1 is attractive for MS-DOS but is untenable on Unix.
  68. *
  69. * The most portable solution for file types that can't be identified by their
  70. * first byte is to make the user tell us what they are. This is also the
  71. * only approach for "raw" file types that contain only arbitrary values.
  72. * We presently apply this method for Targa files. Most of the time Targa
  73. * files start with 0x00, so we recognize that case. Potentially, however,
  74. * a Targa file could start with any byte value (byte 0 is the length of the
  75. * seldom-used ID field), so we provide a switch to force Targa input mode.
  76. */
  77. static boolean is_targa; /* records user -targa switch */
  78. static boolean is_jpeg;
  79. static boolean copy_markers;
  80. LOCAL(cjpeg_source_ptr)
  81. select_file_type(j_compress_ptr cinfo, FILE *infile)
  82. {
  83. int c;
  84. if (is_targa) {
  85. #ifdef TARGA_SUPPORTED
  86. return jinit_read_targa(cinfo);
  87. #else
  88. ERREXIT(cinfo, JERR_TGA_NOTCOMP);
  89. #endif
  90. }
  91. if ((c = getc(infile)) == EOF)
  92. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  93. if (ungetc(c, infile) == EOF)
  94. ERREXIT(cinfo, JERR_UNGETC_FAILED);
  95. switch (c) {
  96. #ifdef BMP_SUPPORTED
  97. case 'B':
  98. return jinit_read_bmp(cinfo, TRUE);
  99. #endif
  100. #ifdef GIF_SUPPORTED
  101. case 'G':
  102. return jinit_read_gif(cinfo);
  103. #endif
  104. #ifdef PPM_SUPPORTED
  105. case 'P':
  106. return jinit_read_ppm(cinfo);
  107. #endif
  108. #ifdef PNG_SUPPORTED
  109. case 0x89:
  110. copy_markers = TRUE;
  111. return jinit_read_png(cinfo);
  112. #endif
  113. #ifdef RLE_SUPPORTED
  114. case 'R':
  115. return jinit_read_rle(cinfo);
  116. #endif
  117. #ifdef TARGA_SUPPORTED
  118. case 0x00:
  119. return jinit_read_targa(cinfo);
  120. #endif
  121. case 0xff:
  122. is_jpeg = TRUE;
  123. copy_markers = TRUE;
  124. return jinit_read_jpeg(cinfo);
  125. default:
  126. ERREXIT(cinfo, JERR_UNKNOWN_FORMAT);
  127. break;
  128. }
  129. return NULL; /* suppress compiler warnings */
  130. }
  131. /*
  132. * Argument-parsing code.
  133. * The switch parser is designed to be useful with DOS-style command line
  134. * syntax, ie, intermixed switches and file names, where only the switches
  135. * to the left of a given file name affect processing of that file.
  136. * The main program in this file doesn't actually use this capability...
  137. */
  138. static const char *progname; /* program name for error messages */
  139. static char *icc_filename; /* for -icc switch */
  140. static char *outfilename; /* for -outfile switch */
  141. boolean memdst; /* for -memdst switch */
  142. LOCAL(void)
  143. usage(void)
  144. /* complain about bad command line */
  145. {
  146. fprintf(stderr, "usage: %s [switches] ", progname);
  147. #ifdef TWO_FILE_COMMANDLINE
  148. fprintf(stderr, "inputfile outputfile\n");
  149. #else
  150. fprintf(stderr, "[inputfile]\n");
  151. #endif
  152. fprintf(stderr, "Switches (names may be abbreviated):\n");
  153. fprintf(stderr, " -quality N[,...] Compression quality (0..100; 5-95 is most useful range,\n");
  154. fprintf(stderr, " default is 75)\n");
  155. fprintf(stderr, " -grayscale Create monochrome JPEG file\n");
  156. fprintf(stderr, " -rgb Create RGB JPEG file\n");
  157. #ifdef ENTROPY_OPT_SUPPORTED
  158. fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression, enabled by default)\n");
  159. #endif
  160. #ifdef C_PROGRESSIVE_SUPPORTED
  161. fprintf(stderr, " -progressive Create progressive JPEG file (enabled by default)\n");
  162. #endif
  163. fprintf(stderr, " -baseline Create baseline JPEG file (disable progressive coding)\n");
  164. #ifdef TARGA_SUPPORTED
  165. fprintf(stderr, " -targa Input file is Targa format (usually not needed)\n");
  166. #endif
  167. fprintf(stderr, " -revert Revert to standard defaults (instead of mozjpeg defaults)\n");
  168. fprintf(stderr, " -fastcrush Disable progressive scan optimization\n");
  169. fprintf(stderr, " -dc-scan-opt DC scan optimization mode\n");
  170. fprintf(stderr, " - 0 One scan for all components\n");
  171. fprintf(stderr, " - 1 One scan per component (default)\n");
  172. fprintf(stderr, " - 2 Optimize between one scan for all components and one scan for 1st component\n");
  173. fprintf(stderr, " plus one scan for remaining components\n");
  174. fprintf(stderr, " -notrellis Disable trellis optimization\n");
  175. fprintf(stderr, " -trellis-dc Enable trellis optimization of DC coefficients (default)\n");
  176. fprintf(stderr, " -notrellis-dc Disable trellis optimization of DC coefficients\n");
  177. fprintf(stderr, " -tune-psnr Tune trellis optimization for PSNR\n");
  178. fprintf(stderr, " -tune-hvs-psnr Tune trellis optimization for PSNR-HVS (default)\n");
  179. fprintf(stderr, " -tune-ssim Tune trellis optimization for SSIM\n");
  180. fprintf(stderr, " -tune-ms-ssim Tune trellis optimization for MS-SSIM\n");
  181. fprintf(stderr, "Switches for advanced users:\n");
  182. fprintf(stderr, " -noovershoot Disable black-on-white deringing via overshoot\n");
  183. fprintf(stderr, " -nojfif Do not write JFIF (reduces size by 18 bytes but breaks standards; no known problems in Web browsers)\n");
  184. #ifdef C_ARITH_CODING_SUPPORTED
  185. fprintf(stderr, " -arithmetic Use arithmetic coding\n");
  186. #endif
  187. #ifdef DCT_ISLOW_SUPPORTED
  188. fprintf(stderr, " -dct int Use integer DCT method%s\n",
  189. (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
  190. #endif
  191. #ifdef DCT_IFAST_SUPPORTED
  192. fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",
  193. (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
  194. #endif
  195. #ifdef DCT_FLOAT_SUPPORTED
  196. fprintf(stderr, " -dct float Use floating-point DCT method%s\n",
  197. (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
  198. #endif
  199. fprintf(stderr, " -quant-baseline Use 8-bit quantization table entries for baseline JPEG compatibility\n");
  200. fprintf(stderr, " -quant-table N Use predefined quantization table N:\n");
  201. fprintf(stderr, " - 0 JPEG Annex K\n");
  202. fprintf(stderr, " - 1 Flat\n");
  203. fprintf(stderr, " - 2 Custom, tuned for MS-SSIM\n");
  204. fprintf(stderr, " - 3 ImageMagick table by N. Robidoux\n");
  205. fprintf(stderr, " - 4 Custom, tuned for PSNR-HVS\n");
  206. fprintf(stderr, " - 5 Table from paper by Klein, Silverstein and Carney\n");
  207. fprintf(stderr, " -icc FILE Embed ICC profile contained in FILE\n");
  208. fprintf(stderr, " -restart N Set restart interval in rows, or in blocks with B\n");
  209. #ifdef INPUT_SMOOTHING_SUPPORTED
  210. fprintf(stderr, " -smooth N Smooth dithered input (N=1..100 is strength)\n");
  211. #endif
  212. fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
  213. fprintf(stderr, " -outfile name Specify name for output file\n");
  214. #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
  215. fprintf(stderr, " -memdst Compress to memory instead of file (useful for benchmarking)\n");
  216. #endif
  217. fprintf(stderr, " -verbose or -debug Emit debug output\n");
  218. fprintf(stderr, " -version Print version information and exit\n");
  219. fprintf(stderr, "Switches for wizards:\n");
  220. fprintf(stderr, " -qtables FILE Use quantization tables given in FILE\n");
  221. fprintf(stderr, " -qslots N[,...] Set component quantization tables\n");
  222. fprintf(stderr, " -sample HxV[,...] Set component sampling factors\n");
  223. #ifdef C_MULTISCAN_FILES_SUPPORTED
  224. fprintf(stderr, " -scans FILE Create multi-scan JPEG per script FILE\n");
  225. #endif
  226. exit(EXIT_FAILURE);
  227. }
  228. LOCAL(int)
  229. parse_switches(j_compress_ptr cinfo, int argc, char **argv,
  230. int last_file_arg_seen, boolean for_real)
  231. /* Parse optional switches.
  232. * Returns argv[] index of first file-name argument (== argc if none).
  233. * Any file names with indexes <= last_file_arg_seen are ignored;
  234. * they have presumably been processed in a previous iteration.
  235. * (Pass 0 for last_file_arg_seen on the first or only iteration.)
  236. * for_real is FALSE on the first (dummy) pass; we may skip any expensive
  237. * processing.
  238. */
  239. {
  240. int argn;
  241. char *arg;
  242. boolean force_baseline;
  243. boolean simple_progressive;
  244. char *qualityarg = NULL; /* saves -quality parm if any */
  245. char *qtablefile = NULL; /* saves -qtables filename if any */
  246. char *qslotsarg = NULL; /* saves -qslots parm if any */
  247. char *samplearg = NULL; /* saves -sample parm if any */
  248. char *scansarg = NULL; /* saves -scans parm if any */
  249. /* Set up default JPEG parameters. */
  250. force_baseline = FALSE; /* by default, allow 16-bit quantizers */
  251. #ifdef C_PROGRESSIVE_SUPPORTED
  252. simple_progressive = cinfo->num_scans == 0 ? FALSE : TRUE;
  253. #else
  254. simple_progressive = FALSE;
  255. #endif
  256. is_targa = FALSE;
  257. icc_filename = NULL;
  258. outfilename = NULL;
  259. memdst = FALSE;
  260. cinfo->err->trace_level = 0;
  261. /* Scan command line options, adjust parameters */
  262. for (argn = 1; argn < argc; argn++) {
  263. arg = argv[argn];
  264. if (*arg != '-') {
  265. /* Not a switch, must be a file name argument */
  266. if (argn <= last_file_arg_seen) {
  267. outfilename = NULL; /* -outfile applies to just one input file */
  268. continue; /* ignore this name if previously processed */
  269. }
  270. break; /* else done parsing switches */
  271. }
  272. arg++; /* advance past switch marker character */
  273. if (keymatch(arg, "arithmetic", 1)) {
  274. /* Use arithmetic coding. */
  275. #ifdef C_ARITH_CODING_SUPPORTED
  276. cinfo->arith_code = TRUE;
  277. /* No table optimization required for AC */
  278. cinfo->optimize_coding = FALSE;
  279. #else
  280. fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
  281. progname);
  282. exit(EXIT_FAILURE);
  283. #endif
  284. } else if (keymatch(arg, "baseline", 1)) {
  285. /* Force baseline-compatible output (8-bit quantizer values). */
  286. force_baseline = TRUE;
  287. /* Disable multiple scans */
  288. simple_progressive = FALSE;
  289. cinfo->num_scans = 0;
  290. cinfo->scan_info = NULL;
  291. } else if (keymatch(arg, "dct", 2)) {
  292. /* Select DCT algorithm. */
  293. if (++argn >= argc) { /* advance to next argument */
  294. fprintf(stderr, "%s: missing argument for dct\n", progname);
  295. usage();
  296. }
  297. if (keymatch(argv[argn], "int", 1)) {
  298. cinfo->dct_method = JDCT_ISLOW;
  299. } else if (keymatch(argv[argn], "fast", 2)) {
  300. cinfo->dct_method = JDCT_IFAST;
  301. } else if (keymatch(argv[argn], "float", 2)) {
  302. cinfo->dct_method = JDCT_FLOAT;
  303. } else {
  304. fprintf(stderr, "%s: invalid argument for dct\n", progname);
  305. usage();
  306. }
  307. } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
  308. /* Enable debug printouts. */
  309. /* On first -d, print version identification */
  310. static boolean printed_version = FALSE;
  311. if (!printed_version) {
  312. fprintf(stderr, "%s version %s (build %s)\n",
  313. PACKAGE_NAME, VERSION, BUILD);
  314. fprintf(stderr, "%s\n\n", JCOPYRIGHT);
  315. fprintf(stderr, "Emulating The Independent JPEG Group's software, version %s\n\n",
  316. JVERSION);
  317. printed_version = TRUE;
  318. }
  319. cinfo->err->trace_level++;
  320. } else if (keymatch(arg, "version", 4)) {
  321. fprintf(stderr, "%s version %s (build %s)\n",
  322. PACKAGE_NAME, VERSION, BUILD);
  323. exit(EXIT_SUCCESS);
  324. } else if (keymatch(arg, "fastcrush", 4)) {
  325. jpeg_c_set_bool_param(cinfo, JBOOLEAN_OPTIMIZE_SCANS, FALSE);
  326. } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
  327. /* Force a monochrome JPEG file to be generated. */
  328. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  329. } else if (keymatch(arg, "rgb", 3)) {
  330. /* Force an RGB JPEG file to be generated. */
  331. jpeg_set_colorspace(cinfo, JCS_RGB);
  332. } else if (keymatch(arg, "lambda1", 7)) {
  333. if (++argn >= argc) /* advance to next argument */
  334. usage();
  335. jpeg_c_set_float_param(cinfo, JFLOAT_LAMBDA_LOG_SCALE1,
  336. atof(argv[argn]));
  337. } else if (keymatch(arg, "lambda2", 7)) {
  338. if (++argn >= argc) /* advance to next argument */
  339. usage();
  340. jpeg_c_set_float_param(cinfo, JFLOAT_LAMBDA_LOG_SCALE2,
  341. atof(argv[argn]));
  342. } else if (keymatch(arg, "icc", 1)) {
  343. /* Set ICC filename. */
  344. if (++argn >= argc) /* advance to next argument */
  345. usage();
  346. icc_filename = argv[argn];
  347. } else if (keymatch(arg, "maxmemory", 3)) {
  348. /* Maximum memory in Kb (or Mb with 'm'). */
  349. long lval;
  350. char ch = 'x';
  351. if (++argn >= argc) /* advance to next argument */
  352. usage();
  353. if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
  354. usage();
  355. if (ch == 'm' || ch == 'M')
  356. lval *= 1000L;
  357. cinfo->mem->max_memory_to_use = lval * 1000L;
  358. } else if (keymatch(arg, "dc-scan-opt", 3)) {
  359. if (++argn >= argc) { /* advance to next argument */
  360. fprintf(stderr, "%s: missing argument for dc-scan-opt\n", progname);
  361. usage();
  362. }
  363. jpeg_c_set_int_param(cinfo, JINT_DC_SCAN_OPT_MODE, atoi(argv[argn]));
  364. } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
  365. /* Enable entropy parm optimization. */
  366. #ifdef ENTROPY_OPT_SUPPORTED
  367. cinfo->optimize_coding = TRUE;
  368. #else
  369. fprintf(stderr, "%s: sorry, entropy optimization was not compiled in\n",
  370. progname);
  371. exit(EXIT_FAILURE);
  372. #endif
  373. } else if (keymatch(arg, "outfile", 4)) {
  374. /* Set output file name. */
  375. if (++argn >= argc) { /* advance to next argument */
  376. fprintf(stderr, "%s: missing argument for outfile\n", progname);
  377. usage();
  378. }
  379. outfilename = argv[argn]; /* save it away for later use */
  380. } else if (keymatch(arg, "progressive", 1)) {
  381. /* Select simple progressive mode. */
  382. #ifdef C_PROGRESSIVE_SUPPORTED
  383. simple_progressive = TRUE;
  384. /* We must postpone execution until num_components is known. */
  385. #else
  386. fprintf(stderr, "%s: sorry, progressive output was not compiled in\n",
  387. progname);
  388. exit(EXIT_FAILURE);
  389. #endif
  390. } else if (keymatch(arg, "memdst", 2)) {
  391. /* Use in-memory destination manager */
  392. #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
  393. memdst = TRUE;
  394. #else
  395. fprintf(stderr, "%s: sorry, in-memory destination manager was not compiled in\n",
  396. progname);
  397. exit(EXIT_FAILURE);
  398. #endif
  399. } else if (keymatch(arg, "quality", 1)) {
  400. /* Quality ratings (quantization table scaling factors). */
  401. if (++argn >= argc) { /* advance to next argument */
  402. fprintf(stderr, "%s: missing argument for quality\n", progname);
  403. usage();
  404. }
  405. qualityarg = argv[argn];
  406. } else if (keymatch(arg, "qslots", 2)) {
  407. /* Quantization table slot numbers. */
  408. if (++argn >= argc) /* advance to next argument */
  409. usage();
  410. qslotsarg = argv[argn];
  411. /* Must delay setting qslots until after we have processed any
  412. * colorspace-determining switches, since jpeg_set_colorspace sets
  413. * default quant table numbers.
  414. */
  415. } else if (keymatch(arg, "qtables", 2)) {
  416. /* Quantization tables fetched from file. */
  417. if (++argn >= argc) /* advance to next argument */
  418. usage();
  419. qtablefile = argv[argn];
  420. /* We postpone actually reading the file in case -quality comes later. */
  421. } else if (keymatch(arg, "quant-table", 7)) {
  422. int val;
  423. if (++argn >= argc) /* advance to next argument */
  424. usage();
  425. val = atoi(argv[argn]);
  426. jpeg_c_set_int_param(cinfo, JINT_BASE_QUANT_TBL_IDX, val);
  427. if (jpeg_c_get_int_param(cinfo, JINT_BASE_QUANT_TBL_IDX) != val) {
  428. fprintf(stderr, "%s: %d is invalid argument for quant-table\n", progname, val);
  429. usage();
  430. }
  431. jpeg_set_quality(cinfo, 75, TRUE);
  432. } else if (keymatch(arg, "quant-baseline", 7)) {
  433. /* Force quantization table to meet baseline requirements */
  434. force_baseline = TRUE;
  435. } else if (keymatch(arg, "restart", 1)) {
  436. /* Restart interval in MCU rows (or in MCUs with 'b'). */
  437. long lval;
  438. char ch = 'x';
  439. if (++argn >= argc) /* advance to next argument */
  440. usage();
  441. if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
  442. usage();
  443. if (lval < 0 || lval > 65535L)
  444. usage();
  445. if (ch == 'b' || ch == 'B') {
  446. cinfo->restart_interval = (unsigned int)lval;
  447. cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
  448. } else {
  449. cinfo->restart_in_rows = (int)lval;
  450. /* restart_interval will be computed during startup */
  451. }
  452. } else if (keymatch(arg, "revert", 3)) {
  453. /* revert to old JPEG default */
  454. jpeg_c_set_int_param(cinfo, JINT_COMPRESS_PROFILE, JCP_FASTEST);
  455. jpeg_set_defaults(cinfo);
  456. } else if (keymatch(arg, "sample", 2)) {
  457. /* Set sampling factors. */
  458. if (++argn >= argc) /* advance to next argument */
  459. usage();
  460. samplearg = argv[argn];
  461. /* Must delay setting sample factors until after we have processed any
  462. * colorspace-determining switches, since jpeg_set_colorspace sets
  463. * default sampling factors.
  464. */
  465. } else if (keymatch(arg, "scans", 4)) {
  466. /* Set scan script. */
  467. #ifdef C_MULTISCAN_FILES_SUPPORTED
  468. if (++argn >= argc) /* advance to next argument */
  469. usage();
  470. scansarg = argv[argn];
  471. /* We must postpone reading the file in case -progressive appears. */
  472. #else
  473. fprintf(stderr, "%s: sorry, multi-scan output was not compiled in\n",
  474. progname);
  475. exit(EXIT_FAILURE);
  476. #endif
  477. } else if (keymatch(arg, "smooth", 2)) {
  478. /* Set input smoothing factor. */
  479. int val;
  480. if (++argn >= argc) /* advance to next argument */
  481. usage();
  482. if (sscanf(argv[argn], "%d", &val) != 1)
  483. usage();
  484. if (val < 0 || val > 100)
  485. usage();
  486. cinfo->smoothing_factor = val;
  487. } else if (keymatch(arg, "targa", 1)) {
  488. /* Input file is Targa format. */
  489. is_targa = TRUE;
  490. } else if (keymatch(arg, "notrellis-dc", 11)) {
  491. /* disable trellis quantization */
  492. jpeg_c_set_bool_param(cinfo, JBOOLEAN_TRELLIS_QUANT_DC, FALSE);
  493. } else if (keymatch(arg, "notrellis", 1)) {
  494. /* disable trellis quantization */
  495. jpeg_c_set_bool_param(cinfo, JBOOLEAN_TRELLIS_QUANT, FALSE);
  496. } else if (keymatch(arg, "trellis-dc-ver-weight", 12)) {
  497. if (++argn >= argc) { /* advance to next argument */
  498. fprintf(stderr, "%s: missing argument for trellis-dc-ver-weight\n", progname);
  499. usage();
  500. }
  501. jpeg_c_set_float_param(cinfo, JFLOAT_TRELLIS_DELTA_DC_WEIGHT, atof(argv[argn]));
  502. } else if (keymatch(arg, "trellis-dc", 9)) {
  503. /* enable DC trellis quantization */
  504. jpeg_c_set_bool_param(cinfo, JBOOLEAN_TRELLIS_QUANT_DC, TRUE);
  505. } else if (keymatch(arg, "tune-psnr", 6)) {
  506. jpeg_c_set_int_param(cinfo, JINT_BASE_QUANT_TBL_IDX, 1);
  507. jpeg_c_set_float_param(cinfo, JFLOAT_LAMBDA_LOG_SCALE1, 9.0);
  508. jpeg_c_set_float_param(cinfo, JFLOAT_LAMBDA_LOG_SCALE2, 0.0);
  509. jpeg_c_set_bool_param(cinfo, JBOOLEAN_USE_LAMBDA_WEIGHT_TBL, FALSE);
  510. jpeg_set_quality(cinfo, 75, TRUE);
  511. } else if (keymatch(arg, "tune-ssim", 6)) {
  512. jpeg_c_set_int_param(cinfo, JINT_BASE_QUANT_TBL_IDX, 1);
  513. jpeg_c_set_float_param(cinfo, JFLOAT_LAMBDA_LOG_SCALE1, 11.5);
  514. jpeg_c_set_float_param(cinfo, JFLOAT_LAMBDA_LOG_SCALE2, 12.75);
  515. jpeg_c_set_bool_param(cinfo, JBOOLEAN_USE_LAMBDA_WEIGHT_TBL, FALSE);
  516. jpeg_set_quality(cinfo, 75, TRUE);
  517. } else if (keymatch(arg, "tune-ms-ssim", 6)) {
  518. jpeg_c_set_int_param(cinfo, JINT_BASE_QUANT_TBL_IDX, 3);
  519. jpeg_c_set_float_param(cinfo, JFLOAT_LAMBDA_LOG_SCALE1, 12.0);
  520. jpeg_c_set_float_param(cinfo, JFLOAT_LAMBDA_LOG_SCALE2, 13.0);
  521. jpeg_c_set_bool_param(cinfo, JBOOLEAN_USE_LAMBDA_WEIGHT_TBL, TRUE);
  522. jpeg_set_quality(cinfo, 75, TRUE);
  523. } else if (keymatch(arg, "tune-hvs-psnr", 6)) {
  524. jpeg_c_set_int_param(cinfo, JINT_BASE_QUANT_TBL_IDX, 3);
  525. jpeg_c_set_float_param(cinfo, JFLOAT_LAMBDA_LOG_SCALE1, 14.75);
  526. jpeg_c_set_float_param(cinfo, JFLOAT_LAMBDA_LOG_SCALE2, 16.5);
  527. jpeg_c_set_bool_param(cinfo, JBOOLEAN_USE_LAMBDA_WEIGHT_TBL, TRUE);
  528. jpeg_set_quality(cinfo, 75, TRUE);
  529. } else if (keymatch(arg, "noovershoot", 11)) {
  530. jpeg_c_set_bool_param(cinfo, JBOOLEAN_OVERSHOOT_DERINGING, FALSE);
  531. } else if (keymatch(arg, "nojfif", 6)) {
  532. cinfo->write_JFIF_header = 0;
  533. } else {
  534. fprintf(stderr, "%s: unknown option '%s'\n", progname, arg);
  535. usage(); /* bogus switch */
  536. }
  537. }
  538. /* Post-switch-scanning cleanup */
  539. if (for_real) {
  540. /* Set quantization tables for selected quality. */
  541. /* Some or all may be overridden if -qtables is present. */
  542. if (qualityarg != NULL) /* process -quality if it was present */
  543. if (! set_quality_ratings(cinfo, qualityarg, force_baseline)) {
  544. fprintf(stderr, "%s: can't set quality ratings\n", progname);
  545. usage();
  546. }
  547. if (qtablefile != NULL) /* process -qtables if it was present */
  548. if (! read_quant_tables(cinfo, qtablefile, force_baseline)) {
  549. fprintf(stderr, "%s: can't read qtable file\n", progname);
  550. usage();
  551. }
  552. if (qslotsarg != NULL) /* process -qslots if it was present */
  553. if (!set_quant_slots(cinfo, qslotsarg))
  554. usage();
  555. /* set_quality_ratings sets default subsampling, so the explicit
  556. subsampling must be set after it */
  557. if (samplearg != NULL) /* process -sample if it was present */
  558. if (! set_sample_factors(cinfo, samplearg)) {
  559. fprintf(stderr, "%s: can't set sample factors\n", progname);
  560. usage();
  561. }
  562. #ifdef C_PROGRESSIVE_SUPPORTED
  563. if (simple_progressive) /* process -progressive; -scans can override */
  564. jpeg_simple_progression(cinfo);
  565. #endif
  566. #ifdef C_MULTISCAN_FILES_SUPPORTED
  567. if (scansarg != NULL) /* process -scans if it was present */
  568. if (!read_scan_script(cinfo, scansarg))
  569. usage();
  570. #endif
  571. }
  572. return argn; /* return index of next arg (file name) */
  573. }
  574. /*
  575. * The main program.
  576. */
  577. int
  578. main(int argc, char **argv)
  579. {
  580. struct jpeg_compress_struct cinfo;
  581. struct jpeg_error_mgr jerr;
  582. #ifdef PROGRESS_REPORT
  583. struct cdjpeg_progress_mgr progress;
  584. #endif
  585. int file_index;
  586. cjpeg_source_ptr src_mgr;
  587. FILE *input_file;
  588. FILE *icc_file;
  589. JOCTET *icc_profile = NULL;
  590. long icc_len = 0;
  591. FILE *output_file = NULL;
  592. unsigned char *outbuffer = NULL;
  593. unsigned long outsize = 0;
  594. JDIMENSION num_scanlines;
  595. /* On Mac, fetch a command line. */
  596. #ifdef USE_CCOMMAND
  597. argc = ccommand(&argv);
  598. #endif
  599. progname = argv[0];
  600. if (progname == NULL || progname[0] == 0)
  601. progname = "cjpeg"; /* in case C library doesn't provide it */
  602. /* Initialize the JPEG compression object with default error handling. */
  603. cinfo.err = jpeg_std_error(&jerr);
  604. jpeg_create_compress(&cinfo);
  605. /* Add some application-specific error messages (from cderror.h) */
  606. jerr.addon_message_table = cdjpeg_message_table;
  607. jerr.first_addon_message = JMSG_FIRSTADDONCODE;
  608. jerr.last_addon_message = JMSG_LASTADDONCODE;
  609. /* Initialize JPEG parameters.
  610. * Much of this may be overridden later.
  611. * In particular, we don't yet know the input file's color space,
  612. * but we need to provide some value for jpeg_set_defaults() to work.
  613. */
  614. cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
  615. jpeg_set_defaults(&cinfo);
  616. /* Scan command line to find file names.
  617. * It is convenient to use just one switch-parsing routine, but the switch
  618. * values read here are ignored; we will rescan the switches after opening
  619. * the input file.
  620. */
  621. file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
  622. #ifdef TWO_FILE_COMMANDLINE
  623. if (!memdst) {
  624. /* Must have either -outfile switch or explicit output file name */
  625. if (outfilename == NULL) {
  626. if (file_index != argc - 2) {
  627. fprintf(stderr, "%s: must name one input and one output file\n",
  628. progname);
  629. usage();
  630. }
  631. outfilename = argv[file_index + 1];
  632. } else {
  633. if (file_index != argc - 1) {
  634. fprintf(stderr, "%s: must name one input and one output file\n",
  635. progname);
  636. usage();
  637. }
  638. }
  639. }
  640. #else
  641. /* Unix style: expect zero or one file name */
  642. if (file_index < argc - 1) {
  643. fprintf(stderr, "%s: only one input file\n", progname);
  644. usage();
  645. }
  646. #endif /* TWO_FILE_COMMANDLINE */
  647. /* Open the input file. */
  648. if (file_index < argc) {
  649. if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
  650. fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
  651. exit(EXIT_FAILURE);
  652. }
  653. } else {
  654. /* default input file is stdin */
  655. input_file = read_stdin();
  656. }
  657. /* Open the output file. */
  658. if (outfilename != NULL) {
  659. if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
  660. fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
  661. exit(EXIT_FAILURE);
  662. }
  663. } else if (!memdst) {
  664. /* default output file is stdout */
  665. output_file = write_stdout();
  666. }
  667. if (icc_filename != NULL) {
  668. if ((icc_file = fopen(icc_filename, READ_BINARY)) == NULL) {
  669. fprintf(stderr, "%s: can't open %s\n", progname, icc_filename);
  670. exit(EXIT_FAILURE);
  671. }
  672. if (fseek(icc_file, 0, SEEK_END) < 0 ||
  673. (icc_len = ftell(icc_file)) < 1 ||
  674. fseek(icc_file, 0, SEEK_SET) < 0) {
  675. fprintf(stderr, "%s: can't determine size of %s\n", progname,
  676. icc_filename);
  677. exit(EXIT_FAILURE);
  678. }
  679. if ((icc_profile = (JOCTET *)malloc(icc_len)) == NULL) {
  680. fprintf(stderr, "%s: can't allocate memory for ICC profile\n", progname);
  681. fclose(icc_file);
  682. exit(EXIT_FAILURE);
  683. }
  684. if (fread(icc_profile, icc_len, 1, icc_file) < 1) {
  685. fprintf(stderr, "%s: can't read ICC profile from %s\n", progname,
  686. icc_filename);
  687. free(icc_profile);
  688. fclose(icc_file);
  689. exit(EXIT_FAILURE);
  690. }
  691. fclose(icc_file);
  692. }
  693. #ifdef PROGRESS_REPORT
  694. start_progress_monitor((j_common_ptr)&cinfo, &progress);
  695. #endif
  696. /* Figure out the input file format, and set up to read it. */
  697. src_mgr = select_file_type(&cinfo, input_file);
  698. src_mgr->input_file = input_file;
  699. /* Read the input file header to obtain file size & colorspace. */
  700. (*src_mgr->start_input) (&cinfo, src_mgr);
  701. /* Now that we know input colorspace, fix colorspace-dependent defaults */
  702. #if JPEG_RAW_READER
  703. if (!is_jpeg)
  704. #endif
  705. jpeg_default_colorspace(&cinfo);
  706. /* Adjust default compression parameters by re-parsing the options */
  707. file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
  708. /* Specify data destination for compression */
  709. #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED)
  710. if (memdst)
  711. jpeg_mem_dest(&cinfo, &outbuffer, &outsize);
  712. else
  713. #endif
  714. jpeg_stdio_dest(&cinfo, output_file);
  715. /* Start compressor */
  716. jpeg_start_compress(&cinfo, TRUE);
  717. /* Copy metadata */
  718. if (copy_markers) {
  719. jpeg_saved_marker_ptr marker;
  720. /* In the current implementation, we don't actually need to examine the
  721. * option flag here; we just copy everything that got saved.
  722. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  723. * if the encoder library already wrote one.
  724. */
  725. for (marker = src_mgr->marker_list; marker != NULL; marker = marker->next) {
  726. if (cinfo.write_JFIF_header &&
  727. marker->marker == JPEG_APP0 &&
  728. marker->data_length >= 5 &&
  729. GETJOCTET(marker->data[0]) == 0x4A &&
  730. GETJOCTET(marker->data[1]) == 0x46 &&
  731. GETJOCTET(marker->data[2]) == 0x49 &&
  732. GETJOCTET(marker->data[3]) == 0x46 &&
  733. GETJOCTET(marker->data[4]) == 0)
  734. continue; /* reject duplicate JFIF */
  735. if (cinfo.write_Adobe_marker &&
  736. marker->marker == JPEG_APP0+14 &&
  737. marker->data_length >= 5 &&
  738. GETJOCTET(marker->data[0]) == 0x41 &&
  739. GETJOCTET(marker->data[1]) == 0x64 &&
  740. GETJOCTET(marker->data[2]) == 0x6F &&
  741. GETJOCTET(marker->data[3]) == 0x62 &&
  742. GETJOCTET(marker->data[4]) == 0x65)
  743. continue; /* reject duplicate Adobe */
  744. jpeg_write_marker(&cinfo, marker->marker, marker->data,
  745. marker->data_length);
  746. }
  747. }
  748. if (icc_profile != NULL)
  749. jpeg_write_icc_profile(&cinfo, icc_profile, (unsigned int)icc_len);
  750. /* Process data */
  751. while (cinfo.next_scanline < cinfo.image_height) {
  752. num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
  753. #if JPEG_RAW_READER
  754. if (is_jpeg)
  755. (void) jpeg_write_raw_data(&cinfo, src_mgr->plane_pointer, num_scanlines);
  756. else
  757. #endif
  758. (void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
  759. }
  760. /* Finish compression and release memory */
  761. (*src_mgr->finish_input) (&cinfo, src_mgr);
  762. jpeg_finish_compress(&cinfo);
  763. jpeg_destroy_compress(&cinfo);
  764. /* Close files, if we opened them */
  765. if (input_file != stdin)
  766. fclose(input_file);
  767. if (output_file != stdout && output_file != NULL)
  768. fclose(output_file);
  769. #ifdef PROGRESS_REPORT
  770. end_progress_monitor((j_common_ptr)&cinfo);
  771. #endif
  772. if (memdst) {
  773. fprintf(stderr, "Compressed size: %lu bytes\n", outsize);
  774. free(outbuffer);
  775. }
  776. free(icc_profile);
  777. /* All done. */
  778. exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
  779. return 0; /* suppress no-return-value warnings */
  780. }