Coverage Report

Created: 2026-02-15 06:30

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