Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/external/source/vncdll/winvnc/libjpeg/cjpeg.c
Views: 11784
/*1* cjpeg.c2*3* Copyright (C) 1991-1998, Thomas G. Lane.4* This file is part of the Independent JPEG Group's software.5* For conditions of distribution and use, see the accompanying README file.6*7* This file contains a command-line user interface for the JPEG compressor.8* It should work on any system with Unix- or MS-DOS-style command lines.9*10* Two different command line styles are permitted, depending on the11* compile-time switch TWO_FILE_COMMANDLINE:12* cjpeg [options] inputfile outputfile13* cjpeg [options] [inputfile]14* In the second style, output is always to standard output, which you'd15* normally redirect to a file or pipe to some other program. Input is16* either from a named file or from standard input (typically redirected).17* The second style is convenient on Unix but is unhelpful on systems that18* don't support pipes. Also, you MUST use the first style if your system19* doesn't do binary I/O to stdin/stdout.20* To simplify script writing, the "-outfile" switch is provided. The syntax21* cjpeg [options] -outfile outputfile inputfile22* works regardless of which command line style is used.23*/2425#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */26#include "jversion.h" /* for version message */2728#ifdef USE_CCOMMAND /* command-line reader for Macintosh */29#ifdef __MWERKS__30#include <SIOUX.h> /* Metrowerks needs this */31#include <console.h> /* ... and this */32#endif33#ifdef THINK_C34#include <console.h> /* Think declares it here */35#endif36#endif373839/* Create the add-on message string table. */4041#define JMESSAGE(code,string) string ,4243static const char * const cdjpeg_message_table[] = {44#include "cderror.h"45NULL46};474849/*50* This routine determines what format the input file is,51* and selects the appropriate input-reading module.52*53* To determine which family of input formats the file belongs to,54* we may look only at the first byte of the file, since C does not55* guarantee that more than one character can be pushed back with ungetc.56* Looking at additional bytes would require one of these approaches:57* 1) assume we can fseek() the input file (fails for piped input);58* 2) assume we can push back more than one character (works in59* some C implementations, but unportable);60* 3) provide our own buffering (breaks input readers that want to use61* stdio directly, such as the RLE library);62* or 4) don't put back the data, and modify the input_init methods to assume63* they start reading after the start of file (also breaks RLE library).64* #1 is attractive for MS-DOS but is untenable on Unix.65*66* The most portable solution for file types that can't be identified by their67* first byte is to make the user tell us what they are. This is also the68* only approach for "raw" file types that contain only arbitrary values.69* We presently apply this method for Targa files. Most of the time Targa70* files start with 0x00, so we recognize that case. Potentially, however,71* a Targa file could start with any byte value (byte 0 is the length of the72* seldom-used ID field), so we provide a switch to force Targa input mode.73*/7475static boolean is_targa; /* records user -targa switch */767778LOCAL(cjpeg_source_ptr)79select_file_type (j_compress_ptr cinfo, FILE * infile)80{81int c;8283if (is_targa) {84#ifdef TARGA_SUPPORTED85return jinit_read_targa(cinfo);86#else87ERREXIT(cinfo, JERR_TGA_NOTCOMP);88#endif89}9091if ((c = getc(infile)) == EOF)92ERREXIT(cinfo, JERR_INPUT_EMPTY);93if (ungetc(c, infile) == EOF)94ERREXIT(cinfo, JERR_UNGETC_FAILED);9596switch (c) {97#ifdef BMP_SUPPORTED98case 'B':99return jinit_read_bmp(cinfo);100#endif101#ifdef GIF_SUPPORTED102case 'G':103return jinit_read_gif(cinfo);104#endif105#ifdef PPM_SUPPORTED106case 'P':107return jinit_read_ppm(cinfo);108#endif109#ifdef RLE_SUPPORTED110case 'R':111return jinit_read_rle(cinfo);112#endif113#ifdef TARGA_SUPPORTED114case 0x00:115return jinit_read_targa(cinfo);116#endif117default:118ERREXIT(cinfo, JERR_UNKNOWN_FORMAT);119break;120}121122return NULL; /* suppress compiler warnings */123}124125126/*127* Argument-parsing code.128* The switch parser is designed to be useful with DOS-style command line129* syntax, ie, intermixed switches and file names, where only the switches130* to the left of a given file name affect processing of that file.131* The main program in this file doesn't actually use this capability...132*/133134135static const char * progname; /* program name for error messages */136static char * outfilename; /* for -outfile switch */137138139LOCAL(void)140usage (void)141/* complain about bad command line */142{143fprintf(stderr, "usage: %s [switches] ", progname);144#ifdef TWO_FILE_COMMANDLINE145fprintf(stderr, "inputfile outputfile\n");146#else147fprintf(stderr, "[inputfile]\n");148#endif149150fprintf(stderr, "Switches (names may be abbreviated):\n");151fprintf(stderr, " -quality N Compression quality (0..100; 5-95 is useful range)\n");152fprintf(stderr, " -grayscale Create monochrome JPEG file\n");153#ifdef ENTROPY_OPT_SUPPORTED154fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression)\n");155#endif156#ifdef C_PROGRESSIVE_SUPPORTED157fprintf(stderr, " -progressive Create progressive JPEG file\n");158#endif159#ifdef TARGA_SUPPORTED160fprintf(stderr, " -targa Input file is Targa format (usually not needed)\n");161#endif162fprintf(stderr, "Switches for advanced users:\n");163#ifdef DCT_ISLOW_SUPPORTED164fprintf(stderr, " -dct int Use integer DCT method%s\n",165(JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));166#endif167#ifdef DCT_IFAST_SUPPORTED168fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",169(JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));170#endif171#ifdef DCT_FLOAT_SUPPORTED172fprintf(stderr, " -dct float Use floating-point DCT method%s\n",173(JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));174#endif175fprintf(stderr, " -restart N Set restart interval in rows, or in blocks with B\n");176#ifdef INPUT_SMOOTHING_SUPPORTED177fprintf(stderr, " -smooth N Smooth dithered input (N=1..100 is strength)\n");178#endif179fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");180fprintf(stderr, " -outfile name Specify name for output file\n");181fprintf(stderr, " -verbose or -debug Emit debug output\n");182fprintf(stderr, "Switches for wizards:\n");183#ifdef C_ARITH_CODING_SUPPORTED184fprintf(stderr, " -arithmetic Use arithmetic coding\n");185#endif186fprintf(stderr, " -baseline Force baseline quantization tables\n");187fprintf(stderr, " -qtables file Use quantization tables given in file\n");188fprintf(stderr, " -qslots N[,...] Set component quantization tables\n");189fprintf(stderr, " -sample HxV[,...] Set component sampling factors\n");190#ifdef C_MULTISCAN_FILES_SUPPORTED191fprintf(stderr, " -scans file Create multi-scan JPEG per script file\n");192#endif193exit(EXIT_FAILURE);194}195196197LOCAL(int)198parse_switches (j_compress_ptr cinfo, int argc, char **argv,199int last_file_arg_seen, boolean for_real)200/* Parse optional switches.201* Returns argv[] index of first file-name argument (== argc if none).202* Any file names with indexes <= last_file_arg_seen are ignored;203* they have presumably been processed in a previous iteration.204* (Pass 0 for last_file_arg_seen on the first or only iteration.)205* for_real is FALSE on the first (dummy) pass; we may skip any expensive206* processing.207*/208{209int argn;210char * arg;211int quality; /* -quality parameter */212int q_scale_factor; /* scaling percentage for -qtables */213boolean force_baseline;214boolean simple_progressive;215char * qtablefile = NULL; /* saves -qtables filename if any */216char * qslotsarg = NULL; /* saves -qslots parm if any */217char * samplearg = NULL; /* saves -sample parm if any */218char * scansarg = NULL; /* saves -scans parm if any */219220/* Set up default JPEG parameters. */221/* Note that default -quality level need not, and does not,222* match the default scaling for an explicit -qtables argument.223*/224quality = 75; /* default -quality value */225q_scale_factor = 100; /* default to no scaling for -qtables */226force_baseline = FALSE; /* by default, allow 16-bit quantizers */227simple_progressive = FALSE;228is_targa = FALSE;229outfilename = NULL;230cinfo->err->trace_level = 0;231232/* Scan command line options, adjust parameters */233234for (argn = 1; argn < argc; argn++) {235arg = argv[argn];236if (*arg != '-') {237/* Not a switch, must be a file name argument */238if (argn <= last_file_arg_seen) {239outfilename = NULL; /* -outfile applies to just one input file */240continue; /* ignore this name if previously processed */241}242break; /* else done parsing switches */243}244arg++; /* advance past switch marker character */245246if (keymatch(arg, "arithmetic", 1)) {247/* Use arithmetic coding. */248#ifdef C_ARITH_CODING_SUPPORTED249cinfo->arith_code = TRUE;250#else251fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",252progname);253exit(EXIT_FAILURE);254#endif255256} else if (keymatch(arg, "baseline", 1)) {257/* Force baseline-compatible output (8-bit quantizer values). */258force_baseline = TRUE;259260} else if (keymatch(arg, "dct", 2)) {261/* Select DCT algorithm. */262if (++argn >= argc) /* advance to next argument */263usage();264if (keymatch(argv[argn], "int", 1)) {265cinfo->dct_method = JDCT_ISLOW;266} else if (keymatch(argv[argn], "fast", 2)) {267cinfo->dct_method = JDCT_IFAST;268} else if (keymatch(argv[argn], "float", 2)) {269cinfo->dct_method = JDCT_FLOAT;270} else271usage();272273} else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {274/* Enable debug printouts. */275/* On first -d, print version identification */276static boolean printed_version = FALSE;277278if (! printed_version) {279fprintf(stderr, "Independent JPEG Group's CJPEG, version %s\n%s\n",280JVERSION, JCOPYRIGHT);281printed_version = TRUE;282}283cinfo->err->trace_level++;284285} else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {286/* Force a monochrome JPEG file to be generated. */287jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);288289} else if (keymatch(arg, "maxmemory", 3)) {290/* Maximum memory in Kb (or Mb with 'm'). */291long lval;292char ch = 'x';293294if (++argn >= argc) /* advance to next argument */295usage();296if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)297usage();298if (ch == 'm' || ch == 'M')299lval *= 1000L;300cinfo->mem->max_memory_to_use = lval * 1000L;301302} else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {303/* Enable entropy parm optimization. */304#ifdef ENTROPY_OPT_SUPPORTED305cinfo->optimize_coding = TRUE;306#else307fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",308progname);309exit(EXIT_FAILURE);310#endif311312} else if (keymatch(arg, "outfile", 4)) {313/* Set output file name. */314if (++argn >= argc) /* advance to next argument */315usage();316outfilename = argv[argn]; /* save it away for later use */317318} else if (keymatch(arg, "progressive", 1)) {319/* Select simple progressive mode. */320#ifdef C_PROGRESSIVE_SUPPORTED321simple_progressive = TRUE;322/* We must postpone execution until num_components is known. */323#else324fprintf(stderr, "%s: sorry, progressive output was not compiled\n",325progname);326exit(EXIT_FAILURE);327#endif328329} else if (keymatch(arg, "quality", 1)) {330/* Quality factor (quantization table scaling factor). */331if (++argn >= argc) /* advance to next argument */332usage();333if (sscanf(argv[argn], "%d", &quality) != 1)334usage();335/* Change scale factor in case -qtables is present. */336q_scale_factor = jpeg_quality_scaling(quality);337338} else if (keymatch(arg, "qslots", 2)) {339/* Quantization table slot numbers. */340if (++argn >= argc) /* advance to next argument */341usage();342qslotsarg = argv[argn];343/* Must delay setting qslots until after we have processed any344* colorspace-determining switches, since jpeg_set_colorspace sets345* default quant table numbers.346*/347348} else if (keymatch(arg, "qtables", 2)) {349/* Quantization tables fetched from file. */350if (++argn >= argc) /* advance to next argument */351usage();352qtablefile = argv[argn];353/* We postpone actually reading the file in case -quality comes later. */354355} else if (keymatch(arg, "restart", 1)) {356/* Restart interval in MCU rows (or in MCUs with 'b'). */357long lval;358char ch = 'x';359360if (++argn >= argc) /* advance to next argument */361usage();362if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)363usage();364if (lval < 0 || lval > 65535L)365usage();366if (ch == 'b' || ch == 'B') {367cinfo->restart_interval = (unsigned int) lval;368cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */369} else {370cinfo->restart_in_rows = (int) lval;371/* restart_interval will be computed during startup */372}373374} else if (keymatch(arg, "sample", 2)) {375/* Set sampling factors. */376if (++argn >= argc) /* advance to next argument */377usage();378samplearg = argv[argn];379/* Must delay setting sample factors until after we have processed any380* colorspace-determining switches, since jpeg_set_colorspace sets381* default sampling factors.382*/383384} else if (keymatch(arg, "scans", 2)) {385/* Set scan script. */386#ifdef C_MULTISCAN_FILES_SUPPORTED387if (++argn >= argc) /* advance to next argument */388usage();389scansarg = argv[argn];390/* We must postpone reading the file in case -progressive appears. */391#else392fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",393progname);394exit(EXIT_FAILURE);395#endif396397} else if (keymatch(arg, "smooth", 2)) {398/* Set input smoothing factor. */399int val;400401if (++argn >= argc) /* advance to next argument */402usage();403if (sscanf(argv[argn], "%d", &val) != 1)404usage();405if (val < 0 || val > 100)406usage();407cinfo->smoothing_factor = val;408409} else if (keymatch(arg, "targa", 1)) {410/* Input file is Targa format. */411is_targa = TRUE;412413} else {414usage(); /* bogus switch */415}416}417418/* Post-switch-scanning cleanup */419420if (for_real) {421422/* Set quantization tables for selected quality. */423/* Some or all may be overridden if -qtables is present. */424jpeg_set_quality(cinfo, quality, force_baseline);425426if (qtablefile != NULL) /* process -qtables if it was present */427if (! read_quant_tables(cinfo, qtablefile,428q_scale_factor, force_baseline))429usage();430431if (qslotsarg != NULL) /* process -qslots if it was present */432if (! set_quant_slots(cinfo, qslotsarg))433usage();434435if (samplearg != NULL) /* process -sample if it was present */436if (! set_sample_factors(cinfo, samplearg))437usage();438439#ifdef C_PROGRESSIVE_SUPPORTED440if (simple_progressive) /* process -progressive; -scans can override */441jpeg_simple_progression(cinfo);442#endif443444#ifdef C_MULTISCAN_FILES_SUPPORTED445if (scansarg != NULL) /* process -scans if it was present */446if (! read_scan_script(cinfo, scansarg))447usage();448#endif449}450451return argn; /* return index of next arg (file name) */452}453454455/*456* The main program.457*/458459int460main (int argc, char **argv)461{462struct jpeg_compress_struct cinfo;463struct jpeg_error_mgr jerr;464#ifdef PROGRESS_REPORT465struct cdjpeg_progress_mgr progress;466#endif467int file_index;468cjpeg_source_ptr src_mgr;469FILE * input_file;470FILE * output_file;471JDIMENSION num_scanlines;472473/* On Mac, fetch a command line. */474#ifdef USE_CCOMMAND475argc = ccommand(&argv);476#endif477478progname = argv[0];479if (progname == NULL || progname[0] == 0)480progname = "cjpeg"; /* in case C library doesn't provide it */481482/* Initialize the JPEG compression object with default error handling. */483cinfo.err = jpeg_std_error(&jerr);484jpeg_create_compress(&cinfo);485/* Add some application-specific error messages (from cderror.h) */486jerr.addon_message_table = cdjpeg_message_table;487jerr.first_addon_message = JMSG_FIRSTADDONCODE;488jerr.last_addon_message = JMSG_LASTADDONCODE;489490/* Now safe to enable signal catcher. */491#ifdef NEED_SIGNAL_CATCHER492enable_signal_catcher((j_common_ptr) &cinfo);493#endif494495/* Initialize JPEG parameters.496* Much of this may be overridden later.497* In particular, we don't yet know the input file's color space,498* but we need to provide some value for jpeg_set_defaults() to work.499*/500501cinfo.in_color_space = JCS_RGB; /* arbitrary guess */502jpeg_set_defaults(&cinfo);503504/* Scan command line to find file names.505* It is convenient to use just one switch-parsing routine, but the switch506* values read here are ignored; we will rescan the switches after opening507* the input file.508*/509510file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);511512#ifdef TWO_FILE_COMMANDLINE513/* Must have either -outfile switch or explicit output file name */514if (outfilename == NULL) {515if (file_index != argc-2) {516fprintf(stderr, "%s: must name one input and one output file\n",517progname);518usage();519}520outfilename = argv[file_index+1];521} else {522if (file_index != argc-1) {523fprintf(stderr, "%s: must name one input and one output file\n",524progname);525usage();526}527}528#else529/* Unix style: expect zero or one file name */530if (file_index < argc-1) {531fprintf(stderr, "%s: only one input file\n", progname);532usage();533}534#endif /* TWO_FILE_COMMANDLINE */535536/* Open the input file. */537if (file_index < argc) {538if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {539fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);540exit(EXIT_FAILURE);541}542} else {543/* default input file is stdin */544input_file = read_stdin();545}546547/* Open the output file. */548if (outfilename != NULL) {549if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {550fprintf(stderr, "%s: can't open %s\n", progname, outfilename);551exit(EXIT_FAILURE);552}553} else {554/* default output file is stdout */555output_file = write_stdout();556}557558#ifdef PROGRESS_REPORT559start_progress_monitor((j_common_ptr) &cinfo, &progress);560#endif561562/* Figure out the input file format, and set up to read it. */563src_mgr = select_file_type(&cinfo, input_file);564src_mgr->input_file = input_file;565566/* Read the input file header to obtain file size & colorspace. */567(*src_mgr->start_input) (&cinfo, src_mgr);568569/* Now that we know input colorspace, fix colorspace-dependent defaults */570jpeg_default_colorspace(&cinfo);571572/* Adjust default compression parameters by re-parsing the options */573file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);574575/* Specify data destination for compression */576jpeg_stdio_dest(&cinfo, output_file);577578/* Start compressor */579jpeg_start_compress(&cinfo, TRUE);580581/* Process data */582while (cinfo.next_scanline < cinfo.image_height) {583num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);584(void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);585}586587/* Finish compression and release memory */588(*src_mgr->finish_input) (&cinfo, src_mgr);589jpeg_finish_compress(&cinfo);590jpeg_destroy_compress(&cinfo);591592/* Close files, if we opened them */593if (input_file != stdin)594fclose(input_file);595if (output_file != stdout)596fclose(output_file);597598#ifdef PROGRESS_REPORT599end_progress_monitor((j_common_ptr) &cinfo);600#endif601602/* All done. */603exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);604return 0; /* suppress no-return-value warnings */605}606607608