Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

616 lines
20 KiB

  1. /*
  2. * cjpeg.c
  3. *
  4. * Copyright (C) 1991-1998, Thomas G. Lane.
  5. * Modified 2003-2008 by Guido Vollbeding.
  6. * This file is part of the Independent JPEG Group's software.
  7. * For conditions of distribution and use, see the accompanying README file.
  8. *
  9. * This file contains a command-line user interface for the JPEG compressor.
  10. * It should work on any system with Unix- or MS-DOS-style command lines.
  11. *
  12. * Two different command line styles are permitted, depending on the
  13. * compile-time switch TWO_FILE_COMMANDLINE:
  14. * cjpeg [options] inputfile outputfile
  15. * cjpeg [options] [inputfile]
  16. * In the second style, output is always to standard output, which you'd
  17. * normally redirect to a file or pipe to some other program. Input is
  18. * either from a named file or from standard input (typically redirected).
  19. * The second style is convenient on Unix but is unhelpful on systems that
  20. * don't support pipes. Also, you MUST use the first style if your system
  21. * doesn't do binary I/O to stdin/stdout.
  22. * To simplify script writing, the "-outfile" switch is provided. The syntax
  23. * cjpeg [options] -outfile outputfile inputfile
  24. * works regardless of which command line style is used.
  25. */
  26. #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
  27. #include "jversion.h" /* for version message */
  28. #ifdef USE_CCOMMAND /* command-line reader for Macintosh */
  29. #ifdef __MWERKS__
  30. #include <SIOUX.h> /* Metrowerks needs this */
  31. #include <console.h> /* ... and this */
  32. #endif
  33. #ifdef THINK_C
  34. #include <console.h> /* Think declares it here */
  35. #endif
  36. #endif
  37. /* Create the add-on message string table. */
  38. #define JMESSAGE(code,string) string ,
  39. static const char * const cdjpeg_message_table[] = {
  40. #include "cderror.h"
  41. NULL
  42. };
  43. /*
  44. * This routine determines what format the input file is,
  45. * and selects the appropriate input-reading module.
  46. *
  47. * To determine which family of input formats the file belongs to,
  48. * we may look only at the first byte of the file, since C does not
  49. * guarantee that more than one character can be pushed back with ungetc.
  50. * Looking at additional bytes would require one of these approaches:
  51. * 1) assume we can fseek() the input file (fails for piped input);
  52. * 2) assume we can push back more than one character (works in
  53. * some C implementations, but unportable);
  54. * 3) provide our own buffering (breaks input readers that want to use
  55. * stdio directly, such as the RLE library);
  56. * or 4) don't put back the data, and modify the input_init methods to assume
  57. * they start reading after the start of file (also breaks RLE library).
  58. * #1 is attractive for MS-DOS but is untenable on Unix.
  59. *
  60. * The most portable solution for file types that can't be identified by their
  61. * first byte is to make the user tell us what they are. This is also the
  62. * only approach for "raw" file types that contain only arbitrary values.
  63. * We presently apply this method for Targa files. Most of the time Targa
  64. * files start with 0x00, so we recognize that case. Potentially, however,
  65. * a Targa file could start with any byte value (byte 0 is the length of the
  66. * seldom-used ID field), so we provide a switch to force Targa input mode.
  67. */
  68. static boolean is_targa; /* records user -targa switch */
  69. LOCAL(cjpeg_source_ptr)
  70. select_file_type (j_compress_ptr cinfo, FILE * infile)
  71. {
  72. int c;
  73. if (is_targa) {
  74. #ifdef TARGA_SUPPORTED
  75. return jinit_read_targa(cinfo);
  76. #else
  77. ERREXIT(cinfo, JERR_TGA_NOTCOMP);
  78. #endif
  79. }
  80. if ((c = getc(infile)) == EOF)
  81. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  82. if (ungetc(c, infile) == EOF)
  83. ERREXIT(cinfo, JERR_UNGETC_FAILED);
  84. switch (c) {
  85. #ifdef BMP_SUPPORTED
  86. case 'B':
  87. return jinit_read_bmp(cinfo);
  88. #endif
  89. #ifdef GIF_SUPPORTED
  90. case 'G':
  91. return jinit_read_gif(cinfo);
  92. #endif
  93. #ifdef PPM_SUPPORTED
  94. case 'P':
  95. return jinit_read_ppm(cinfo);
  96. #endif
  97. #ifdef RLE_SUPPORTED
  98. case 'R':
  99. return jinit_read_rle(cinfo);
  100. #endif
  101. #ifdef TARGA_SUPPORTED
  102. case 0x00:
  103. return jinit_read_targa(cinfo);
  104. #endif
  105. default:
  106. ERREXIT(cinfo, JERR_UNKNOWN_FORMAT);
  107. break;
  108. }
  109. return NULL; /* suppress compiler warnings */
  110. }
  111. /*
  112. * Argument-parsing code.
  113. * The switch parser is designed to be useful with DOS-style command line
  114. * syntax, ie, intermixed switches and file names, where only the switches
  115. * to the left of a given file name affect processing of that file.
  116. * The main program in this file doesn't actually use this capability...
  117. */
  118. static const char * progname; /* program name for error messages */
  119. static char * outfilename; /* for -outfile switch */
  120. LOCAL(void)
  121. usage (void)
  122. /* complain about bad command line */
  123. {
  124. fprintf(stderr, "usage: %s [switches] ", progname);
  125. #ifdef TWO_FILE_COMMANDLINE
  126. fprintf(stderr, "inputfile outputfile\n");
  127. #else
  128. fprintf(stderr, "[inputfile]\n");
  129. #endif
  130. fprintf(stderr, "Switches (names may be abbreviated):\n");
  131. fprintf(stderr, " -quality N[,...] Compression quality (0..100; 5-95 is useful range)\n");
  132. fprintf(stderr, " -grayscale Create monochrome JPEG file\n");
  133. #ifdef ENTROPY_OPT_SUPPORTED
  134. fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression)\n");
  135. #endif
  136. #ifdef C_PROGRESSIVE_SUPPORTED
  137. fprintf(stderr, " -progressive Create progressive JPEG file\n");
  138. #endif
  139. #ifdef DCT_SCALING_SUPPORTED
  140. fprintf(stderr, " -scale M/N Scale image by fraction M/N, eg, 1/2\n");
  141. #endif
  142. #ifdef TARGA_SUPPORTED
  143. fprintf(stderr, " -targa Input file is Targa format (usually not needed)\n");
  144. #endif
  145. fprintf(stderr, "Switches for advanced users:\n");
  146. #ifdef DCT_ISLOW_SUPPORTED
  147. fprintf(stderr, " -dct int Use integer DCT method%s\n",
  148. (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
  149. #endif
  150. #ifdef DCT_IFAST_SUPPORTED
  151. fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",
  152. (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
  153. #endif
  154. #ifdef DCT_FLOAT_SUPPORTED
  155. fprintf(stderr, " -dct float Use floating-point DCT method%s\n",
  156. (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
  157. #endif
  158. fprintf(stderr, " -nosmooth Don't use high-quality downsampling\n");
  159. fprintf(stderr, " -restart N Set restart interval in rows, or in blocks with B\n");
  160. #ifdef INPUT_SMOOTHING_SUPPORTED
  161. fprintf(stderr, " -smooth N Smooth dithered input (N=1..100 is strength)\n");
  162. #endif
  163. fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
  164. fprintf(stderr, " -outfile name Specify name for output file\n");
  165. fprintf(stderr, " -verbose or -debug Emit debug output\n");
  166. fprintf(stderr, "Switches for wizards:\n");
  167. #ifdef C_ARITH_CODING_SUPPORTED
  168. fprintf(stderr, " -arithmetic Use arithmetic coding\n");
  169. #endif
  170. fprintf(stderr, " -baseline Force baseline quantization tables\n");
  171. fprintf(stderr, " -qtables file Use quantization tables given in file\n");
  172. fprintf(stderr, " -qslots N[,...] Set component quantization tables\n");
  173. fprintf(stderr, " -sample HxV[,...] Set component sampling factors\n");
  174. #ifdef C_MULTISCAN_FILES_SUPPORTED
  175. fprintf(stderr, " -scans file Create multi-scan JPEG per script file\n");
  176. #endif
  177. exit(EXIT_FAILURE);
  178. }
  179. LOCAL(int)
  180. parse_switches (j_compress_ptr cinfo, int argc, char **argv,
  181. int last_file_arg_seen, boolean for_real)
  182. /* Parse optional switches.
  183. * Returns argv[] index of first file-name argument (== argc if none).
  184. * Any file names with indexes <= last_file_arg_seen are ignored;
  185. * they have presumably been processed in a previous iteration.
  186. * (Pass 0 for last_file_arg_seen on the first or only iteration.)
  187. * for_real is FALSE on the first (dummy) pass; we may skip any expensive
  188. * processing.
  189. */
  190. {
  191. int argn;
  192. char * arg;
  193. boolean force_baseline;
  194. boolean simple_progressive;
  195. char * qualityarg = NULL; /* saves -quality parm if any */
  196. char * qtablefile = NULL; /* saves -qtables filename if any */
  197. char * qslotsarg = NULL; /* saves -qslots parm if any */
  198. char * samplearg = NULL; /* saves -sample parm if any */
  199. char * scansarg = NULL; /* saves -scans parm if any */
  200. /* Set up default JPEG parameters. */
  201. force_baseline = FALSE; /* by default, allow 16-bit quantizers */
  202. simple_progressive = FALSE;
  203. is_targa = FALSE;
  204. outfilename = NULL;
  205. cinfo->err->trace_level = 0;
  206. /* Scan command line options, adjust parameters */
  207. for (argn = 1; argn < argc; argn++) {
  208. arg = argv[argn];
  209. if (*arg != '-') {
  210. /* Not a switch, must be a file name argument */
  211. if (argn <= last_file_arg_seen) {
  212. outfilename = NULL; /* -outfile applies to just one input file */
  213. continue; /* ignore this name if previously processed */
  214. }
  215. break; /* else done parsing switches */
  216. }
  217. arg++; /* advance past switch marker character */
  218. if (keymatch(arg, "arithmetic", 1)) {
  219. /* Use arithmetic coding. */
  220. #ifdef C_ARITH_CODING_SUPPORTED
  221. cinfo->arith_code = TRUE;
  222. #else
  223. fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
  224. progname);
  225. exit(EXIT_FAILURE);
  226. #endif
  227. } else if (keymatch(arg, "baseline", 1)) {
  228. /* Force baseline-compatible output (8-bit quantizer values). */
  229. force_baseline = TRUE;
  230. } else if (keymatch(arg, "dct", 2)) {
  231. /* Select DCT algorithm. */
  232. if (++argn >= argc) /* advance to next argument */
  233. usage();
  234. if (keymatch(argv[argn], "int", 1)) {
  235. cinfo->dct_method = JDCT_ISLOW;
  236. } else if (keymatch(argv[argn], "fast", 2)) {
  237. cinfo->dct_method = JDCT_IFAST;
  238. } else if (keymatch(argv[argn], "float", 2)) {
  239. cinfo->dct_method = JDCT_FLOAT;
  240. } else
  241. usage();
  242. } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
  243. /* Enable debug printouts. */
  244. /* On first -d, print version identification */
  245. static boolean printed_version = FALSE;
  246. if (! printed_version) {
  247. fprintf(stderr, "Independent JPEG Group's CJPEG, version %s\n%s\n",
  248. JVERSION, JCOPYRIGHT);
  249. printed_version = TRUE;
  250. }
  251. cinfo->err->trace_level++;
  252. } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
  253. /* Force a monochrome JPEG file to be generated. */
  254. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  255. } else if (keymatch(arg, "maxmemory", 3)) {
  256. /* Maximum memory in Kb (or Mb with 'm'). */
  257. long lval;
  258. char ch = 'x';
  259. if (++argn >= argc) /* advance to next argument */
  260. usage();
  261. if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
  262. usage();
  263. if (ch == 'm' || ch == 'M')
  264. lval *= 1000L;
  265. cinfo->mem->max_memory_to_use = lval * 1000L;
  266. } else if (keymatch(arg, "nosmooth", 3)) {
  267. /* Suppress fancy downsampling */
  268. cinfo->do_fancy_downsampling = FALSE;
  269. } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
  270. /* Enable entropy parm optimization. */
  271. #ifdef ENTROPY_OPT_SUPPORTED
  272. cinfo->optimize_coding = TRUE;
  273. #else
  274. fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
  275. progname);
  276. exit(EXIT_FAILURE);
  277. #endif
  278. } else if (keymatch(arg, "outfile", 4)) {
  279. /* Set output file name. */
  280. if (++argn >= argc) /* advance to next argument */
  281. usage();
  282. outfilename = argv[argn]; /* save it away for later use */
  283. } else if (keymatch(arg, "progressive", 1)) {
  284. /* Select simple progressive mode. */
  285. #ifdef C_PROGRESSIVE_SUPPORTED
  286. simple_progressive = TRUE;
  287. /* We must postpone execution until num_components is known. */
  288. #else
  289. fprintf(stderr, "%s: sorry, progressive output was not compiled\n",
  290. progname);
  291. exit(EXIT_FAILURE);
  292. #endif
  293. } else if (keymatch(arg, "quality", 1)) {
  294. /* Quality ratings (quantization table scaling factors). */
  295. if (++argn >= argc) /* advance to next argument */
  296. usage();
  297. qualityarg = argv[argn];
  298. } else if (keymatch(arg, "qslots", 2)) {
  299. /* Quantization table slot numbers. */
  300. if (++argn >= argc) /* advance to next argument */
  301. usage();
  302. qslotsarg = argv[argn];
  303. /* Must delay setting qslots until after we have processed any
  304. * colorspace-determining switches, since jpeg_set_colorspace sets
  305. * default quant table numbers.
  306. */
  307. } else if (keymatch(arg, "qtables", 2)) {
  308. /* Quantization tables fetched from file. */
  309. if (++argn >= argc) /* advance to next argument */
  310. usage();
  311. qtablefile = argv[argn];
  312. /* We postpone actually reading the file in case -quality comes later. */
  313. } else if (keymatch(arg, "restart", 1)) {
  314. /* Restart interval in MCU rows (or in MCUs with 'b'). */
  315. long lval;
  316. char ch = 'x';
  317. if (++argn >= argc) /* advance to next argument */
  318. usage();
  319. if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
  320. usage();
  321. if (lval < 0 || lval > 65535L)
  322. usage();
  323. if (ch == 'b' || ch == 'B') {
  324. cinfo->restart_interval = (unsigned int) lval;
  325. cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
  326. } else {
  327. cinfo->restart_in_rows = (int) lval;
  328. /* restart_interval will be computed during startup */
  329. }
  330. } else if (keymatch(arg, "sample", 2)) {
  331. /* Set sampling factors. */
  332. if (++argn >= argc) /* advance to next argument */
  333. usage();
  334. samplearg = argv[argn];
  335. /* Must delay setting sample factors until after we have processed any
  336. * colorspace-determining switches, since jpeg_set_colorspace sets
  337. * default sampling factors.
  338. */
  339. } else if (keymatch(arg, "scale", 4)) {
  340. /* Scale the image by a fraction M/N. */
  341. if (++argn >= argc) /* advance to next argument */
  342. usage();
  343. if (sscanf(argv[argn], "%d/%d",
  344. &cinfo->scale_num, &cinfo->scale_denom) != 2)
  345. usage();
  346. } else if (keymatch(arg, "scans", 4)) {
  347. /* Set scan script. */
  348. #ifdef C_MULTISCAN_FILES_SUPPORTED
  349. if (++argn >= argc) /* advance to next argument */
  350. usage();
  351. scansarg = argv[argn];
  352. /* We must postpone reading the file in case -progressive appears. */
  353. #else
  354. fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",
  355. progname);
  356. exit(EXIT_FAILURE);
  357. #endif
  358. } else if (keymatch(arg, "smooth", 2)) {
  359. /* Set input smoothing factor. */
  360. int val;
  361. if (++argn >= argc) /* advance to next argument */
  362. usage();
  363. if (sscanf(argv[argn], "%d", &val) != 1)
  364. usage();
  365. if (val < 0 || val > 100)
  366. usage();
  367. cinfo->smoothing_factor = val;
  368. } else if (keymatch(arg, "targa", 1)) {
  369. /* Input file is Targa format. */
  370. is_targa = TRUE;
  371. } else {
  372. usage(); /* bogus switch */
  373. }
  374. }
  375. /* Post-switch-scanning cleanup */
  376. if (for_real) {
  377. /* Set quantization tables for selected quality. */
  378. /* Some or all may be overridden if -qtables is present. */
  379. if (qualityarg != NULL) /* process -quality if it was present */
  380. if (! set_quality_ratings(cinfo, qualityarg, force_baseline))
  381. usage();
  382. if (qtablefile != NULL) /* process -qtables if it was present */
  383. if (! read_quant_tables(cinfo, qtablefile, force_baseline))
  384. usage();
  385. if (qslotsarg != NULL) /* process -qslots if it was present */
  386. if (! set_quant_slots(cinfo, qslotsarg))
  387. usage();
  388. if (samplearg != NULL) /* process -sample if it was present */
  389. if (! set_sample_factors(cinfo, samplearg))
  390. usage();
  391. #ifdef C_PROGRESSIVE_SUPPORTED
  392. if (simple_progressive) /* process -progressive; -scans can override */
  393. jpeg_simple_progression(cinfo);
  394. #endif
  395. #ifdef C_MULTISCAN_FILES_SUPPORTED
  396. if (scansarg != NULL) /* process -scans if it was present */
  397. if (! read_scan_script(cinfo, scansarg))
  398. usage();
  399. #endif
  400. }
  401. return argn; /* return index of next arg (file name) */
  402. }
  403. /*
  404. * The main program.
  405. */
  406. int
  407. main (int argc, char **argv)
  408. {
  409. struct jpeg_compress_struct cinfo;
  410. struct jpeg_error_mgr jerr;
  411. #ifdef PROGRESS_REPORT
  412. struct cdjpeg_progress_mgr progress;
  413. #endif
  414. int file_index;
  415. cjpeg_source_ptr src_mgr;
  416. FILE * input_file;
  417. FILE * output_file;
  418. JDIMENSION num_scanlines;
  419. /* On Mac, fetch a command line. */
  420. #ifdef USE_CCOMMAND
  421. argc = ccommand(&argv);
  422. #endif
  423. progname = argv[0];
  424. if (progname == NULL || progname[0] == 0)
  425. progname = "cjpeg"; /* in case C library doesn't provide it */
  426. /* Initialize the JPEG compression object with default error handling. */
  427. cinfo.err = jpeg_std_error(&jerr);
  428. jpeg_create_compress(&cinfo);
  429. /* Add some application-specific error messages (from cderror.h) */
  430. jerr.addon_message_table = cdjpeg_message_table;
  431. jerr.first_addon_message = JMSG_FIRSTADDONCODE;
  432. jerr.last_addon_message = JMSG_LASTADDONCODE;
  433. /* Now safe to enable signal catcher. */
  434. #ifdef NEED_SIGNAL_CATCHER
  435. enable_signal_catcher((j_common_ptr) &cinfo);
  436. #endif
  437. /* Initialize JPEG parameters.
  438. * Much of this may be overridden later.
  439. * In particular, we don't yet know the input file's color space,
  440. * but we need to provide some value for jpeg_set_defaults() to work.
  441. */
  442. cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
  443. jpeg_set_defaults(&cinfo);
  444. /* Scan command line to find file names.
  445. * It is convenient to use just one switch-parsing routine, but the switch
  446. * values read here are ignored; we will rescan the switches after opening
  447. * the input file.
  448. */
  449. file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
  450. #ifdef TWO_FILE_COMMANDLINE
  451. /* Must have either -outfile switch or explicit output file name */
  452. if (outfilename == NULL) {
  453. if (file_index != argc-2) {
  454. fprintf(stderr, "%s: must name one input and one output file\n",
  455. progname);
  456. usage();
  457. }
  458. outfilename = argv[file_index+1];
  459. } else {
  460. if (file_index != argc-1) {
  461. fprintf(stderr, "%s: must name one input and one output file\n",
  462. progname);
  463. usage();
  464. }
  465. }
  466. #else
  467. /* Unix style: expect zero or one file name */
  468. if (file_index < argc-1) {
  469. fprintf(stderr, "%s: only one input file\n", progname);
  470. usage();
  471. }
  472. #endif /* TWO_FILE_COMMANDLINE */
  473. /* Open the input file. */
  474. if (file_index < argc) {
  475. if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
  476. fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
  477. exit(EXIT_FAILURE);
  478. }
  479. } else {
  480. /* default input file is stdin */
  481. input_file = read_stdin();
  482. }
  483. /* Open the output file. */
  484. if (outfilename != NULL) {
  485. if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
  486. fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
  487. exit(EXIT_FAILURE);
  488. }
  489. } else {
  490. /* default output file is stdout */
  491. output_file = write_stdout();
  492. }
  493. #ifdef PROGRESS_REPORT
  494. start_progress_monitor((j_common_ptr) &cinfo, &progress);
  495. #endif
  496. /* Figure out the input file format, and set up to read it. */
  497. src_mgr = select_file_type(&cinfo, input_file);
  498. src_mgr->input_file = input_file;
  499. /* Read the input file header to obtain file size & colorspace. */
  500. (*src_mgr->start_input) (&cinfo, src_mgr);
  501. /* Now that we know input colorspace, fix colorspace-dependent defaults */
  502. jpeg_default_colorspace(&cinfo);
  503. /* Adjust default compression parameters by re-parsing the options */
  504. file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
  505. /* Specify data destination for compression */
  506. jpeg_stdio_dest(&cinfo, output_file);
  507. /* Start compressor */
  508. jpeg_start_compress(&cinfo, TRUE);
  509. /* Process data */
  510. while (cinfo.next_scanline < cinfo.image_height) {
  511. num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
  512. (void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
  513. }
  514. /* Finish compression and release memory */
  515. (*src_mgr->finish_input) (&cinfo, src_mgr);
  516. jpeg_finish_compress(&cinfo);
  517. jpeg_destroy_compress(&cinfo);
  518. /* Close files, if we opened them */
  519. if (input_file != stdin)
  520. fclose(input_file);
  521. if (output_file != stdout)
  522. fclose(output_file);
  523. #ifdef PROGRESS_REPORT
  524. end_progress_monitor((j_common_ptr) &cinfo);
  525. #endif
  526. /* All done. */
  527. exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
  528. return 0; /* suppress no-return-value warnings */
  529. }