cjpeg.c 24 KB

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