Coverage Report

Created: 2025-07-01 06:27

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