Coverage Report

Created: 2026-05-11 06:55

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