Check for SYS/GL during library init. Reason is that
[AROS.git] / workbench / libs / jpeg / cjpeg.c
blobd05cdd0a941f52c22002e5613fb1adb3c54ebf34
1 /*
2 * cjpeg.c
4 * Copyright (C) 1991-1998, Thomas G. Lane.
5 * Modified 2003-2013 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.
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.
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.
27 #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
28 #include "jversion.h" /* for version message */
30 #ifdef USE_CCOMMAND /* command-line reader for Macintosh */
31 #ifdef __MWERKS__
32 #include <SIOUX.h> /* Metrowerks needs this */
33 #include <console.h> /* ... and this */
34 #endif
35 #ifdef THINK_C
36 #include <console.h> /* Think declares it here */
37 #endif
38 #endif
41 /* Create the add-on message string table. */
43 #define JMESSAGE(code,string) string ,
45 static const char * const cdjpeg_message_table[] = {
46 #include "cderror.h"
47 NULL
52 * This routine determines what format the input file is,
53 * and selects the appropriate input-reading module.
55 * To determine which family of input formats the file belongs to,
56 * we may look only at the first byte of the file, since C does not
57 * guarantee that more than one character can be pushed back with ungetc.
58 * Looking at additional bytes would require one of these approaches:
59 * 1) assume we can fseek() the input file (fails for piped input);
60 * 2) assume we can push back more than one character (works in
61 * some C implementations, but unportable);
62 * 3) provide our own buffering (breaks input readers that want to use
63 * stdio directly, such as the RLE library);
64 * or 4) don't put back the data, and modify the input_init methods to assume
65 * they start reading after the start of file (also breaks RLE library).
66 * #1 is attractive for MS-DOS but is untenable on Unix.
68 * The most portable solution for file types that can't be identified by their
69 * first byte is to make the user tell us what they are. This is also the
70 * only approach for "raw" file types that contain only arbitrary values.
71 * We presently apply this method for Targa files. Most of the time Targa
72 * files start with 0x00, so we recognize that case. Potentially, however,
73 * a Targa file could start with any byte value (byte 0 is the length of the
74 * seldom-used ID field), so we provide a switch to force Targa input mode.
77 static boolean is_targa; /* records user -targa switch */
80 LOCAL(cjpeg_source_ptr)
81 select_file_type (j_compress_ptr cinfo, FILE * infile)
83 int c;
85 if (is_targa) {
86 #ifdef TARGA_SUPPORTED
87 return jinit_read_targa(cinfo);
88 #else
89 ERREXIT(cinfo, JERR_TGA_NOTCOMP);
90 #endif
93 if ((c = getc(infile)) == EOF)
94 ERREXIT(cinfo, JERR_INPUT_EMPTY);
95 if (ungetc(c, infile) == EOF)
96 ERREXIT(cinfo, JERR_UNGETC_FAILED);
98 switch (c) {
99 #ifdef BMP_SUPPORTED
100 case 'B':
101 return jinit_read_bmp(cinfo);
102 #endif
103 #ifdef GIF_SUPPORTED
104 case 'G':
105 return jinit_read_gif(cinfo);
106 #endif
107 #ifdef PPM_SUPPORTED
108 case 'P':
109 return jinit_read_ppm(cinfo);
110 #endif
111 #ifdef RLE_SUPPORTED
112 case 'R':
113 return jinit_read_rle(cinfo);
114 #endif
115 #ifdef TARGA_SUPPORTED
116 case 0x00:
117 return jinit_read_targa(cinfo);
118 #endif
119 default:
120 ERREXIT(cinfo, JERR_UNKNOWN_FORMAT);
121 break;
124 return NULL; /* suppress compiler warnings */
129 * Argument-parsing code.
130 * The switch parser is designed to be useful with DOS-style command line
131 * syntax, ie, intermixed switches and file names, where only the switches
132 * to the left of a given file name affect processing of that file.
133 * The main program in this file doesn't actually use this capability...
137 static const char * progname; /* program name for error messages */
138 static char * outfilename; /* for -outfile switch */
141 LOCAL(void)
142 usage (void)
143 /* complain about bad command line */
145 fprintf(stderr, "usage: %s [switches] ", progname);
146 #ifdef TWO_FILE_COMMANDLINE
147 fprintf(stderr, "inputfile outputfile\n");
148 #else
149 fprintf(stderr, "[inputfile]\n");
150 #endif
152 fprintf(stderr, "Switches (names may be abbreviated):\n");
153 fprintf(stderr, " -quality N[,...] Compression quality (0..100; 5-95 is useful range)\n");
154 fprintf(stderr, " -grayscale Create monochrome JPEG file\n");
155 fprintf(stderr, " -rgb Create RGB JPEG file\n");
156 #ifdef ENTROPY_OPT_SUPPORTED
157 fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression)\n");
158 #endif
159 #ifdef C_PROGRESSIVE_SUPPORTED
160 fprintf(stderr, " -progressive Create progressive JPEG file\n");
161 #endif
162 #ifdef DCT_SCALING_SUPPORTED
163 fprintf(stderr, " -scale M/N Scale image by fraction M/N, eg, 1/2\n");
164 #endif
165 #ifdef TARGA_SUPPORTED
166 fprintf(stderr, " -targa Input file is Targa format (usually not needed)\n");
167 #endif
168 fprintf(stderr, "Switches for advanced users:\n");
169 #ifdef C_ARITH_CODING_SUPPORTED
170 fprintf(stderr, " -arithmetic Use arithmetic coding\n");
171 #endif
172 #ifdef DCT_SCALING_SUPPORTED
173 fprintf(stderr, " -block N DCT block size (1..16; default is 8)\n");
174 #endif
175 #if JPEG_LIB_VERSION_MAJOR >= 9
176 fprintf(stderr, " -rgb1 Create RGB JPEG file with reversible color transform\n");
177 #endif
178 #ifdef DCT_ISLOW_SUPPORTED
179 fprintf(stderr, " -dct int Use integer DCT method%s\n",
180 (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
181 #endif
182 #ifdef DCT_IFAST_SUPPORTED
183 fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",
184 (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
185 #endif
186 #ifdef DCT_FLOAT_SUPPORTED
187 fprintf(stderr, " -dct float Use floating-point DCT method%s\n",
188 (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
189 #endif
190 fprintf(stderr, " -nosmooth Don't use high-quality downsampling\n");
191 fprintf(stderr, " -restart N Set restart interval in rows, or in blocks with B\n");
192 #ifdef INPUT_SMOOTHING_SUPPORTED
193 fprintf(stderr, " -smooth N Smooth dithered input (N=1..100 is strength)\n");
194 #endif
195 fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
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);
210 LOCAL(int)
211 parse_switches (j_compress_ptr cinfo, int argc, char **argv,
212 int last_file_arg_seen, boolean for_real)
213 /* Parse optional switches.
214 * Returns argv[] index of first file-name argument (== argc if none).
215 * Any file names with indexes <= last_file_arg_seen are ignored;
216 * they have presumably been processed in a previous iteration.
217 * (Pass 0 for last_file_arg_seen on the first or only iteration.)
218 * for_real is FALSE on the first (dummy) pass; we may skip any expensive
219 * processing.
222 int argn;
223 char * arg;
224 boolean force_baseline;
225 boolean simple_progressive;
226 char * qualityarg = NULL; /* saves -quality parm if any */
227 char * qtablefile = NULL; /* saves -qtables filename if any */
228 char * qslotsarg = NULL; /* saves -qslots parm if any */
229 char * samplearg = NULL; /* saves -sample parm if any */
230 char * scansarg = NULL; /* saves -scans parm if any */
232 /* Set up default JPEG parameters. */
234 force_baseline = FALSE; /* by default, allow 16-bit quantizers */
235 simple_progressive = FALSE;
236 is_targa = FALSE;
237 outfilename = NULL;
238 cinfo->err->trace_level = 0;
240 /* Scan command line options, adjust parameters */
242 for (argn = 1; argn < argc; argn++) {
243 arg = argv[argn];
244 if (*arg != '-') {
245 /* Not a switch, must be a file name argument */
246 if (argn <= last_file_arg_seen) {
247 outfilename = NULL; /* -outfile applies to just one input file */
248 continue; /* ignore this name if previously processed */
250 break; /* else done parsing switches */
252 arg++; /* advance past switch marker character */
254 if (keymatch(arg, "arithmetic", 1)) {
255 /* Use arithmetic coding. */
256 #ifdef C_ARITH_CODING_SUPPORTED
257 cinfo->arith_code = TRUE;
258 #else
259 fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
260 progname);
261 exit(EXIT_FAILURE);
262 #endif
264 } else if (keymatch(arg, "baseline", 2)) {
265 /* Force baseline-compatible output (8-bit quantizer values). */
266 force_baseline = TRUE;
268 } else if (keymatch(arg, "block", 2)) {
269 /* Set DCT block size. */
270 #if defined DCT_SCALING_SUPPORTED && JPEG_LIB_VERSION_MAJOR >= 8 && \
271 (JPEG_LIB_VERSION_MAJOR > 8 || JPEG_LIB_VERSION_MINOR >= 3)
272 int val;
274 if (++argn >= argc) /* advance to next argument */
275 usage();
276 if (sscanf(argv[argn], "%d", &val) != 1)
277 usage();
278 if (val < 1 || val > 16)
279 usage();
280 cinfo->block_size = val;
281 #else
282 fprintf(stderr, "%s: sorry, block size setting not supported\n",
283 progname);
284 exit(EXIT_FAILURE);
285 #endif
287 } else if (keymatch(arg, "dct", 2)) {
288 /* Select DCT algorithm. */
289 if (++argn >= argc) /* advance to next argument */
290 usage();
291 if (keymatch(argv[argn], "int", 1)) {
292 cinfo->dct_method = JDCT_ISLOW;
293 } else if (keymatch(argv[argn], "fast", 2)) {
294 cinfo->dct_method = JDCT_IFAST;
295 } else if (keymatch(argv[argn], "float", 2)) {
296 cinfo->dct_method = JDCT_FLOAT;
297 } else
298 usage();
300 } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
301 /* Enable debug printouts. */
302 /* On first -d, print version identification */
303 static boolean printed_version = FALSE;
305 if (! printed_version) {
306 fprintf(stderr, "Independent JPEG Group's CJPEG, version %s\n%s\n",
307 JVERSION, JCOPYRIGHT);
308 printed_version = TRUE;
310 cinfo->err->trace_level++;
312 } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
313 /* Force a monochrome JPEG file to be generated. */
314 jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
316 } else if (keymatch(arg, "rgb", 3) || keymatch(arg, "rgb1", 4)) {
317 /* Force an RGB JPEG file to be generated. */
318 #if JPEG_LIB_VERSION_MAJOR >= 9
319 /* Note: Entropy table assignment in jpeg_set_colorspace depends
320 * on color_transform.
322 cinfo->color_transform = arg[3] ? JCT_SUBTRACT_GREEN : JCT_NONE;
323 #endif
324 jpeg_set_colorspace(cinfo, JCS_RGB);
326 } else if (keymatch(arg, "maxmemory", 3)) {
327 /* Maximum memory in Kb (or Mb with 'm'). */
328 long lval;
329 char ch = 'x';
331 if (++argn >= argc) /* advance to next argument */
332 usage();
333 if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
334 usage();
335 if (ch == 'm' || ch == 'M')
336 lval *= 1000L;
337 cinfo->mem->max_memory_to_use = lval * 1000L;
339 } else if (keymatch(arg, "nosmooth", 3)) {
340 /* Suppress fancy downsampling. */
341 cinfo->do_fancy_downsampling = FALSE;
343 } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
344 /* Enable entropy parm optimization. */
345 #ifdef ENTROPY_OPT_SUPPORTED
346 cinfo->optimize_coding = TRUE;
347 #else
348 fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
349 progname);
350 exit(EXIT_FAILURE);
351 #endif
353 } else if (keymatch(arg, "outfile", 4)) {
354 /* Set output file name. */
355 if (++argn >= argc) /* advance to next argument */
356 usage();
357 outfilename = argv[argn]; /* save it away for later use */
359 } else if (keymatch(arg, "progressive", 1)) {
360 /* Select simple progressive mode. */
361 #ifdef C_PROGRESSIVE_SUPPORTED
362 simple_progressive = TRUE;
363 /* We must postpone execution until num_components is known. */
364 #else
365 fprintf(stderr, "%s: sorry, progressive output was not compiled\n",
366 progname);
367 exit(EXIT_FAILURE);
368 #endif
370 } else if (keymatch(arg, "quality", 1)) {
371 /* Quality ratings (quantization table scaling factors). */
372 if (++argn >= argc) /* advance to next argument */
373 usage();
374 qualityarg = argv[argn];
376 } else if (keymatch(arg, "qslots", 2)) {
377 /* Quantization table slot numbers. */
378 if (++argn >= argc) /* advance to next argument */
379 usage();
380 qslotsarg = argv[argn];
381 /* Must delay setting qslots until after we have processed any
382 * colorspace-determining switches, since jpeg_set_colorspace sets
383 * default quant table numbers.
386 } else if (keymatch(arg, "qtables", 2)) {
387 /* Quantization tables fetched from file. */
388 if (++argn >= argc) /* advance to next argument */
389 usage();
390 qtablefile = argv[argn];
391 /* We postpone actually reading the file in case -quality comes later. */
393 } else if (keymatch(arg, "restart", 1)) {
394 /* Restart interval in MCU rows (or in MCUs with 'b'). */
395 long lval;
396 char ch = 'x';
398 if (++argn >= argc) /* advance to next argument */
399 usage();
400 if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
401 usage();
402 if (lval < 0 || lval > 65535L)
403 usage();
404 if (ch == 'b' || ch == 'B') {
405 cinfo->restart_interval = (unsigned int) lval;
406 cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
407 } else {
408 cinfo->restart_in_rows = (int) lval;
409 /* restart_interval will be computed during startup */
412 } else if (keymatch(arg, "sample", 2)) {
413 /* Set sampling factors. */
414 if (++argn >= argc) /* advance to next argument */
415 usage();
416 samplearg = argv[argn];
417 /* Must delay setting sample factors until after we have processed any
418 * colorspace-determining switches, since jpeg_set_colorspace sets
419 * default sampling factors.
422 } else if (keymatch(arg, "scale", 4)) {
423 /* Scale the image by a fraction M/N. */
424 if (++argn >= argc) /* advance to next argument */
425 usage();
426 if (sscanf(argv[argn], "%u/%u",
427 &cinfo->scale_num, &cinfo->scale_denom) != 2)
428 usage();
430 } else if (keymatch(arg, "scans", 4)) {
431 /* Set scan script. */
432 #ifdef C_MULTISCAN_FILES_SUPPORTED
433 if (++argn >= argc) /* advance to next argument */
434 usage();
435 scansarg = argv[argn];
436 /* We must postpone reading the file in case -progressive appears. */
437 #else
438 fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",
439 progname);
440 exit(EXIT_FAILURE);
441 #endif
443 } else if (keymatch(arg, "smooth", 2)) {
444 /* Set input smoothing factor. */
445 int val;
447 if (++argn >= argc) /* advance to next argument */
448 usage();
449 if (sscanf(argv[argn], "%d", &val) != 1)
450 usage();
451 if (val < 0 || val > 100)
452 usage();
453 cinfo->smoothing_factor = val;
455 } else if (keymatch(arg, "targa", 1)) {
456 /* Input file is Targa format. */
457 is_targa = TRUE;
459 } else {
460 usage(); /* bogus switch */
464 /* Post-switch-scanning cleanup */
466 if (for_real) {
468 /* Set quantization tables for selected quality. */
469 /* Some or all may be overridden if -qtables is present. */
470 if (qualityarg != NULL) /* process -quality if it was present */
471 if (! set_quality_ratings(cinfo, qualityarg, force_baseline))
472 usage();
474 if (qtablefile != NULL) /* process -qtables if it was present */
475 if (! read_quant_tables(cinfo, qtablefile, force_baseline))
476 usage();
478 if (qslotsarg != NULL) /* process -qslots if it was present */
479 if (! set_quant_slots(cinfo, qslotsarg))
480 usage();
482 if (samplearg != NULL) /* process -sample if it was present */
483 if (! set_sample_factors(cinfo, samplearg))
484 usage();
486 #ifdef C_PROGRESSIVE_SUPPORTED
487 if (simple_progressive) /* process -progressive; -scans can override */
488 jpeg_simple_progression(cinfo);
489 #endif
491 #ifdef C_MULTISCAN_FILES_SUPPORTED
492 if (scansarg != NULL) /* process -scans if it was present */
493 if (! read_scan_script(cinfo, scansarg))
494 usage();
495 #endif
498 return argn; /* return index of next arg (file name) */
503 * The main program.
507 main (int argc, char **argv)
509 struct jpeg_compress_struct cinfo;
510 struct jpeg_error_mgr jerr;
511 #ifdef PROGRESS_REPORT
512 struct cdjpeg_progress_mgr progress;
513 #endif
514 int file_index;
515 cjpeg_source_ptr src_mgr;
516 FILE * input_file;
517 FILE * output_file;
518 JDIMENSION num_scanlines;
520 /* On Mac, fetch a command line. */
521 #ifdef USE_CCOMMAND
522 argc = ccommand(&argv);
523 #endif
525 progname = argv[0];
526 if (progname == NULL || progname[0] == 0)
527 progname = "cjpeg"; /* in case C library doesn't provide it */
529 /* Initialize the JPEG compression object with default error handling. */
530 cinfo.err = jpeg_std_error(&jerr);
531 jpeg_create_compress(&cinfo);
532 /* Add some application-specific error messages (from cderror.h) */
533 jerr.addon_message_table = cdjpeg_message_table;
534 jerr.first_addon_message = JMSG_FIRSTADDONCODE;
535 jerr.last_addon_message = JMSG_LASTADDONCODE;
537 /* Now safe to enable signal catcher. */
538 #ifdef NEED_SIGNAL_CATCHER
539 enable_signal_catcher((j_common_ptr) &cinfo);
540 #endif
542 /* Initialize JPEG parameters.
543 * Much of this may be overridden later.
544 * In particular, we don't yet know the input file's color space,
545 * but we need to provide some value for jpeg_set_defaults() to work.
548 cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
549 jpeg_set_defaults(&cinfo);
551 /* Scan command line to find file names.
552 * It is convenient to use just one switch-parsing routine, but the switch
553 * values read here are ignored; we will rescan the switches after opening
554 * the input file.
557 file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
559 #ifdef TWO_FILE_COMMANDLINE
560 /* Must have either -outfile switch or explicit output file name */
561 if (outfilename == NULL) {
562 if (file_index != argc-2) {
563 fprintf(stderr, "%s: must name one input and one output file\n",
564 progname);
565 usage();
567 outfilename = argv[file_index+1];
568 } else {
569 if (file_index != argc-1) {
570 fprintf(stderr, "%s: must name one input and one output file\n",
571 progname);
572 usage();
575 #else
576 /* Unix style: expect zero or one file name */
577 if (file_index < argc-1) {
578 fprintf(stderr, "%s: only one input file\n", progname);
579 usage();
581 #endif /* TWO_FILE_COMMANDLINE */
583 /* Open the input file. */
584 if (file_index < argc) {
585 if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
586 fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
587 exit(EXIT_FAILURE);
589 } else {
590 /* default input file is stdin */
591 input_file = read_stdin();
594 /* Open the output file. */
595 if (outfilename != NULL) {
596 if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
597 fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
598 exit(EXIT_FAILURE);
600 } else {
601 /* default output file is stdout */
602 output_file = write_stdout();
605 #ifdef PROGRESS_REPORT
606 start_progress_monitor((j_common_ptr) &cinfo, &progress);
607 #endif
609 /* Figure out the input file format, and set up to read it. */
610 src_mgr = select_file_type(&cinfo, input_file);
611 src_mgr->input_file = input_file;
613 /* Read the input file header to obtain file size & colorspace. */
614 (*src_mgr->start_input) (&cinfo, src_mgr);
616 /* Now that we know input colorspace, fix colorspace-dependent defaults */
617 jpeg_default_colorspace(&cinfo);
619 /* Adjust default compression parameters by re-parsing the options */
620 file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
622 /* Specify data destination for compression */
623 jpeg_stdio_dest(&cinfo, output_file);
625 /* Start compressor */
626 jpeg_start_compress(&cinfo, TRUE);
628 /* Process data */
629 while (cinfo.next_scanline < cinfo.image_height) {
630 num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
631 (void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
634 /* Finish compression and release memory */
635 (*src_mgr->finish_input) (&cinfo, src_mgr);
636 jpeg_finish_compress(&cinfo);
637 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)
643 fclose(output_file);
645 #ifdef PROGRESS_REPORT
646 end_progress_monitor((j_common_ptr) &cinfo);
647 #endif
649 /* All done. */
650 exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
651 return 0; /* suppress no-return-value warnings */