cjpegalt.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. /*
  2. * alternate cjpeg.c
  3. *
  4. * Copyright (C) 1991-1998, Thomas G. Lane.
  5. * Modified 2009-2023 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 an alternate user interface for the JPEG compressor.
  10. * One or more input files are named on the command line, and output file
  11. * names are created by substituting ".jpg" for the input file's extension.
  12. */
  13. #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
  14. #include "jversion.h" /* for version message */
  15. #ifdef USE_CCOMMAND /* command-line reader for Macintosh */
  16. #ifdef __MWERKS__
  17. #include <SIOUX.h> /* Metrowerks needs this */
  18. #include <console.h> /* ... and this */
  19. #endif
  20. #ifdef THINK_C
  21. #include <console.h> /* Think declares it here */
  22. #endif
  23. #endif
  24. #ifndef PATH_MAX /* ANSI maximum-pathname-length constant */
  25. #define PATH_MAX 256
  26. #endif
  27. /* Create the add-on message string table. */
  28. #define JMESSAGE(code,string) string ,
  29. static const char * const cdjpeg_message_table[] = {
  30. #include "cderror.h"
  31. NULL
  32. };
  33. /*
  34. * Automatic determination of available memory.
  35. */
  36. static long default_maxmem; /* saves value determined at startup, or 0 */
  37. #ifndef FREE_MEM_ESTIMATE /* may be defined from command line */
  38. #ifdef MSDOS /* For MS-DOS (unless flat-memory model) */
  39. #include <dos.h> /* for access to intdos() call */
  40. LOCAL(long)
  41. unused_dos_memory (void)
  42. /* Obtain total amount of unallocated DOS memory */
  43. {
  44. union REGS regs;
  45. long nparas;
  46. regs.h.ah = 0x48; /* DOS function Allocate Memory Block */
  47. regs.x.bx = 0xFFFF; /* Ask for more memory than DOS can have */
  48. (void) intdos(&regs, &regs);
  49. /* DOS will fail and return # of paragraphs actually available in BX. */
  50. nparas = (unsigned int) regs.x.bx;
  51. /* Times 16 to convert to bytes. */
  52. return nparas << 4;
  53. }
  54. /* The default memory setting is 95% of the available space. */
  55. #define FREE_MEM_ESTIMATE ((unused_dos_memory() * 95L) / 100L)
  56. #endif /* MSDOS */
  57. #ifdef ATARI /* For Atari ST/Mega/STE/TT/Falcon, Pure C or Turbo C */
  58. #include <ext.h>
  59. /* The default memory setting is 90% of the available space. */
  60. #define FREE_MEM_ESTIMATE (((long) coreleft() * 90L) / 100L)
  61. #endif /* ATARI */
  62. /* Add memory-estimation procedures for other operating systems here,
  63. * with appropriate #ifdef's around them.
  64. */
  65. #endif /* !FREE_MEM_ESTIMATE */
  66. /*
  67. * This routine determines what format the input file is,
  68. * and selects the appropriate input-reading module.
  69. *
  70. * To determine which family of input formats the file belongs to,
  71. * we may look only at the first byte of the file, since C does not
  72. * guarantee that more than one character can be pushed back with ungetc.
  73. * Looking at additional bytes would require one of these approaches:
  74. * 1) assume we can fseek() the input file (fails for piped input);
  75. * 2) assume we can push back more than one character (works in
  76. * some C implementations, but unportable);
  77. * 3) provide our own buffering (breaks input readers that want to use
  78. * stdio directly, such as the RLE library);
  79. * or 4) don't put back the data, and modify the input_init methods to assume
  80. * they start reading after the start of file (also breaks RLE library).
  81. * #1 is attractive for MS-DOS but is untenable on Unix.
  82. *
  83. * The most portable solution for file types that can't be identified by their
  84. * first byte is to make the user tell us what they are. This is also the
  85. * only approach for "raw" file types that contain only arbitrary values.
  86. * We presently apply this method for Targa files. Most of the time Targa
  87. * files start with 0x00, so we recognize that case. Potentially, however,
  88. * a Targa file could start with any byte value (byte 0 is the length of the
  89. * seldom-used ID field), so we provide a switch to force Targa input mode.
  90. */
  91. static boolean is_targa; /* records user -targa switch */
  92. LOCAL(cjpeg_source_ptr)
  93. select_file_type (j_compress_ptr cinfo, FILE * infile)
  94. {
  95. int c;
  96. if (is_targa) {
  97. #ifdef TARGA_SUPPORTED
  98. return jinit_read_targa(cinfo);
  99. #else
  100. ERREXIT(cinfo, JERR_TGA_NOTCOMP);
  101. #endif
  102. }
  103. if ((c = getc(infile)) == EOF)
  104. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  105. if (ungetc(c, infile) == EOF)
  106. ERREXIT(cinfo, JERR_UNGETC_FAILED);
  107. switch (c) {
  108. #ifdef BMP_SUPPORTED
  109. case 'B':
  110. return jinit_read_bmp(cinfo);
  111. #endif
  112. #ifdef GIF_SUPPORTED
  113. case 'G':
  114. return jinit_read_gif(cinfo);
  115. #endif
  116. #ifdef PPM_SUPPORTED
  117. case 'P':
  118. return jinit_read_ppm(cinfo);
  119. #endif
  120. #ifdef RLE_SUPPORTED
  121. case 'R':
  122. return jinit_read_rle(cinfo);
  123. #endif
  124. #ifdef TARGA_SUPPORTED
  125. case 0x00:
  126. return jinit_read_targa(cinfo);
  127. #endif
  128. default:
  129. ERREXIT(cinfo, JERR_UNKNOWN_FORMAT);
  130. break;
  131. }
  132. return NULL; /* suppress compiler warnings */
  133. }
  134. /*
  135. * Argument-parsing code.
  136. * The switch parser is designed to be useful with DOS-style command line
  137. * syntax, ie, intermixed switches and file names, where only the switches
  138. * to the left of a given file name affect processing of that file.
  139. */
  140. static const char * progname; /* program name for error messages */
  141. static char * outfilename; /* for -outfile switch */
  142. LOCAL(void)
  143. usage (void)
  144. /* complain about bad command line */
  145. {
  146. fprintf(stderr, "usage: %s [switches] inputfile(s)\n", progname);
  147. fprintf(stderr, "List of input files may use wildcards (* and ?)\n");
  148. fprintf(stderr, "Output filename is same as input filename, but extension .jpg\n");
  149. fprintf(stderr, "Switches (names may be abbreviated):\n");
  150. fprintf(stderr, " -quality N[,...] Compression quality (0..100; 5-95 is useful range)\n");
  151. fprintf(stderr, " -grayscale Create monochrome JPEG file\n");
  152. fprintf(stderr, " -rgb Create RGB JPEG file\n");
  153. #ifdef ENTROPY_OPT_SUPPORTED
  154. fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression)\n");
  155. #endif
  156. #ifdef C_PROGRESSIVE_SUPPORTED
  157. fprintf(stderr, " -progressive Create progressive JPEG file\n");
  158. #endif
  159. #ifdef DCT_SCALING_SUPPORTED
  160. fprintf(stderr, " -scale M/N Scale image by fraction M/N, eg, 1/2\n");
  161. #endif
  162. #ifdef TARGA_SUPPORTED
  163. fprintf(stderr, " -targa Input file is Targa format (usually not needed)\n");
  164. #endif
  165. fprintf(stderr, "Switches for advanced users:\n");
  166. #ifdef C_ARITH_CODING_SUPPORTED
  167. fprintf(stderr, " -arithmetic Use arithmetic coding\n");
  168. #endif
  169. #ifdef DCT_SCALING_SUPPORTED
  170. fprintf(stderr, " -block N DCT block size (1..16; default is 8)\n");
  171. #endif
  172. #if JPEG_LIB_VERSION_MAJOR >= 9
  173. fprintf(stderr, " -rgb1 Create RGB JPEG file with reversible color transform\n");
  174. fprintf(stderr, " -bgycc Create big gamut YCC JPEG file\n");
  175. #endif
  176. #ifdef DCT_ISLOW_SUPPORTED
  177. fprintf(stderr, " -dct int Use integer DCT method%s\n",
  178. (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
  179. #endif
  180. #ifdef DCT_IFAST_SUPPORTED
  181. fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",
  182. (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
  183. #endif
  184. #ifdef DCT_FLOAT_SUPPORTED
  185. fprintf(stderr, " -dct float Use floating-point DCT method%s\n",
  186. (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
  187. #endif
  188. fprintf(stderr, " -nosmooth Don't use high-quality downsampling\n");
  189. fprintf(stderr, " -restart N Set restart interval in rows, or in blocks with B\n");
  190. #ifdef INPUT_SMOOTHING_SUPPORTED
  191. fprintf(stderr, " -smooth N Smooth dithered input (N=1..100 is strength)\n");
  192. #endif
  193. #ifndef FREE_MEM_ESTIMATE
  194. fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
  195. #endif
  196. fprintf(stderr, " -outfile name Specify name for output file\n");
  197. fprintf(stderr, " -verbose or -debug Emit debug output\n");
  198. fprintf(stderr, "Switches for wizards:\n");
  199. fprintf(stderr, " -baseline Force baseline quantization tables\n");
  200. fprintf(stderr, " -qtables file Use quantization tables given in file\n");
  201. fprintf(stderr, " -qslots N[,...] Set component quantization tables\n");
  202. fprintf(stderr, " -sample HxV[,...] Set component sampling factors\n");
  203. #ifdef C_MULTISCAN_FILES_SUPPORTED
  204. fprintf(stderr, " -scans file Create multi-scan JPEG per script file\n");
  205. #endif
  206. exit(EXIT_FAILURE);
  207. }
  208. LOCAL(int)
  209. parse_switches (j_compress_ptr cinfo, int argc, char **argv,
  210. int last_file_arg_seen, boolean for_real)
  211. /* Parse optional switches.
  212. * Returns argv[] index of first file-name argument (== argc if none).
  213. * Any file names with indexes <= last_file_arg_seen are ignored;
  214. * they have presumably been processed in a previous iteration.
  215. * (Pass 0 for last_file_arg_seen on the first or only iteration.)
  216. * for_real is FALSE on the first (dummy) pass; we may skip any expensive
  217. * processing.
  218. */
  219. {
  220. int argn;
  221. char * arg;
  222. boolean force_baseline;
  223. boolean simple_progressive;
  224. char * qualityarg = NULL; /* saves -quality parm if any */
  225. char * qtablefile = NULL; /* saves -qtables filename if any */
  226. char * qslotsarg = NULL; /* saves -qslots parm if any */
  227. char * samplearg = NULL; /* saves -sample parm if any */
  228. char * scansarg = NULL; /* saves -scans parm if any */
  229. /* Set up default JPEG parameters. */
  230. force_baseline = FALSE; /* by default, allow 16-bit quantizers */
  231. simple_progressive = FALSE;
  232. is_targa = FALSE;
  233. outfilename = NULL;
  234. cinfo->err->trace_level = 0;
  235. if (default_maxmem > 0) /* override library's default value */
  236. cinfo->mem->max_memory_to_use = default_maxmem;
  237. /* Scan command line options, adjust parameters */
  238. for (argn = 1; argn < argc; argn++) {
  239. arg = argv[argn];
  240. if (*arg != '-') {
  241. /* Not a switch, must be a file name argument */
  242. if (argn <= last_file_arg_seen) {
  243. outfilename = NULL; /* -outfile applies to just one input file */
  244. continue; /* ignore this name if previously processed */
  245. }
  246. break; /* else done parsing switches */
  247. }
  248. arg++; /* advance past switch marker character */
  249. if (keymatch(arg, "arithmetic", 1)) {
  250. /* Use arithmetic coding. */
  251. #ifdef C_ARITH_CODING_SUPPORTED
  252. cinfo->arith_code = TRUE;
  253. #else
  254. fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
  255. progname);
  256. exit(EXIT_FAILURE);
  257. #endif
  258. } else if (keymatch(arg, "baseline", 2)) {
  259. /* Force baseline-compatible output (8-bit quantizer values). */
  260. force_baseline = TRUE;
  261. } else if (keymatch(arg, "block", 2)) {
  262. /* Set DCT block size. */
  263. #if defined DCT_SCALING_SUPPORTED && JPEG_LIB_VERSION_MAJOR >= 8 && \
  264. (JPEG_LIB_VERSION_MAJOR > 8 || JPEG_LIB_VERSION_MINOR >= 3)
  265. int val;
  266. if (++argn >= argc) /* advance to next argument */
  267. usage();
  268. if (sscanf(argv[argn], "%d", &val) != 1)
  269. usage();
  270. if (val < 1 || val > 16)
  271. usage();
  272. cinfo->block_size = val;
  273. #else
  274. fprintf(stderr, "%s: sorry, block size setting not supported\n",
  275. progname);
  276. exit(EXIT_FAILURE);
  277. #endif
  278. } else if (keymatch(arg, "dct", 2)) {
  279. /* Select DCT algorithm. */
  280. if (++argn >= argc) /* advance to next argument */
  281. usage();
  282. if (keymatch(argv[argn], "int", 1)) {
  283. cinfo->dct_method = JDCT_ISLOW;
  284. } else if (keymatch(argv[argn], "fast", 2)) {
  285. cinfo->dct_method = JDCT_IFAST;
  286. } else if (keymatch(argv[argn], "float", 2)) {
  287. cinfo->dct_method = JDCT_FLOAT;
  288. } else
  289. usage();
  290. } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
  291. /* Enable debug printouts. */
  292. /* On first -d, print version identification */
  293. static boolean printed_version = FALSE;
  294. if (! printed_version) {
  295. fprintf(stderr, "Independent JPEG Group's CJPEG, version %s\n%s\n",
  296. JVERSION, JCOPYRIGHT);
  297. printed_version = TRUE;
  298. }
  299. cinfo->err->trace_level++;
  300. } else if (keymatch(arg, "grayscale", 2) || 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) || keymatch(arg, "rgb1", 4)) {
  304. /* Force an RGB JPEG file to be generated. */
  305. #if JPEG_LIB_VERSION_MAJOR >= 9
  306. /* Note: Entropy table assignment in jpeg_set_colorspace depends
  307. * on color_transform.
  308. */
  309. cinfo->color_transform = arg[3] ? JCT_SUBTRACT_GREEN : JCT_NONE;
  310. #endif
  311. jpeg_set_colorspace(cinfo, JCS_RGB);
  312. } else if (keymatch(arg, "bgycc", 5)) {
  313. /* Force a big gamut YCC JPEG file to be generated. */
  314. #if JPEG_LIB_VERSION_MAJOR >= 9 && \
  315. (JPEG_LIB_VERSION_MAJOR > 9 || JPEG_LIB_VERSION_MINOR >= 1)
  316. jpeg_set_colorspace(cinfo, JCS_BG_YCC);
  317. #else
  318. fprintf(stderr, "%s: sorry, BG_YCC colorspace not supported\n",
  319. progname);
  320. exit(EXIT_FAILURE);
  321. #endif
  322. } else if (keymatch(arg, "maxmemory", 3)) {
  323. /* Maximum memory in Kb (or Mb with 'm'). */
  324. long lval;
  325. char ch = 'x';
  326. if (++argn >= argc) /* advance to next argument */
  327. usage();
  328. if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
  329. usage();
  330. if (ch == 'm' || ch == 'M')
  331. lval *= 1000L;
  332. cinfo->mem->max_memory_to_use = lval * 1000L;
  333. } else if (keymatch(arg, "nosmooth", 3)) {
  334. /* Suppress fancy downsampling. */
  335. cinfo->do_fancy_downsampling = FALSE;
  336. } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
  337. /* Enable entropy parm optimization. */
  338. #ifdef ENTROPY_OPT_SUPPORTED
  339. cinfo->optimize_coding = TRUE;
  340. #else
  341. fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
  342. progname);
  343. exit(EXIT_FAILURE);
  344. #endif
  345. } else if (keymatch(arg, "outfile", 4)) {
  346. /* Set output file name. */
  347. if (++argn >= argc) /* advance to next argument */
  348. usage();
  349. outfilename = argv[argn]; /* save it away for later use */
  350. } else if (keymatch(arg, "progressive", 1)) {
  351. /* Select simple progressive mode. */
  352. #ifdef C_PROGRESSIVE_SUPPORTED
  353. simple_progressive = TRUE;
  354. /* We must postpone execution until num_components is known. */
  355. #else
  356. fprintf(stderr, "%s: sorry, progressive output was not compiled\n",
  357. progname);
  358. exit(EXIT_FAILURE);
  359. #endif
  360. } else if (keymatch(arg, "quality", 1)) {
  361. /* Quality ratings (quantization table scaling factors). */
  362. if (++argn >= argc) /* advance to next argument */
  363. usage();
  364. qualityarg = argv[argn];
  365. } else if (keymatch(arg, "qslots", 2)) {
  366. /* Quantization table slot numbers. */
  367. if (++argn >= argc) /* advance to next argument */
  368. usage();
  369. qslotsarg = argv[argn];
  370. /* Must delay setting qslots until after we have processed any
  371. * colorspace-determining switches, since jpeg_set_colorspace sets
  372. * default quant table numbers.
  373. */
  374. } else if (keymatch(arg, "qtables", 2)) {
  375. /* Quantization tables fetched from file. */
  376. if (++argn >= argc) /* advance to next argument */
  377. usage();
  378. qtablefile = argv[argn];
  379. /* We postpone actually reading the file in case -quality comes later. */
  380. } else if (keymatch(arg, "restart", 1)) {
  381. /* Restart interval in MCU rows (or in MCUs with 'b'). */
  382. long lval;
  383. char ch = 'x';
  384. if (++argn >= argc) /* advance to next argument */
  385. usage();
  386. if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
  387. usage();
  388. if (lval < 0 || lval > 65535L)
  389. usage();
  390. if (ch == 'b' || ch == 'B') {
  391. cinfo->restart_interval = (unsigned int) lval;
  392. cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
  393. } else {
  394. cinfo->restart_in_rows = (int) lval;
  395. /* restart_interval will be computed during startup */
  396. }
  397. } else if (keymatch(arg, "sample", 2)) {
  398. /* Set sampling factors. */
  399. if (++argn >= argc) /* advance to next argument */
  400. usage();
  401. samplearg = argv[argn];
  402. /* Must delay setting sample factors until after we have processed any
  403. * colorspace-determining switches, since jpeg_set_colorspace sets
  404. * default sampling factors.
  405. */
  406. } else if (keymatch(arg, "scale", 4)) {
  407. /* Scale the image by a fraction M/N. */
  408. if (++argn >= argc) /* advance to next argument */
  409. usage();
  410. if (sscanf(argv[argn], "%d/%d",
  411. &cinfo->scale_num, &cinfo->scale_denom) != 2)
  412. usage();
  413. } else if (keymatch(arg, "scans", 4)) {
  414. /* Set scan script. */
  415. #ifdef C_MULTISCAN_FILES_SUPPORTED
  416. if (++argn >= argc) /* advance to next argument */
  417. usage();
  418. scansarg = argv[argn];
  419. /* We must postpone reading the file in case -progressive appears. */
  420. #else
  421. fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",
  422. progname);
  423. exit(EXIT_FAILURE);
  424. #endif
  425. } else if (keymatch(arg, "smooth", 2)) {
  426. /* Set input smoothing factor. */
  427. int val;
  428. if (++argn >= argc) /* advance to next argument */
  429. usage();
  430. if (sscanf(argv[argn], "%d", &val) != 1)
  431. usage();
  432. if (val < 0 || val > 100)
  433. usage();
  434. cinfo->smoothing_factor = val;
  435. } else if (keymatch(arg, "targa", 1)) {
  436. /* Input file is Targa format. */
  437. is_targa = TRUE;
  438. } else {
  439. usage(); /* bogus switch */
  440. }
  441. }
  442. /* Post-switch-scanning cleanup */
  443. if (for_real) {
  444. /* Set quantization tables for selected quality. */
  445. /* Some or all may be overridden if -qtables is present. */
  446. if (qualityarg != NULL) /* process -quality if it was present */
  447. if (! set_quality_ratings(cinfo, qualityarg, force_baseline))
  448. usage();
  449. if (qtablefile != NULL) /* process -qtables if it was present */
  450. if (! read_quant_tables(cinfo, qtablefile, force_baseline))
  451. usage();
  452. if (qslotsarg != NULL) /* process -qslots if it was present */
  453. if (! set_quant_slots(cinfo, qslotsarg))
  454. usage();
  455. if (samplearg != NULL) /* process -sample if it was present */
  456. if (! set_sample_factors(cinfo, samplearg))
  457. usage();
  458. #ifdef C_PROGRESSIVE_SUPPORTED
  459. if (simple_progressive) /* process -progressive; -scans can override */
  460. jpeg_simple_progression(cinfo);
  461. #endif
  462. #ifdef C_MULTISCAN_FILES_SUPPORTED
  463. if (scansarg != NULL) /* process -scans if it was present */
  464. if (! read_scan_script(cinfo, scansarg))
  465. usage();
  466. #endif
  467. }
  468. return argn; /* return index of next arg (file name) */
  469. }
  470. /*
  471. * Check for overwrite of an existing file; clear it with user
  472. */
  473. #ifndef NO_OVERWRITE_CHECK
  474. LOCAL(boolean)
  475. is_write_ok (char * outfname)
  476. {
  477. FILE * ofile;
  478. int ch;
  479. ofile = fopen(outfname, READ_BINARY);
  480. if (ofile == NULL)
  481. return TRUE; /* not present */
  482. fclose(ofile); /* oops, it is present */
  483. for (;;) {
  484. fprintf(stderr, "%s already exists, overwrite it? [y/n] ",
  485. outfname);
  486. fflush(stderr);
  487. ch = getc(stdin);
  488. if (ch != '\n') /* flush rest of line */
  489. while (getc(stdin) != '\n')
  490. /* nothing */;
  491. switch (ch) {
  492. case 'Y':
  493. case 'y':
  494. return TRUE;
  495. case 'N':
  496. case 'n':
  497. return FALSE;
  498. /* otherwise, ask again */
  499. }
  500. }
  501. }
  502. #endif
  503. /*
  504. * Process a single input file name, and return its index in argv[].
  505. * File names at or to left of old_file_index have been processed already.
  506. */
  507. LOCAL(int)
  508. process_one_file (int argc, char **argv, int old_file_index)
  509. {
  510. struct jpeg_compress_struct cinfo;
  511. struct jpeg_error_mgr jerr;
  512. char *infilename;
  513. char workfilename[PATH_MAX];
  514. #ifdef PROGRESS_REPORT
  515. struct cdjpeg_progress_mgr progress;
  516. #endif
  517. int file_index;
  518. cjpeg_source_ptr src_mgr;
  519. FILE * input_file = NULL;
  520. FILE * output_file = NULL;
  521. JDIMENSION num_scanlines;
  522. /* Initialize the JPEG compression object with default error handling. */
  523. cinfo.err = jpeg_std_error(&jerr);
  524. jpeg_create_compress(&cinfo);
  525. /* Add some application-specific error messages (from cderror.h) */
  526. jerr.addon_message_table = cdjpeg_message_table;
  527. jerr.first_addon_message = JMSG_FIRSTADDONCODE;
  528. jerr.last_addon_message = JMSG_LASTADDONCODE;
  529. /* Now safe to enable signal catcher. */
  530. #ifdef NEED_SIGNAL_CATCHER
  531. enable_signal_catcher((j_common_ptr) &cinfo);
  532. #endif
  533. /* Initialize JPEG parameters.
  534. * Much of this may be overridden later.
  535. * In particular, we don't yet know the input file's color space,
  536. * but we need to provide some value for jpeg_set_defaults() to work.
  537. */
  538. cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
  539. jpeg_set_defaults(&cinfo);
  540. /* Scan command line to find next file name.
  541. * It is convenient to use just one switch-parsing routine, but the switch
  542. * values read here are ignored; we will rescan the switches after opening
  543. * the input file.
  544. */
  545. file_index = parse_switches(&cinfo, argc, argv, old_file_index, FALSE);
  546. if (file_index >= argc) {
  547. fprintf(stderr, "%s: missing input file name\n", progname);
  548. usage();
  549. }
  550. /* Open the input file. */
  551. infilename = argv[file_index];
  552. if ((input_file = fopen(infilename, READ_BINARY)) == NULL) {
  553. fprintf(stderr, "%s: can't open %s\n", progname, infilename);
  554. goto fail;
  555. }
  556. #ifdef PROGRESS_REPORT
  557. start_progress_monitor((j_common_ptr) &cinfo, &progress);
  558. #endif
  559. /* Figure out the input file format, and set up to read it. */
  560. src_mgr = select_file_type(&cinfo, input_file);
  561. src_mgr->input_file = input_file;
  562. /* Read the input file header to obtain file size & colorspace. */
  563. (*src_mgr->start_input) (&cinfo, src_mgr);
  564. /* Now that we know input colorspace, fix colorspace-dependent defaults */
  565. jpeg_default_colorspace(&cinfo);
  566. /* Adjust default compression parameters by re-parsing the options */
  567. file_index = parse_switches(&cinfo, argc, argv, old_file_index, TRUE);
  568. /* If user didn't supply -outfile switch, select output file name. */
  569. if (outfilename == NULL) {
  570. int i;
  571. outfilename = workfilename;
  572. /* Make outfilename be infilename with .jpg substituted for extension */
  573. strcpy(outfilename, infilename);
  574. for (i = (int)strlen(outfilename)-1; i >= 0; i--) {
  575. switch (outfilename[i]) {
  576. case ':':
  577. case '/':
  578. case '\\':
  579. i = 0; /* stop scanning */
  580. break;
  581. case '.':
  582. outfilename[i] = '\0'; /* lop off existing extension */
  583. i = 0; /* stop scanning */
  584. break;
  585. default:
  586. break; /* keep scanning */
  587. }
  588. }
  589. strcat(outfilename, ".jpg");
  590. }
  591. fprintf(stderr, "Compressing %s => %s\n", infilename, outfilename);
  592. #ifndef NO_OVERWRITE_CHECK
  593. if (! is_write_ok(outfilename))
  594. goto fail;
  595. #endif
  596. /* Open the output file. */
  597. if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
  598. fprintf(stderr, "%s: can't create %s\n", progname, outfilename);
  599. goto fail;
  600. }
  601. /* Specify data destination for compression */
  602. jpeg_stdio_dest(&cinfo, output_file);
  603. /* Start compressor */
  604. jpeg_start_compress(&cinfo, TRUE);
  605. /* Process data */
  606. while (cinfo.next_scanline < cinfo.image_height) {
  607. num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
  608. (void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
  609. }
  610. /* Finish compression and release memory */
  611. (*src_mgr->finish_input) (&cinfo, src_mgr);
  612. jpeg_finish_compress(&cinfo);
  613. /* Clean up and exit */
  614. fail:
  615. jpeg_destroy_compress(&cinfo);
  616. if (input_file != NULL) fclose(input_file);
  617. if (output_file != NULL) fclose(output_file);
  618. #ifdef PROGRESS_REPORT
  619. end_progress_monitor((j_common_ptr) &cinfo);
  620. #endif
  621. /* Disable signal catcher. */
  622. #ifdef NEED_SIGNAL_CATCHER
  623. enable_signal_catcher((j_common_ptr) NULL);
  624. #endif
  625. return file_index;
  626. }
  627. /*
  628. * The main program.
  629. */
  630. int
  631. main (int argc, char **argv)
  632. {
  633. int file_index;
  634. /* On Mac, fetch a command line. */
  635. #ifdef USE_CCOMMAND
  636. argc = ccommand(&argv);
  637. #endif
  638. #ifdef MSDOS
  639. progname = "cjpeg"; /* DOS tends to be too verbose about argv[0] */
  640. #else
  641. progname = argv[0];
  642. if (progname == NULL || progname[0] == 0)
  643. progname = "cjpeg"; /* in case C library doesn't provide it */
  644. #endif
  645. /* The default maxmem must be computed only once at program startup,
  646. * since releasing memory with free() won't give it back to the OS.
  647. */
  648. #ifdef FREE_MEM_ESTIMATE
  649. default_maxmem = FREE_MEM_ESTIMATE;
  650. #else
  651. default_maxmem = 0;
  652. #endif
  653. /* Scan command line, parse switches and locate input file names */
  654. if (argc < 2)
  655. usage(); /* nothing on the command line?? */
  656. file_index = 0;
  657. while (file_index < argc-1)
  658. file_index = process_one_file(argc, argv, file_index);
  659. /* All done. */
  660. exit(EXIT_SUCCESS);
  661. return 0; /* suppress no-return-value warnings */
  662. }