Coverage Report

Created: 2025-07-11 07:03

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