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