Coverage Report

Created: 2026-10-31 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/jpegoptim/jpegoptim.c
Line
Count
Source
1
/*******************************************************************
2
 * JPEGoptim
3
 * Copyright (c) Timo Kokkonen, 1996-2026.
4
 * All Rights Reserved.
5
 *
6
 * requires libjpeg (Independent JPEG Group's JPEG software
7
 *                     release 6a or later...)
8
 *
9
 * SPDX-License-Identifier: GPL-3.0-or-later
10
 *
11
 * This file is part of JPEGoptim.
12
 *
13
 * JPEGoptim is free software: you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation, either version 3 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * JPEGoptim is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with JPEGoptim. If not, see <https://www.gnu.org/licenses/>.
25
 */
26
27
#ifdef HAVE_CONFIG_H
28
#include "config.h"
29
#endif
30
#include <stdio.h>
31
#include <stdint.h>
32
#include <inttypes.h>
33
#include <stdlib.h>
34
#ifdef HAVE_UNISTD_H
35
#include <unistd.h>
36
#endif
37
#if HAVE_DIRENT_H
38
#include <dirent.h>
39
#endif
40
#if HAVE_FCNTL_H
41
#include <fcntl.h>
42
#endif
43
#if HAVE_SYS_STAT_H
44
#include <sys/stat.h>
45
#endif
46
#if HAVE_SYS_TYPES_H
47
#include <sys/types.h>
48
#endif
49
#if HAVE_SYS_WAIT_H
50
#include <sys/wait.h>
51
#endif
52
#if HAVE_GETOPT_H && HAVE_GETOPT_LONG
53
#include <getopt.h>
54
#else
55
#include "getopt.h"
56
#endif
57
#include <signal.h>
58
#include <string.h>
59
#include <limits.h>
60
#include <jpeglib.h>
61
#include <jerror.h>
62
#include <setjmp.h>
63
#include <time.h>
64
#include <math.h>
65
66
#include "jpegmarker.h"
67
#include "jpegoptim.h"
68
69
70
0
#define VERSION "1.5.7beta"
71
0
#define COPYRIGHT  "Copyright (C) 1996-2026, Timo Kokkonen"
72
73
#if HAVE_WAIT && HAVE_FORK
74
#define PARALLEL_PROCESSING 1
75
0
#define MAX_WORKERS 256
76
#include <poll.h>
77
#include <errno.h>
78
#endif
79
80
2.25k
#define IN_BUF_SIZE (256 * 1024)
81
82
/* Check for libjpeg-turbo or MozJPEG */
83
#if defined(HAVE_MOZJPEG)
84
#define JPEG_LIB_VARIANT "(MozJPEG)"
85
#elif defined(LIBJPEG_TURBO_VERSION)
86
0
#define JPEG_LIB_VARIANT "(libjpeg-turbo)"
87
#else
88
#define JPEG_LIB_VARIANT ""
89
#endif
90
91
struct my_error_mgr {
92
  struct jpeg_error_mgr pub;
93
  jmp_buf setjmp_buffer;
94
  int     jump_set;
95
};
96
typedef struct my_error_mgr * my_error_ptr;
97
98
99
#ifdef PARALLEL_PROCESSING
100
struct worker {
101
  pid_t pid;
102
  int   read_pipe;
103
};
104
struct worker *workers;
105
int worker_count = 0;
106
#endif
107
108
109
int verbose_mode = 0;
110
int quiet_mode = 0;
111
int preserve_mtime = 0;
112
int preserve_perms = 0;
113
int overwrite_mode = 0;
114
int retry_mode = 0;
115
int totals_mode = 0;
116
int stdin_mode = 0;
117
int stdout_mode = 0;
118
int noaction = 0;
119
int quality = -1;
120
int dest = 0;
121
int force = 0;
122
int save_extra = 0;
123
int save_exif = 1;
124
int save_iptc = 1;
125
int save_com = 1;
126
int save_icc = 1;
127
int save_xmp = 1;
128
int save_adobe = 0;
129
int save_jfxx = 0;
130
int save_jfif = 1;
131
int strip_none = 0;
132
int strip_ai = 0;
133
double threshold = -1.0;
134
int csv = 0;
135
int auto_mode = 0;
136
int all_normal = 0;
137
int all_progressive = 0;
138
int target_size = 0;
139
#ifdef HAVE_ARITH_CODE
140
int arith_mode = -1;
141
#endif
142
int max_workers = 1;
143
uint64_t max_pixels = 0;
144
int nofix_mode = 0;
145
int files_stdin = 0;
146
FILE *files_from = NULL;
147
148
int compress_err_count = 0;
149
int decompress_err_count = 0;
150
int global_error_counter = 0;
151
char last_error[JMSG_LENGTH_MAX+1];
152
FILE *jpeg_log_fh;
153
uint64_t average_count = 0;
154
double average_rate = 0.0;
155
double total_save = 0.0;
156
157
158
/* Codes for long arguments that need parsing */
159
0
#define MAX_PIXELS 0xf001
160
161
const struct option long_options[] = {
162
#ifdef HAVE_ARITH_CODE
163
  { "all-arith",          0, &arith_mode,          1 },
164
  { "all-huffman",        0, &arith_mode,          0 },
165
#endif
166
  { "auto-mode",          0, &auto_mode,           1 },
167
  { "all-normal",         0, &all_normal,          1 },
168
  { "all-progressive",    0, &all_progressive,     1 },
169
  { "csv",                0, 0,                   'b' },
170
  { "dest",               1, 0,                   'd' },
171
  { "files-stdin",        0, &files_stdin,         1 },
172
  { "files-from",         1, 0,                   'F' },
173
  { "force",              0, 0,                   'f' },
174
  { "help",               0, 0,                   'h' },
175
  { "keep-adobe",         0, &save_adobe,          1 },
176
  { "keep-all",           0, &strip_none,          1 },
177
  { "keep-com",           0, &save_com,            1 },
178
  { "keep-exif",          0, &save_exif,           1 },
179
  { "keep-iptc",          0, &save_iptc,           1 },
180
  { "keep-icc",           0, &save_icc,            1 },
181
  { "keep-jfif",          0, &save_jfif,           1 },
182
  { "keep-jfxx",          0, &save_jfxx,           1 },
183
  { "keep-xmp",           0, &save_xmp,            1 },
184
  { "max",                1, 0,                   'm' },
185
  { "max-pixels",         1, 0,                    MAX_PIXELS },
186
  { "noaction",           0, 0,                   'n' },
187
  { "nofix",              0, &nofix_mode,          1 },
188
  { "overwrite",          0, 0,                   'o' },
189
  { "preserve",           0, 0,                   'p' },
190
  { "preserve-perms",     0, 0,                   'P' },
191
  { "quiet",              0, 0,                   'q' },
192
  { "retry",              0, 0,                   'r' },
193
  { "save-extra",         0, &save_extra,          1 },
194
  { "size",               1, 0,                   'S' },
195
  { "stdin",              0, &stdin_mode,          1 },
196
  { "stdout",             0, &stdout_mode,         1 },
197
  { "strip-all",          0, 0,                   's' },
198
  { "strip-none",         0, &strip_none,          1 },
199
  { "strip-com",          0, &save_com,            0 },
200
  { "strip-exif",         0, &save_exif,           0 },
201
  { "strip-iptc",         0, &save_iptc,           0 },
202
  { "strip-icc",          0, &save_icc,            0 },
203
  { "strip-xmp",          0, &save_xmp,            0 },
204
  { "strip-jfif",         0, &save_jfif,           0 },
205
  { "strip-jfxx",         0, &save_jfxx,           0 },
206
  { "strip-adobe",        0, &save_adobe,          0 },
207
  { "strip-ai",           0, &strip_ai,            1 },
208
  { "threshold",          1, 0,                   'T' },
209
  { "totals",             0, 0,                   't' },
210
  { "verbose",            0, 0,                   'v' },
211
  { "version",            0, 0,                   'V' },
212
#ifdef PARALLEL_PROCESSING
213
  { "workers",            1, 0,                   'w' },
214
#endif
215
  { 0, 0, 0, 0 }
216
};
217
218
219
/*****************************************************************/
220
221
222
void free_line_buf(JSAMPARRAY volatile *buf, unsigned int lines)
223
982
{
224
982
  if (*buf == NULL)
225
485
    return;
226
227
2.19M
  for (unsigned int i = 0; i < lines; i++) {
228
2.19M
    if ((*buf)[i])
229
2.19M
      free((*buf)[i]);
230
2.19M
  }
231
497
  free(*buf);
232
497
  *buf = NULL;
233
497
}
234
235
236
METHODDEF(void) my_error_exit (j_common_ptr cinfo)
237
402
{
238
402
  my_error_ptr myerr = (my_error_ptr)cinfo->err;
239
240
402
  (*cinfo->err->output_message)(cinfo);
241
402
  if (myerr->jump_set)
242
402
    longjmp(myerr->setjmp_buffer, 1);
243
0
  else
244
0
    fatal("fatal error");
245
402
}
246
247
248
METHODDEF(void) my_output_message (j_common_ptr cinfo)
249
1.36k
{
250
1.36k
  char buffer[JMSG_LENGTH_MAX+1];
251
252
1.36k
  (*cinfo->err->format_message)((j_common_ptr)cinfo, buffer);
253
1.36k
  buffer[sizeof(buffer) - 1] = 0;
254
255
1.36k
  if (verbose_mode)
256
0
    fprintf(jpeg_log_fh, " (%s) ", buffer);
257
258
1.36k
  global_error_counter++;
259
1.36k
  strncopy(last_error, buffer, sizeof(last_error));
260
1.36k
}
261
262
263
void print_usage(void)
264
0
{
265
0
  fprintf(stdout,PROGRAMNAME " v" VERSION "  " COPYRIGHT "\n");
266
267
0
  fprintf(stdout,
268
0
    "Usage: " PROGRAMNAME " [options] <filenames> \n\n"
269
0
    "  -d<path>, --dest=<path>\n"
270
0
    "                    Specify alternative destination directory for \n"
271
0
    "                    optimized files (default is to overwrite originals)\n"
272
0
    "  -f, --force       Force optimization\n"
273
0
    "  -h, --help        Display this help and exit\n"
274
0
    "  -m<quality>, --max=<quality>\n"
275
0
    "                    Set maximum image quality factor (disables lossless\n"
276
0
    "                    optimization mode, which is by default on)\n"
277
0
    "                    Valid quality values: 0 - 100\n"
278
0
    "  -n, --noaction    Don't really optimize files, just print results\n"
279
0
    "  -S<size>, --size=<size>\n"
280
0
    "                    Try to optimize file to given size (disables lossless\n"
281
0
    "                    optimization mode). Target size is specified either in\n"
282
0
    "                    kilo bytes (1 - n) or as percentage (1%% - 99%%)\n"
283
0
    "  -T<threshold>, --threshold=<threshold>\n"
284
0
    "                    Keep old file if the gain is below a threshold (%%)\n"
285
0
#ifdef PARALLEL_PROCESSING
286
0
    "  -w<max>, --workers=<max>\n"
287
0
    "                    Set maximum number of parallel threads (default is 1)\n"
288
0
#endif
289
0
    "  -b, --csv         Print progress info in CSV format\n"
290
0
    "  -o, --overwrite   Overwrite target file even if it exists (meaningful\n"
291
0
    "                    only when used with -d, --dest option)\n"
292
0
    "  -p, --preserve    Preserve file timestamps\n"
293
0
    "  -P, --preserve-perms\n"
294
0
    "                    Preserve original file permissions by overwriting it\n"
295
0
    "  -q, --quiet       Quiet mode\n"
296
0
    "  -r, --retry       Try (recursively) optimize until file size does not change anymore\n"
297
0
    "  -t, --totals      Print totals after processing all files\n"
298
0
    "  -v, --verbose     Enable verbose mode (positively chatty)\n"
299
0
    "  -V, --version     Print program version\n\n"
300
0
    "  -s, --strip-all   Strip all markers from output file\n"
301
0
    "  --strip-none      Do not strip any markers\n"
302
0
    "  --strip-adobe     Strip Adobe (APP14) markers from output file\n"
303
0
    "  --strip-com       Strip Comment markers from output file\n"
304
0
    "  --strip-exif      Strip Exif markers from output file\n"
305
0
    "  --strip-iptc      Strip IPTC/Photoshop (APP13) markers from output file\n"
306
0
    "  --strip-icc       Strip ICC profile markers from output file\n"
307
0
    "  --strip-jfif      Strip JFIF markers from output file\n"
308
0
    "  --strip-jfxx      Strip JFXX (JFIF Extension) markers from output file\n"
309
0
    "  --strip-xmp       Strip XMP markers markers from output file\n"
310
0
    "  --strip-ai        Strip metadata telling the image was generated or edited\n"
311
0
    "                    with AI: C2PA manifests (Content Credentials), IPTC\n"
312
0
    "                    digital source type and generation parameters\n"
313
0
    "\n"
314
0
    "  --keep-all        Do not strip any markers (same as --strip-none)\n"
315
0
    "  --keep-adobe      Preserve any Adobe (APP14) markers\n"
316
0
    "  --keep-com        Preserve any Comment markers\n"
317
0
    "  --keep-exif       Preserve any Exif markers\n"
318
0
    "  --keep-iptc       Preserve any IPTC/Photoshop (APP13) markers\n"
319
0
    "  --keep-icc        Preserve any ICC profile markers\n"
320
0
    "  --keep-jfif       Preserve any JFIF markers\n"
321
0
    "  --keep-jfxx       Preserve any JFXX (JFIF Extension) markers\n"
322
0
    "  --keep-xmp        Preserve any XMP markers markers\n"
323
0
    "\n"
324
0
    "  --all-normal      Force all output files to be non-progressive\n"
325
0
    "  --all-progressive Force all output files to be progressive\n"
326
0
    "  --auto-mode       Select normal or progressive based on which produces\n"
327
0
    "                    smaller output file\n"
328
0
#ifdef HAVE_ARITH_CODE
329
0
    "  --all-arith       Force all output files to use arithmetic coding\n"
330
0
    "  --all-huffman     Force all output files to use Huffman coding\n"
331
0
#endif
332
0
    "  --stdout          Send output to standard output (instead of a file)\n"
333
0
    "  --stdin           Read input from standard input (instead of a file)\n"
334
0
    "  --files-stdin     Read names of files to process from stdin\n"
335
0
    "  --files-from=FILE Read names of files to process from a file\n"
336
0
    "  --max-pixels=<megapixels>\n"
337
0
    "                    Set maximum allowed input image size (in megapixels)\n"
338
0
    "  --nofix           Skip processing of input files if they contain any errors\n"
339
0
    "  --save-extra      Preserve extraneous data after the end of image\n"
340
0
    "\n\n");
341
0
}
342
343
344
void print_version()
345
0
{
346
0
  struct jpeg_error_mgr jerr;
347
348
0
#ifdef  __DATE__
349
0
  printf(PROGRAMNAME " v%s  %s (%s)\n",VERSION, HOST_TYPE, __DATE__);
350
#else
351
  printf(PROGRAMNAME " v%s  %s\n", VERSION, HOST_TYPE);
352
#endif
353
0
  printf(COPYRIGHT "\n\n");
354
0
  printf("This program comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
355
0
    "and you are welcome to redistribute it under certain conditions.\n"
356
0
    "See the GNU General Public License for more details.\n\n");
357
358
0
  if (!jpeg_std_error(&jerr))
359
0
    fatal("jpeg_std_error() failed");
360
361
0
  printf("\nlibjpeg version: %s %s\n%s\n",
362
0
         jerr.jpeg_message_table[JMSG_VERSION], JPEG_LIB_VARIANT,
363
0
         jerr.jpeg_message_table[JMSG_COPYRIGHT]);
364
0
}
365
366
367
void parse_arguments(int argc, char **argv, char *dest_path, size_t dest_path_len)
368
0
{
369
0
  int opt_index;
370
0
  int i, c;
371
372
0
  while(1) {
373
0
    opt_index=0;
374
0
    if ((c = getopt_long(argc,argv,"d:hm:nstqvfVpProT:S:bw:",
375
0
            long_options, &opt_index)) == -1)
376
0
      break;
377
378
0
    switch (c) {
379
380
0
    case 'm':
381
0
            {
382
0
        int tmpvar;
383
384
0
        if (str_to_int(optarg, &tmpvar, 10)) {
385
0
          if (tmpvar < 0 || tmpvar > 100)
386
0
            fatal("invalid value for -m, --max specified (valid range 0..100)");
387
0
          quality=tmpvar;
388
0
        }
389
0
        else
390
0
          fatal("invalid argument for -m, --max");
391
0
      }
392
0
      break;
393
394
0
    case 'd':
395
0
            {
396
        /* Use the allocating form of realpath(), as a caller
397
           supplied buffer would need to be at least PATH_MAX
398
           bytes, which can be larger than MAXPATHLEN... */
399
0
        char *dpath = realpath(optarg, NULL);
400
401
0
        if (!dpath)
402
0
          fatal("invalid destination directory: %s", optarg);
403
0
        if (!is_directory(dpath))
404
0
          fatal("destination not a directory: %s", dpath);
405
0
        if (strlen(dpath) + strlen(DIR_SEPARATOR_S) >= dest_path_len)
406
0
          fatal("destination directory path too long: %s", optarg);
407
0
        strncopy(dest_path, dpath, dest_path_len);
408
0
        free(dpath);
409
0
        strncatenate(dest_path, DIR_SEPARATOR_S, dest_path_len);
410
0
        if (verbose_mode)
411
0
          fprintf(stderr,"Destination directory: %s\n",dest_path);
412
0
        dest=1;
413
0
      }
414
0
      break;
415
416
0
    case 'v':
417
0
      verbose_mode++;
418
0
      break;
419
420
0
    case 'h':
421
0
      print_usage();
422
0
      exit(0);
423
0
      break;
424
425
0
    case 'q':
426
0
      quiet_mode=1;
427
0
      break;
428
429
0
    case 'r':
430
0
      retry_mode=1;
431
0
      break;
432
433
0
    case 't':
434
0
      totals_mode=1;
435
0
      break;
436
437
0
    case 'n':
438
0
      noaction=1;
439
0
      break;
440
441
0
    case 'f':
442
0
      force=1;
443
0
      break;
444
445
0
    case 'b':
446
0
      csv=1;
447
0
      quiet_mode=1;
448
0
      break;
449
450
0
    case 'V':
451
0
      print_version();
452
0
      exit(0);
453
0
      break;
454
455
0
    case 'o':
456
0
      overwrite_mode=1;
457
0
      break;
458
459
0
    case 'p':
460
0
      preserve_mtime=1;
461
0
      break;
462
463
0
    case 'P':
464
0
      preserve_perms=1;
465
0
      break;
466
467
0
    case 's':
468
0
      save_exif=0;
469
0
      save_iptc=0;
470
0
      save_com=0;
471
0
      save_icc=0;
472
0
      save_xmp=0;
473
0
      save_adobe=0;
474
0
      save_jfif=0;
475
0
      save_jfxx=0;
476
0
      break;
477
478
0
    case 'T':
479
0
            {
480
0
        double tmpvar;
481
0
        if (str_to_double(optarg, &tmpvar)) {
482
0
          if (tmpvar < 0.0 || tmpvar > 100.0)
483
0
            fatal("invalid value for -T, --threshold specified (valid range 0..100)");
484
0
          threshold=tmpvar;
485
0
        }
486
0
        else fatal("invalid argument for -T, --threshold");
487
0
      }
488
0
      break;
489
490
0
    case 'S':
491
0
            {
492
0
        char *endp = NULL;
493
0
        long tmpvar = strtol(optarg, &endp, 10);
494
495
0
        if (endp == optarg || tmpvar <= 0)
496
0
          fatal("invalid argument for -S, --size: %s", optarg);
497
0
        if (endp[0] == '%' && endp[1] == 0) {
498
          /* Target size given as percentage (1% - 99%) */
499
0
          if (tmpvar >= 100)
500
0
            fatal("invalid percentage for -S, --size: %s", optarg);
501
0
          target_size = -tmpvar;
502
0
        } else if (endp[0] == 0) {
503
          /* Target size given in kilobytes */
504
0
          if (tmpvar > INT_MAX)
505
0
            fatal("invalid argument for -S, --size: %s", optarg);
506
0
          target_size = tmpvar;
507
0
        } else {
508
0
          fatal("invalid argument for -S, --size: %s", optarg);
509
0
        }
510
0
        quality=100;
511
0
      }
512
0
      break;
513
514
0
#ifdef PARALLEL_PROCESSING
515
0
    case 'w':
516
0
            {
517
0
        int tmpvar;
518
0
        if (str_to_int(optarg, &tmpvar, 10)) {
519
0
          if (tmpvar <= 0 || tmpvar > MAX_WORKERS)
520
0
            fatal("invalid value for -w, --workers specified");
521
0
          max_workers = tmpvar;
522
0
        }
523
0
        else fatal("invalid argument for -w, --workers");
524
0
      }
525
0
      break;
526
0
#endif
527
528
0
    case 'F':
529
0
            {
530
0
        if (optarg[0] == '-' && optarg[1] == 0) {
531
0
          files_stdin = 1;
532
0
          break;
533
0
        }
534
0
        if (!is_file(optarg, NULL))
535
0
          fatal("argument for --files-from must be a file");
536
0
        if ((files_from = fopen(optarg, "r")) == NULL)
537
0
          fatal("cannot open file: '%s'", optarg);
538
0
      }
539
0
      break;
540
541
0
    case MAX_PIXELS:
542
0
            {
543
0
        int tmpvar;
544
0
        if (str_to_int(optarg, &tmpvar, 10)) {
545
0
          if (tmpvar < 0)
546
0
            fatal("invalid value for --max-pixels specified");
547
0
          max_pixels = (uint64_t)tmpvar * 1000000;
548
0
        }
549
0
        else fatal("invalid argument for --max-pixels");
550
0
      }
551
0
      break;
552
553
0
    case '?':
554
0
      exit(1);
555
556
0
    }
557
0
  }
558
559
560
  /* check for '-' option indicating input is from stdin... */
561
0
  i = optind;
562
0
  while (argv[i]) {
563
0
    if (argv[i][0]=='-' && argv[i][1]==0)
564
0
      stdin_mode=1;
565
0
    i++;
566
0
  }
567
568
0
  if (stdin_mode)
569
0
    stdout_mode=1;
570
0
  if (files_stdin)
571
0
    files_from = stdin;
572
0
  if (stdin_mode && files_from == stdin)
573
0
    fatal("cannot specify both --stdin and --files-stdin");
574
0
#ifdef PARALLEL_PROCESSING
575
0
  if (stdout_mode && max_workers > 1) {
576
    /* Parallel workers would write to stdout concurrently,
577
       interleaving (corrupting) the output stream... */
578
0
    warn("--stdout is incompatible with parallel workers, using only one worker");
579
0
    max_workers = 1;
580
0
  }
581
0
#endif
582
0
  if (all_normal && all_progressive)
583
0
    fatal("cannot specify both --all-normal and --all-progressive");
584
0
  if (auto_mode && (all_normal || all_progressive))
585
0
    fatal("cannot specify --all-normal or --all-progressive if using --auto-mode");
586
0
}
587
588
589
void own_signal_handler(int a)
590
0
{
591
0
  if (verbose_mode > 1)
592
0
    fprintf(stderr,PROGRAMNAME ": died from signal: %d\n",a);
593
0
  exit(2);
594
0
}
595
596
597
void write_markers(struct jpeg_decompress_struct *dinfo,
598
    struct jpeg_compress_struct *cinfo)
599
4.76k
{
600
4.76k
  jpeg_saved_marker_ptr mrk;
601
4.76k
  int write_marker;
602
4.76k
  const char *s_name;
603
604
4.76k
  if (!cinfo || !dinfo)
605
0
    fatal("invalid call to write_markers()");
606
607
4.76k
  mrk=dinfo->marker_list;
608
6.83M
  while (mrk) {
609
6.82M
    write_marker = 0;
610
6.82M
    s_name = jpeg_special_marker_name(mrk);
611
612
    /* Check for markers to save... */
613
614
6.82M
    if (save_com && mrk->marker == JPEG_COM)
615
91.3k
      write_marker++;
616
617
6.82M
    if (save_iptc && !strncmp(s_name, "IPTC", 5))
618
33.6k
      write_marker++;
619
620
6.82M
    if (save_exif && !strncmp(s_name, "Exif", 5))
621
3.61k
      write_marker++;
622
623
6.82M
    if (save_icc && !strncmp(s_name, "ICC", 4))
624
22.6k
      write_marker++;
625
626
6.82M
    if (save_xmp && !strncmp(s_name, "XMP", 4))
627
7.93k
      write_marker++;
628
629
6.82M
    if (save_jfxx && !strncmp(s_name, "JFXX", 5))
630
0
      write_marker++;
631
632
6.82M
    if (save_adobe && !strncmp(s_name, "Adobe", 6))
633
0
      write_marker++;
634
635
6.82M
    if (strip_none)
636
0
      write_marker++;
637
638
639
    /* libjpeg emits some markers automatically so skip these to avoid duplicates... */
640
641
6.82M
    if (!strncmp(s_name, "JFIF", 5))
642
456k
      write_marker=0;
643
644
645
6.82M
    if (verbose_mode > 2)
646
0
      fprintf(jpeg_log_fh, " (Marker %s [%s]: %s)", jpeg_marker_name(mrk->marker),
647
0
        s_name, (write_marker ? "Keep" : "Discard"));
648
6.82M
    if (write_marker)
649
159k
      jpeg_write_marker(cinfo, mrk->marker, mrk->data, mrk->data_length);
650
651
6.82M
    mrk=mrk->next;
652
6.82M
  }
653
4.76k
}
write_markers
Line
Count
Source
599
1.58k
{
600
1.58k
  jpeg_saved_marker_ptr mrk;
601
1.58k
  int write_marker;
602
1.58k
  const char *s_name;
603
604
1.58k
  if (!cinfo || !dinfo)
605
0
    fatal("invalid call to write_markers()");
606
607
1.58k
  mrk=dinfo->marker_list;
608
2.27M
  while (mrk) {
609
2.27M
    write_marker = 0;
610
2.27M
    s_name = jpeg_special_marker_name(mrk);
611
612
    /* Check for markers to save... */
613
614
2.27M
    if (save_com && mrk->marker == JPEG_COM)
615
30.4k
      write_marker++;
616
617
2.27M
    if (save_iptc && !strncmp(s_name, "IPTC", 5))
618
11.2k
      write_marker++;
619
620
2.27M
    if (save_exif && !strncmp(s_name, "Exif", 5))
621
1.20k
      write_marker++;
622
623
2.27M
    if (save_icc && !strncmp(s_name, "ICC", 4))
624
7.54k
      write_marker++;
625
626
2.27M
    if (save_xmp && !strncmp(s_name, "XMP", 4))
627
2.64k
      write_marker++;
628
629
2.27M
    if (save_jfxx && !strncmp(s_name, "JFXX", 5))
630
0
      write_marker++;
631
632
2.27M
    if (save_adobe && !strncmp(s_name, "Adobe", 6))
633
0
      write_marker++;
634
635
2.27M
    if (strip_none)
636
0
      write_marker++;
637
638
639
    /* libjpeg emits some markers automatically so skip these to avoid duplicates... */
640
641
2.27M
    if (!strncmp(s_name, "JFIF", 5))
642
152k
      write_marker=0;
643
644
645
2.27M
    if (verbose_mode > 2)
646
0
      fprintf(jpeg_log_fh, " (Marker %s [%s]: %s)", jpeg_marker_name(mrk->marker),
647
0
        s_name, (write_marker ? "Keep" : "Discard"));
648
2.27M
    if (write_marker)
649
53.0k
      jpeg_write_marker(cinfo, mrk->marker, mrk->data, mrk->data_length);
650
651
2.27M
    mrk=mrk->next;
652
2.27M
  }
653
1.58k
}
write_markers
Line
Count
Source
599
1.58k
{
600
1.58k
  jpeg_saved_marker_ptr mrk;
601
1.58k
  int write_marker;
602
1.58k
  const char *s_name;
603
604
1.58k
  if (!cinfo || !dinfo)
605
0
    fatal("invalid call to write_markers()");
606
607
1.58k
  mrk=dinfo->marker_list;
608
2.27M
  while (mrk) {
609
2.27M
    write_marker = 0;
610
2.27M
    s_name = jpeg_special_marker_name(mrk);
611
612
    /* Check for markers to save... */
613
614
2.27M
    if (save_com && mrk->marker == JPEG_COM)
615
30.4k
      write_marker++;
616
617
2.27M
    if (save_iptc && !strncmp(s_name, "IPTC", 5))
618
11.2k
      write_marker++;
619
620
2.27M
    if (save_exif && !strncmp(s_name, "Exif", 5))
621
1.20k
      write_marker++;
622
623
2.27M
    if (save_icc && !strncmp(s_name, "ICC", 4))
624
7.54k
      write_marker++;
625
626
2.27M
    if (save_xmp && !strncmp(s_name, "XMP", 4))
627
2.64k
      write_marker++;
628
629
2.27M
    if (save_jfxx && !strncmp(s_name, "JFXX", 5))
630
0
      write_marker++;
631
632
2.27M
    if (save_adobe && !strncmp(s_name, "Adobe", 6))
633
0
      write_marker++;
634
635
2.27M
    if (strip_none)
636
0
      write_marker++;
637
638
639
    /* libjpeg emits some markers automatically so skip these to avoid duplicates... */
640
641
2.27M
    if (!strncmp(s_name, "JFIF", 5))
642
152k
      write_marker=0;
643
644
645
2.27M
    if (verbose_mode > 2)
646
0
      fprintf(jpeg_log_fh, " (Marker %s [%s]: %s)", jpeg_marker_name(mrk->marker),
647
0
        s_name, (write_marker ? "Keep" : "Discard"));
648
2.27M
    if (write_marker)
649
53.0k
      jpeg_write_marker(cinfo, mrk->marker, mrk->data, mrk->data_length);
650
651
2.27M
    mrk=mrk->next;
652
2.27M
  }
653
1.58k
}
write_markers
Line
Count
Source
599
1.58k
{
600
1.58k
  jpeg_saved_marker_ptr mrk;
601
1.58k
  int write_marker;
602
1.58k
  const char *s_name;
603
604
1.58k
  if (!cinfo || !dinfo)
605
0
    fatal("invalid call to write_markers()");
606
607
1.58k
  mrk=dinfo->marker_list;
608
2.27M
  while (mrk) {
609
2.27M
    write_marker = 0;
610
2.27M
    s_name = jpeg_special_marker_name(mrk);
611
612
    /* Check for markers to save... */
613
614
2.27M
    if (save_com && mrk->marker == JPEG_COM)
615
30.4k
      write_marker++;
616
617
2.27M
    if (save_iptc && !strncmp(s_name, "IPTC", 5))
618
11.2k
      write_marker++;
619
620
2.27M
    if (save_exif && !strncmp(s_name, "Exif", 5))
621
1.20k
      write_marker++;
622
623
2.27M
    if (save_icc && !strncmp(s_name, "ICC", 4))
624
7.54k
      write_marker++;
625
626
2.27M
    if (save_xmp && !strncmp(s_name, "XMP", 4))
627
2.64k
      write_marker++;
628
629
2.27M
    if (save_jfxx && !strncmp(s_name, "JFXX", 5))
630
0
      write_marker++;
631
632
2.27M
    if (save_adobe && !strncmp(s_name, "Adobe", 6))
633
0
      write_marker++;
634
635
2.27M
    if (strip_none)
636
0
      write_marker++;
637
638
639
    /* libjpeg emits some markers automatically so skip these to avoid duplicates... */
640
641
2.27M
    if (!strncmp(s_name, "JFIF", 5))
642
152k
      write_marker=0;
643
644
645
2.27M
    if (verbose_mode > 2)
646
0
      fprintf(jpeg_log_fh, " (Marker %s [%s]: %s)", jpeg_marker_name(mrk->marker),
647
0
        s_name, (write_marker ? "Keep" : "Discard"));
648
2.27M
    if (write_marker)
649
53.0k
      jpeg_write_marker(cinfo, mrk->marker, mrk->data, mrk->data_length);
650
651
2.27M
    mrk=mrk->next;
652
2.27M
  }
653
1.58k
}
654
655
656
unsigned int parse_markers(const struct jpeg_decompress_struct *dinfo,
657
      char *str, unsigned int str_size, unsigned int *markers_total_size)
658
2.74k
{
659
2.74k
  jpeg_saved_marker_ptr m;
660
2.74k
  unsigned int count = 0;
661
2.74k
  char *seen;
662
2.74k
  size_t marker_types = jpeg_special_marker_types_count();
663
2.74k
  int com_seen = 0;
664
2.74k
  int special;
665
666
2.74k
  if ((seen = calloc(marker_types, 1)) == NULL)
667
0
    fatal("not enough of memory");
668
669
2.74k
  str[0] = 0;
670
2.74k
  *markers_total_size = 0;
671
672
2.74k
  m = dinfo->marker_list;
673
2.35M
  while (m) {
674
2.35M
    count++;
675
2.35M
    *markers_total_size += m->data_length;
676
677
2.35M
    if ((special = jpeg_special_marker(m)) >= 0) {
678
1.99M
      if (!seen[special])
679
11.1k
        str_add_list(str, str_size, jpeg_special_marker_types[special].name, ",");
680
1.99M
      seen[special]++;
681
1.99M
    }
682
683
2.35M
    if (m->marker == JPEG_COM && !com_seen) {
684
567
      str_add_list(str, str_size, "COM", ",");
685
567
      com_seen = 1;
686
567
    }
687
688
2.35M
    m = m->next;
689
2.35M
  }
690
691
2.74k
  free(seen);
692
693
2.74k
  return count;
694
2.74k
}
parse_markers
Line
Count
Source
658
914
{
659
914
  jpeg_saved_marker_ptr m;
660
914
  unsigned int count = 0;
661
914
  char *seen;
662
914
  size_t marker_types = jpeg_special_marker_types_count();
663
914
  int com_seen = 0;
664
914
  int special;
665
666
914
  if ((seen = calloc(marker_types, 1)) == NULL)
667
0
    fatal("not enough of memory");
668
669
914
  str[0] = 0;
670
914
  *markers_total_size = 0;
671
672
914
  m = dinfo->marker_list;
673
785k
  while (m) {
674
784k
    count++;
675
784k
    *markers_total_size += m->data_length;
676
677
784k
    if ((special = jpeg_special_marker(m)) >= 0) {
678
663k
      if (!seen[special])
679
3.72k
        str_add_list(str, str_size, jpeg_special_marker_types[special].name, ",");
680
663k
      seen[special]++;
681
663k
    }
682
683
784k
    if (m->marker == JPEG_COM && !com_seen) {
684
189
      str_add_list(str, str_size, "COM", ",");
685
189
      com_seen = 1;
686
189
    }
687
688
784k
    m = m->next;
689
784k
  }
690
691
914
  free(seen);
692
693
914
  return count;
694
914
}
parse_markers
Line
Count
Source
658
914
{
659
914
  jpeg_saved_marker_ptr m;
660
914
  unsigned int count = 0;
661
914
  char *seen;
662
914
  size_t marker_types = jpeg_special_marker_types_count();
663
914
  int com_seen = 0;
664
914
  int special;
665
666
914
  if ((seen = calloc(marker_types, 1)) == NULL)
667
0
    fatal("not enough of memory");
668
669
914
  str[0] = 0;
670
914
  *markers_total_size = 0;
671
672
914
  m = dinfo->marker_list;
673
785k
  while (m) {
674
784k
    count++;
675
784k
    *markers_total_size += m->data_length;
676
677
784k
    if ((special = jpeg_special_marker(m)) >= 0) {
678
663k
      if (!seen[special])
679
3.72k
        str_add_list(str, str_size, jpeg_special_marker_types[special].name, ",");
680
663k
      seen[special]++;
681
663k
    }
682
683
784k
    if (m->marker == JPEG_COM && !com_seen) {
684
189
      str_add_list(str, str_size, "COM", ",");
685
189
      com_seen = 1;
686
189
    }
687
688
784k
    m = m->next;
689
784k
  }
690
691
914
  free(seen);
692
693
914
  return count;
694
914
}
parse_markers
Line
Count
Source
658
914
{
659
914
  jpeg_saved_marker_ptr m;
660
914
  unsigned int count = 0;
661
914
  char *seen;
662
914
  size_t marker_types = jpeg_special_marker_types_count();
663
914
  int com_seen = 0;
664
914
  int special;
665
666
914
  if ((seen = calloc(marker_types, 1)) == NULL)
667
0
    fatal("not enough of memory");
668
669
914
  str[0] = 0;
670
914
  *markers_total_size = 0;
671
672
914
  m = dinfo->marker_list;
673
785k
  while (m) {
674
784k
    count++;
675
784k
    *markers_total_size += m->data_length;
676
677
784k
    if ((special = jpeg_special_marker(m)) >= 0) {
678
663k
      if (!seen[special])
679
3.72k
        str_add_list(str, str_size, jpeg_special_marker_types[special].name, ",");
680
663k
      seen[special]++;
681
663k
    }
682
683
784k
    if (m->marker == JPEG_COM && !com_seen) {
684
189
      str_add_list(str, str_size, "COM", ",");
685
189
      com_seen = 1;
686
189
    }
687
688
784k
    m = m->next;
689
784k
  }
690
691
914
  free(seen);
692
693
914
  return count;
694
914
}
695
696
697
698
int optimize(FILE *log_fh, const char *filename, const char *newname,
699
  const char *tmpdir, struct stat *file_stat,
700
  double *rate, double *saved,
701
  int auto_mode, int all_normal, int all_progressive)
702
777
{
703
777
  FILE *infile = NULL;
704
777
  FILE *outfile = NULL;
705
777
  const char *outfname = NULL;
706
777
  char tmpfilename[MAXPATHLEN];
707
777
  struct jpeg_decompress_struct dinfo;
708
777
  struct jpeg_compress_struct cinfo;
709
777
  struct my_error_mgr jcerr, jderr;
710
711
  /* These buffers are (re)allocated between setjmp() and a possible
712
     longjmp() from the libjpeg error handlers, and then freed at
713
     exit_point after the jump. They must be volatile-qualified, as
714
     otherwise their values are indeterminate after longjmp()
715
     (C11 7.13.2.1), risking double-free or leak. */
716
777
  JSAMPARRAY volatile buf = NULL;
717
777
  unsigned char * volatile outbuffer = NULL;
718
777
  unsigned char * volatile inbuffer = NULL;
719
777
  unsigned char * volatile tmpbuffer = NULL;
720
777
  unsigned char * volatile extrabuffer = NULL;
721
722
777
  size_t outbuffersize = 0;
723
777
  size_t inbuffersize = 0;
724
777
  size_t inbufferused = 0;
725
777
  size_t tmpbuffersize = 0;
726
777
  size_t extrabuffersize = 0;
727
777
  int write_error = 0;
728
729
777
  jvirt_barray_ptr *coef_arrays = NULL;
730
777
  char marker_str[256];
731
777
  unsigned int marker_in_count, marker_in_size;
732
733
777
  int64_t in_image_size = 0;
734
777
  int64_t infilesize = 0;
735
777
  int64_t insize = 0, outsize = 0, lastsize = 0;
736
777
  int oldquality, searchdone;
737
777
  double ratio;
738
777
  size_t last_retry_size = 0;
739
777
  int retry_count = 0;
740
777
  int retry = 0;
741
777
  int ai_stripped = 0;
742
777
  int res = -1;
743
744
777
  jpeg_log_fh = log_fh;
745
777
  last_error[0] = 0;
746
747
  /* Initialize decompression object */
748
777
  dinfo.err = jpeg_std_error(&jderr.pub);
749
777
  jpeg_create_decompress(&dinfo);
750
777
  jderr.pub.error_exit=my_error_exit;
751
777
  jderr.pub.output_message=my_output_message;
752
777
  jderr.jump_set = 0;
753
754
  /* Initialize compression object */
755
777
  cinfo.err = jpeg_std_error(&jcerr.pub);
756
777
  jpeg_create_compress(&cinfo);
757
777
  jcerr.pub.error_exit=my_error_exit;
758
777
  jcerr.pub.output_message=my_output_message;
759
777
  jcerr.jump_set = 0;
760
761
777
  if (rate)
762
777
    *rate = 0.0;
763
777
  if (saved)
764
777
    *saved = 0.0;
765
766
777
  if (filename) {
767
777
    if ((infile = fopen(filename, "rb")) == NULL) {
768
0
      warn("cannot open file: %s", filename);
769
0
      res = 1;
770
0
      goto exit_point;
771
0
    }
772
777
    if ((infilesize = file_size(infile)) < 0) {
773
0
      fclose(infile);
774
0
      warn("failed to stat() input file: %s", filename);
775
0
      res = 1;
776
0
      goto exit_point;
777
0
    }
778
777
  } else {
779
0
    infile = stdin;
780
0
    set_filemode_binary(infile);
781
0
  }
782
783
1.08k
retry_point:
784
785
1.08k
  if (setjmp(jderr.setjmp_buffer)) {
786
    /* Error handler for decompress */
787
266
  abort_decompress:
788
266
    jpeg_abort_decompress(&dinfo);
789
266
    fclose(infile);
790
266
    free_line_buf(&buf, dinfo.output_height);
791
266
    if (!quiet_mode || csv)
792
266
      fprintf(log_fh,csv ? ",,,,,\"error: %s\"\n" : " [ERROR: %s]\n", last_error);
793
266
    jderr.jump_set=0;
794
266
    res = 1;
795
266
    goto exit_point;
796
818
  } else {
797
818
    jderr.jump_set=1;
798
818
  }
799
800
801
  /* Prepare to decompress */
802
818
  if (!retry) {
803
777
    if (!quiet_mode || csv) {
804
777
      if (csv) {
805
0
        fprint_csv_field(log_fh, (filename ? filename : "stdin"));
806
0
        fputc(',', log_fh);
807
777
      } else {
808
777
        fprintf(log_fh, "%s ", (filename ? filename : "stdin"));
809
777
      }
810
777
      fflush(log_fh);
811
777
    }
812
813
777
    if (stdin_mode || stdout_mode) {
814
0
      inbuffersize = IN_BUF_SIZE;
815
777
    } else {
816
777
      inbuffersize = (infilesize < IN_BUF_SIZE ? IN_BUF_SIZE : (size_t)infilesize);
817
777
    }
818
777
    if (inbuffer)
819
0
      free(inbuffer);
820
777
    if (!(inbuffer=calloc(inbuffersize, 1))) {
821
0
      strncopy(last_error, "not enough memory", sizeof(last_error));
822
0
      goto abort_decompress;
823
0
    }
824
777
  }
825
818
  global_error_counter=0;
826
818
  jpeg_save_markers(&dinfo, JPEG_COM, 0xffff);
827
18.1k
  for (int i = 0; i < 16; i++) {
828
17.3k
    jpeg_save_markers(&dinfo, JPEG_APP0 + i, 0xffff);
829
17.3k
  }
830
818
  if (!retry) {
831
777
    jpeg_custom_src(&dinfo, infile, &inbuffer, &inbuffersize, &inbufferused, IN_BUF_SIZE);
832
777
  } else {
833
    /* Only the --retry shrink loop (retry == 2) deliberately re-compresses
834
       its own previous output. The lossless fallback (retry == 1) and the
835
       auto-mode alternate pass (retry == 3) must start from the original
836
       image, as recompressing already lossy-compressed data would cause
837
       generation loss. */
838
41
    if (retry == 2)
839
0
      jpeg_custom_mem_src(&dinfo, tmpbuffer, tmpbuffersize);
840
41
    else
841
41
      jpeg_custom_mem_src(&dinfo, inbuffer, inbufferused);
842
41
  }
843
818
  jpeg_read_header(&dinfo, TRUE);
844
845
846
  /* Check for known (Exif, IPTC, ICC , XMP, ...) markers */
847
818
  marker_in_count = parse_markers(&dinfo, marker_str, sizeof(marker_str),
848
818
          &marker_in_size);
849
850
818
  if (!retry) {
851
700
    if (verbose_mode > 1) {
852
0
      fprintf(log_fh,"%d markers found in input file (total size %d bytes)\n",
853
0
        marker_in_count,marker_in_size);
854
0
      fprintf(log_fh,"coding: %s\n", (dinfo.arith_code == TRUE ? "Arithmetic" : "Huffman"));
855
0
    }
856
857
700
    if (!quiet_mode || csv) {
858
700
      fprintf(log_fh,csv ? "%dx%d,%dbit,%c," : "%dx%d %dbit %c ",(int)dinfo.image_width,
859
700
        (int)dinfo.image_height,(int)dinfo.num_components*8,
860
700
        (dinfo.progressive_mode?'P':'N'));
861
700
      if (!csv)
862
700
        fprintf(log_fh,"%s",marker_str);
863
700
      fflush(log_fh);
864
700
    }
865
700
  }
866
867
818
  if (max_pixels > 0) {
868
0
    if ((uint64_t)dinfo.image_width * dinfo.image_height > max_pixels) {
869
0
      strncopy(last_error, "too large input image", sizeof(last_error));
870
0
      goto abort_decompress;
871
0
    }
872
0
  }
873
874
  /* Decompress the image */
875
932
  if (quality >= 0 && retry != 1) {
876
625
    jpeg_start_decompress(&dinfo);
877
878
    /* Allocate line buffer to store the decompressed image */
879
625
    if (!(buf = calloc(dinfo.output_height, sizeof(JSAMPROW)))) {
880
0
      strncopy(last_error, "not enough memory", sizeof(last_error));
881
0
      goto abort_decompress;
882
0
    }
883
2.34M
    for (int i = 0; i < dinfo.output_height; i++) {
884
2.34M
      if (!(buf[i]=calloc((size_t)dinfo.output_width * dinfo.out_color_components,
885
2.34M
              sizeof(JSAMPLE)))) {
886
0
        strncopy(last_error, "not enough memory", sizeof(last_error));
887
0
        goto abort_decompress;
888
0
      }
889
2.34M
    }
890
891
1.02M
    while (dinfo.output_scanline < dinfo.output_height) {
892
1.02M
      jpeg_read_scanlines(&dinfo,&buf[dinfo.output_scanline],
893
1.02M
          dinfo.output_height-dinfo.output_scanline);
894
1.02M
    }
895
625
  } else {
896
193
    coef_arrays = jpeg_read_coefficients(&dinfo);
897
193
    if (!coef_arrays) {
898
0
      strncopy(last_error, "failed to read coefficients", sizeof(last_error));
899
0
      goto abort_decompress;
900
0
    }
901
193
  }
902
818
  if (strip_ai) {
903
    /* All the markers are known only after reading the whole image */
904
0
    int n = strip_ai_markers(&dinfo);
905
906
0
    if (n > 0) {
907
0
      if (verbose_mode && !retry)
908
0
        fprintf(log_fh, " (%d AI metadata removed) ", n);
909
0
      ai_stripped = 1;
910
0
    }
911
0
  }
912
818
  if (!retry) {
913
584
    in_image_size = inbufferused - dinfo.src->bytes_in_buffer;
914
584
    if(verbose_mode > 2)
915
0
      fprintf(log_fh, " (input image size: %"PRId64" (%ld))", in_image_size, inbufferused);
916
584
    if (stdin_mode) {
917
0
      insize = in_image_size;
918
584
    } else {
919
584
      insize = infilesize;
920
584
      if (in_image_size > 0 && in_image_size < insize) {
921
187
        if (!quiet_mode)
922
187
          fprintf(log_fh, " (%"PRId64" bytes extraneous data found after end of image) ",
923
187
            insize - in_image_size);
924
187
        if (nofix_mode)
925
0
          global_error_counter++;
926
187
        if (save_extra) {
927
0
          extrabuffersize = insize - in_image_size;
928
0
          if (extrabuffer)
929
0
            free(extrabuffer);
930
0
          if (!(extrabuffer = calloc(extrabuffersize, 1))) {
931
0
            strncopy(last_error, "not enough memory", sizeof(last_error));
932
0
            goto abort_decompress;
933
0
          }
934
0
          if (fseek(infile, in_image_size, SEEK_SET)) {
935
0
            strncopy(last_error, "failed to seek input file", sizeof(last_error));
936
0
            goto abort_decompress;
937
0
          }
938
0
          if (fread(extrabuffer, extrabuffersize, 1, infile) != 1) {
939
0
            strncopy(last_error, "failed to read input file", sizeof(last_error));
940
0
            goto abort_decompress;
941
0
          }
942
0
        }
943
187
      }
944
584
    }
945
584
    if (!quiet_mode) {
946
584
      fprintf(log_fh,(global_error_counter==0 ? " [OK] " : " [WARNING] "));
947
584
      fflush(log_fh);
948
584
    }
949
950
584
    if (nofix_mode && global_error_counter != 0) {
951
      /* Skip files containing any errors (or warnings) */
952
0
      strncopy(last_error, "skipped due to decoding errors", sizeof(last_error));
953
0
      goto abort_decompress;
954
0
    }
955
956
584
    if (dest && !noaction) {
957
0
      if (file_exists(newname) && !overwrite_mode) {
958
0
        strncopy(last_error, "target file already exists", sizeof(last_error));
959
0
        goto abort_decompress;
960
0
      }
961
0
    }
962
584
  }
963
964
965
  /* Prepare to compress... */
966
818
  if (setjmp(jcerr.setjmp_buffer)) {
967
174
  abort_compress:
968
    /* Error handler for compress failures */
969
174
    if (!quiet_mode)
970
174
      fprintf(log_fh," [Compress ERROR: %s]\n",last_error);
971
174
    jpeg_abort_compress(&cinfo);
972
174
    jpeg_abort_decompress(&dinfo);
973
174
    fclose(infile);
974
174
    free_line_buf(&buf, dinfo.output_height);
975
174
    jcerr.jump_set=0;
976
174
    res = 2;
977
174
    goto exit_point;
978
644
  } else {
979
644
    jcerr.jump_set=1;
980
644
  }
981
982
644
  lastsize = 0;
983
644
  searchdone = 0;
984
644
  if (!retry) {
985
584
    oldquality = 200;
986
584
    if (target_size != 0) {
987
      /* Always start with quality 100 if -S option specified... */
988
584
      quality = 100;
989
584
    }
990
584
  }
991
992
993
2.03k
binary_search_loop:
994
995
  /* Allocate memory buffer that should be large enough to store the output JPEG... */
996
2.03k
  if (outbuffer)
997
1.45k
    free(outbuffer);
998
2.03k
  outbuffersize = insize + 32768;
999
2.03k
  if (!(outbuffer=calloc(outbuffersize, 1))) {
1000
0
    warn("not enough memory");
1001
0
    strncopy(last_error, "not enough memory", sizeof(last_error));
1002
0
    goto abort_compress;
1003
0
  }
1004
1005
  /* setup custom "destination manager" for libjpeg to write to our buffer */
1006
2.03k
  jpeg_memory_dest(&cinfo, &outbuffer, &outbuffersize, 65536);
1007
1008
1009
2.03k
  if (quality >= 0 && retry != 1) {
1010
    /* Lossy "optimization" ... */
1011
1012
1.73k
    cinfo.in_color_space=dinfo.out_color_space;
1013
1.73k
    cinfo.input_components=dinfo.output_components;
1014
1.73k
    cinfo.image_width=dinfo.image_width;
1015
1.73k
    cinfo.image_height=dinfo.image_height;
1016
1.73k
    jpeg_set_defaults(&cinfo);
1017
1.73k
    jpeg_set_quality(&cinfo,quality,TRUE);
1018
#ifdef HAVE_JINT_DC_SCAN_OPT_MODE
1019
1.03k
    if (jpeg_c_int_param_supported(&cinfo, JINT_DC_SCAN_OPT_MODE))
1020
1.03k
      jpeg_c_set_int_param(&cinfo, JINT_DC_SCAN_OPT_MODE, 1);
1021
#endif
1022
1.73k
    if (all_normal || (!dinfo.progressive_mode && !all_progressive)) {
1023
      /* Explicitly disable progressive mode. */
1024
1.18k
      cinfo.scan_info = NULL;
1025
1.18k
      cinfo.num_scans = 0;
1026
1.18k
    } else if (all_progressive || dinfo.progressive_mode) {
1027
      /* Enable progressive mode. */
1028
542
      jpeg_simple_progression(&cinfo);
1029
542
    }
1030
1.73k
    cinfo.optimize_coding = TRUE;
1031
1.73k
#ifdef HAVE_ARITH_CODE
1032
1.73k
    if (arith_mode >= 0)
1033
0
      cinfo.arith_code = (arith_mode > 0 ? TRUE : FALSE);
1034
1.73k
#endif
1035
1.73k
    if (dinfo.saw_JFIF_marker && (save_jfif || strip_none)) {
1036
792
      cinfo.write_JFIF_header = TRUE;
1037
939
    } else {
1038
939
      cinfo.write_JFIF_header = FALSE;
1039
939
    }
1040
1.73k
    if (dinfo.saw_Adobe_marker && (save_adobe || strip_none)) {
1041
      /* If outputting Adobe marker, don't write JFIF marker... */
1042
0
      cinfo.write_JFIF_header = FALSE;
1043
0
    }
1044
1045
1.73k
    jpeg_start_compress(&cinfo,TRUE);
1046
1047
    /* Write markers */
1048
1.73k
    write_markers(&dinfo,&cinfo);
1049
1050
    /* Write image */
1051
3.45k
    while (cinfo.next_scanline < cinfo.image_height) {
1052
1.72k
      jpeg_write_scanlines(&cinfo,&buf[cinfo.next_scanline],
1053
1.72k
          cinfo.image_height - cinfo.next_scanline);
1054
1.72k
    }
1055
1056
1.73k
  } else {
1057
    /* Lossless optimization ... */
1058
1059
306
    jpeg_copy_critical_parameters(&dinfo, &cinfo);
1060
#ifdef HAVE_JINT_DC_SCAN_OPT_MODE
1061
288
    if (jpeg_c_int_param_supported(&cinfo, JINT_DC_SCAN_OPT_MODE))
1062
199
      jpeg_c_set_int_param(&cinfo, JINT_DC_SCAN_OPT_MODE, 1);
1063
#endif
1064
306
    if (all_normal || (!dinfo.progressive_mode && !all_progressive)) {
1065
      /* Explicitly disable progressive mode. */
1066
115
      cinfo.scan_info = NULL;
1067
115
      cinfo.num_scans = 0;
1068
191
    } else if (all_progressive || dinfo.progressive_mode) {
1069
      /* Enable progressive mode. */
1070
102
      jpeg_simple_progression(&cinfo);
1071
102
    }
1072
306
    cinfo.optimize_coding = TRUE;
1073
306
#ifdef HAVE_ARITH_CODE
1074
306
    if (arith_mode >= 0)
1075
0
      cinfo.arith_code = (arith_mode > 0 ? TRUE : FALSE);
1076
306
#endif
1077
306
    if (dinfo.saw_JFIF_marker && (save_jfif || strip_none)) {
1078
49
      cinfo.write_JFIF_header = TRUE;
1079
257
    } else {
1080
257
      cinfo.write_JFIF_header = FALSE;
1081
257
    }
1082
306
    if (dinfo.saw_Adobe_marker && (save_adobe || strip_none)) {
1083
      /* If outputting Adobe marker, don't write JFIF marker... */
1084
0
      cinfo.write_JFIF_header = FALSE;
1085
0
    }
1086
1087
    /* Write image */
1088
306
    jpeg_write_coefficients(&cinfo, coef_arrays);
1089
1090
    /* Write markers */
1091
306
    write_markers(&dinfo,&cinfo);
1092
1093
306
  }
1094
1095
2.03k
  jpeg_finish_compress(&cinfo);
1096
2.03k
  outsize = outbuffersize + extrabuffersize;
1097
2.03k
  if (verbose_mode > 2)
1098
0
    fprintf(log_fh, " (output image size: %"PRId64" (%lu))", outsize, extrabuffersize);
1099
1100
2.03k
  if (target_size != 0 && !retry) {
1101
    /* Perform (binary) search to try to reach target file size... */
1102
1103
1.71k
    int64_t osize = outsize/1024;
1104
1.71k
    int64_t isize = insize/1024;
1105
1.71k
    int64_t tsize = target_size;
1106
1107
1.71k
    if (verbose_mode > 1)
1108
0
      fprintf(log_fh, "(size=%"PRId64")",outsize);
1109
1.71k
    if (tsize < 0) {
1110
      /* 64-bit intermediate, as target_size * insize can overflow
1111
         a 32-bit long (files > ~21MB on ILP32/LLP64 platforms) */
1112
1.71k
      tsize = ((int64_t)(-target_size) * insize / 100) / 1024;
1113
1.71k
      if (tsize < 1)
1114
524
        tsize = 1;
1115
1.71k
    }
1116
1117
1.71k
    if (osize == tsize || searchdone || tsize > isize) {
1118
599
      if (searchdone < 42 && lastsize > 0) {
1119
302
        if (llabs(osize-tsize) > llabs(lastsize-tsize)) {
1120
32
          if (verbose_mode)
1121
0
            fprintf(log_fh,"(revert to %d)",oldquality);
1122
32
          searchdone = 42;
1123
32
          quality = oldquality;
1124
32
          goto binary_search_loop;
1125
32
        }
1126
302
      }
1127
567
      if (verbose_mode)
1128
0
        fprintf(log_fh," ");
1129
1130
1.11k
    } else {
1131
1.11k
      int newquality;
1132
1.11k
      double dif = abs(oldquality-quality) / 2.0;
1133
1134
1.11k
      if (osize > tsize)
1135
737
        newquality = quality - dif;
1136
378
      else
1137
378
        newquality = quality + dif + 0.5;
1138
1139
1.11k
      if (dif < 1.0)
1140
40
        searchdone = 1;
1141
1.11k
      if (newquality < 0) {
1142
71
        newquality = 0;
1143
71
        searchdone = 1;
1144
71
      }
1145
1.11k
      if (newquality > 100) {
1146
156
        newquality = 100;
1147
156
        searchdone = 1;
1148
156
      }
1149
1150
1.11k
      oldquality = quality;
1151
1.11k
      quality = newquality;
1152
1.11k
      lastsize = osize;
1153
1.11k
      if (verbose_mode)
1154
0
        fprintf(log_fh,"(try %d)",quality);
1155
1.11k
      goto binary_search_loop;
1156
1.11k
    }
1157
1.71k
  }
1158
1159
890
  jpeg_finish_decompress(&dinfo);
1160
890
  free_line_buf(&buf, dinfo.output_height);
1161
1162
890
  if (retry_mode) {
1163
0
    if ((retry == 0 || retry == 2) && quality >= 0 && outsize <= insize) {
1164
      /* Retry compression until output file stops getting smaller
1165
         or we hit max limit of iterations (10)... */
1166
0
      if (retry_count == 0)
1167
0
        last_retry_size = outsize + 1;
1168
0
      if (++retry_count < 10 && outsize < last_retry_size) {
1169
0
        if (tmpbuffer)
1170
0
          free(tmpbuffer);
1171
0
        tmpbuffer = outbuffer;
1172
0
        tmpbuffersize = outbuffersize;
1173
0
        outbuffer = NULL;
1174
0
        last_retry_size = outsize;
1175
0
        retry = 2;
1176
0
        if (verbose_mode)
1177
0
          fprintf(log_fh, "(retry%d: %"PRId64") ", retry_count, outsize);
1178
0
        goto retry_point;
1179
0
      }
1180
0
    }
1181
0
    if (retry == 2) {
1182
0
      if (verbose_mode)
1183
0
        fprintf(log_fh, "(retry done: %"PRId64") ", outsize);
1184
0
      if (outsize > last_retry_size) {
1185
0
        if (outbuffer)
1186
0
          free(outbuffer);
1187
0
        outbuffer = tmpbuffer;
1188
0
        outbuffersize = tmpbuffersize;
1189
0
        outsize = outbuffersize + extrabuffersize;
1190
0
        tmpbuffer = NULL;
1191
0
      }
1192
0
    }
1193
0
  }
1194
1195
  /* If auto_mode, try both progressive and non-progressive... */
1196
890
  if (auto_mode) {
1197
0
    int newmode = (dinfo.progressive_mode ? 0 : 1);
1198
0
    if (retry != 3) {
1199
0
      if (newmode)
1200
0
        all_progressive = 1;
1201
0
      else
1202
0
        all_normal = 1;
1203
0
      if (tmpbuffer)
1204
0
        free(tmpbuffer);
1205
0
      tmpbuffer = outbuffer;
1206
0
      tmpbuffersize = outbuffersize;
1207
0
      outbuffer = NULL;
1208
0
      last_retry_size = outsize;
1209
0
      retry = 3;
1210
0
      if (verbose_mode)
1211
0
        fprintf(log_fh, "(retry w/%s) ", (newmode ? "progressive" : "normal"));
1212
0
      goto retry_point;
1213
0
    } else {
1214
0
      if (verbose_mode > 1)
1215
0
        fprintf(log_fh, "(automode done: %"PRId64") ", outsize);
1216
0
      auto_mode = 0;
1217
0
      if (outsize > last_retry_size) {
1218
0
        if (verbose_mode)
1219
0
          fprintf(log_fh, "(revert to %s) ", (!newmode ? "progressive" : "normal"));
1220
0
        all_progressive = 0;
1221
0
        all_normal = 0;
1222
0
        if (outbuffer)
1223
0
          free(outbuffer);
1224
0
        outbuffer = tmpbuffer;
1225
0
        outbuffersize = tmpbuffersize;
1226
0
        outsize = outbuffersize + extrabuffersize;
1227
0
        tmpbuffer = NULL;
1228
0
      }
1229
0
    }
1230
0
  }
1231
1232
  /* In case "lossy" compression resulted larger file than original, retry with "lossless"... */
1233
890
  if (quality >= 0 && outsize >= insize && retry != 1) {
1234
307
    retry = 1;
1235
307
    if (verbose_mode)
1236
0
      fprintf(log_fh, "(retry w/lossless) ");
1237
307
    goto retry_point;
1238
307
  }
1239
1240
583
  fclose(infile);
1241
1242
583
  ratio = (insize - outsize) * 100.0 / insize;
1243
583
  if (!quiet_mode || csv)
1244
337
    fprintf(log_fh,csv ? "%"PRId64",%"PRId64",%0.2f," : "%"PRId64" --> %"PRId64" bytes (%0.2f%%), ",
1245
337
      insize, outsize, ratio);
1246
583
  if (rate) {
1247
337
    *rate = (ratio < 0 ? 0.0 : ratio);
1248
337
  }
1249
1250
  /* Removed AI metadata must not survive in the original file */
1251
583
  if ((outsize < insize && ratio >= threshold) || force || ai_stripped) {
1252
195
    if (saved) {
1253
195
      *saved = (insize - outsize) / 1024.0;
1254
195
    }
1255
195
    if (!quiet_mode || csv)
1256
195
      fprintf(log_fh,csv ? "optimized\n" : "optimized.\n");
1257
195
    if (noaction) {
1258
0
      res = 0;
1259
0
      goto exit_point;
1260
0
    }
1261
1262
195
    if (stdout_mode) {
1263
0
      outfname=NULL;
1264
0
      set_filemode_binary(stdout);
1265
0
      if (fwrite(outbuffer,outbuffersize,1,stdout) != 1)
1266
0
        fatal("%s, write failed to stdout",(stdin_mode ? "stdin" : filename));
1267
0
      if (save_extra && extrabuffersize > 0) {
1268
0
        if (fwrite(extrabuffer,extrabuffersize,1,stdout) != 1)
1269
0
          fatal("%s, write failed to stdout",(stdin_mode ? "stdin" : filename));
1270
0
      }
1271
195
    } else {
1272
195
      if (preserve_perms && !dest) {
1273
        /* make backup of the original file before overwriting it... */
1274
0
        int newlen = snprintf(tmpfilename, sizeof(tmpfilename),
1275
0
            "%s.jpegoptim.bak", newname);
1276
0
        if (newlen < 0 || (size_t)newlen >= sizeof(tmpfilename))
1277
0
          fatal("temp filename too long: %s", tmpfilename);
1278
1279
0
        if (verbose_mode > 1)
1280
0
          fprintf(log_fh,"%s, creating backup as: %s\n", filename, tmpfilename);
1281
0
        if (file_exists(tmpfilename))
1282
0
          fatal("%s, backup file already exists: %s", filename, tmpfilename);
1283
0
        if (copy_file(newname,tmpfilename))
1284
0
          fatal("%s, failed to create backup: %s", filename, tmpfilename);
1285
0
        if ((outfile=create_file(newname))==NULL)
1286
0
          fatal("%s, error opening output file: %s", filename, newname);
1287
0
        outfname = newname;
1288
195
      } else {
1289
195
        if (!(outfile = create_temp_file(tmpdir, "jpegoptim", tmpfilename, sizeof(tmpfilename))))
1290
0
          fatal("error creating temporary file: %s", tmpfilename);
1291
195
        outfname = tmpfilename;
1292
195
      }
1293
195
      int outfd = fileno(outfile);
1294
1295
      /* write "new" image to a file... */
1296
195
      if (verbose_mode > 1)
1297
0
        fprintf(log_fh,"writing %lu bytes to file: %s\n", outbuffersize, outfname);
1298
195
      if (fwrite(outbuffer, outbuffersize, 1, outfile) != 1) {
1299
0
        write_error = 1;
1300
195
      } else if (save_extra && extrabuffersize > 0) {
1301
0
        if (verbose_mode > 1)
1302
0
          fprintf(log_fh,"writing %lu bytes to file: %s\n", extrabuffersize, outfname);
1303
0
        if (fwrite(extrabuffer, extrabuffersize, 1, outfile) != 1)
1304
0
          write_error = 1;
1305
0
      }
1306
195
      if (fflush(outfile) != 0)
1307
0
        write_error = 1;
1308
1309
195
      if (!(preserve_perms && !dest) && !write_error) {
1310
        /* set file mode */
1311
195
        if (verbose_mode > 1)
1312
0
          fprintf(log_fh,"set file permissions same as in original: %s\n", outfname);
1313
195
        if (set_file_mode(outfd, outfname, file_stat->st_mode & 0777) != 0)
1314
0
          warn("failed to set output file mode");
1315
1316
        /* preserve file group (and owner if run by root) */
1317
195
        if (set_file_owner(outfd, outfname, (geteuid()==0 ? file_stat->st_uid : -1),
1318
195
               file_stat->st_gid) != 0)
1319
0
          warn("failed to reset output file group/owner");
1320
195
      }
1321
1322
195
      if (preserve_mtime && !write_error) {
1323
        /* preserve file modification time */
1324
0
        if (verbose_mode > 1)
1325
0
          fprintf(log_fh,"set file modification time same as in original: %s\n",
1326
0
            outfname);
1327
0
        if (set_file_times(outfd, outfname, file_stat) != 0)
1328
0
          warn("failed to reset output file time/date");
1329
0
      }
1330
1331
195
      if (fclose(outfile) != 0)
1332
0
        write_error = 1;
1333
1334
195
      if (write_error) {
1335
0
        if (preserve_perms && !dest) {
1336
          /* original file was truncated already, so restore it from the backup... */
1337
0
          warn("%s, write failed, restoring from backup: %s", filename, tmpfilename);
1338
0
          if (rename_file(tmpfilename, newname))
1339
0
            fatal("write failed to file: %s (failed to restore backup: %s)",
1340
0
              newname, tmpfilename);
1341
0
          if (set_file_mode(-1, newname, (file_stat->st_mode & 0777)) != 0)
1342
0
            warn("failed to restore file mode: %s", newname);
1343
0
          if (set_file_owner(-1, newname,
1344
0
                 (geteuid()==0 ? file_stat->st_uid : -1),
1345
0
                 file_stat->st_gid) != 0)
1346
0
            warn("failed to restore file group/owner: %s", newname);
1347
0
          fatal("write failed to file: %s (original restored)", newname);
1348
0
        }
1349
        /* remove the incomplete temporary file... */
1350
0
        delete_file(outfname);
1351
0
        fatal("write failed to temporary file: %s", outfname);
1352
0
      }
1353
1354
1355
195
      if (preserve_perms && !dest) {
1356
        /* original file was already replaced, remove backup... */
1357
0
        if (verbose_mode > 1)
1358
0
          fprintf(log_fh,"removing backup file: %s\n", tmpfilename);
1359
0
        if (delete_file(tmpfilename))
1360
0
          warn("failed to remove backup file: %s", tmpfilename);
1361
195
      } else {
1362
        /* make temp file to be the original file... */
1363
195
        if (verbose_mode > 1)
1364
0
          fprintf(log_fh,"renaming: %s to %s\n", outfname, newname);
1365
195
        if (rename_file(outfname, newname))
1366
0
          fatal("cannot rename temp file");
1367
195
      }
1368
195
    }
1369
388
  } else {
1370
388
    if (!quiet_mode || csv)
1371
142
      fprintf(log_fh,csv ? "skipped\n" : "skipped.\n");
1372
388
    if (stdout_mode) {
1373
0
      set_filemode_binary(stdout);
1374
0
      if (fwrite(inbuffer, in_image_size, 1, stdout) != 1)
1375
0
        fatal("%s, write failed to stdout",
1376
0
          (stdin_mode ? "stdin" : filename));
1377
0
    }
1378
388
  }
1379
1380
583
  res = 0;
1381
1382
777
 exit_point:
1383
777
  if (inbuffer)
1384
777
    free(inbuffer);
1385
777
  if (outbuffer)
1386
584
    free(outbuffer);
1387
777
  if (tmpbuffer)
1388
0
    free(tmpbuffer);
1389
777
  if (extrabuffer)
1390
0
    free(extrabuffer);
1391
777
  jpeg_destroy_compress(&cinfo);
1392
777
  jpeg_destroy_decompress(&dinfo);
1393
1394
777
  return res;
1395
583
}
optimize
Line
Count
Source
702
93
{
703
93
  FILE *infile = NULL;
704
93
  FILE *outfile = NULL;
705
93
  const char *outfname = NULL;
706
93
  char tmpfilename[MAXPATHLEN];
707
93
  struct jpeg_decompress_struct dinfo;
708
93
  struct jpeg_compress_struct cinfo;
709
93
  struct my_error_mgr jcerr, jderr;
710
711
  /* These buffers are (re)allocated between setjmp() and a possible
712
     longjmp() from the libjpeg error handlers, and then freed at
713
     exit_point after the jump. They must be volatile-qualified, as
714
     otherwise their values are indeterminate after longjmp()
715
     (C11 7.13.2.1), risking double-free or leak. */
716
93
  JSAMPARRAY volatile buf = NULL;
717
93
  unsigned char * volatile outbuffer = NULL;
718
93
  unsigned char * volatile inbuffer = NULL;
719
93
  unsigned char * volatile tmpbuffer = NULL;
720
93
  unsigned char * volatile extrabuffer = NULL;
721
722
93
  size_t outbuffersize = 0;
723
93
  size_t inbuffersize = 0;
724
93
  size_t inbufferused = 0;
725
93
  size_t tmpbuffersize = 0;
726
93
  size_t extrabuffersize = 0;
727
93
  int write_error = 0;
728
729
93
  jvirt_barray_ptr *coef_arrays = NULL;
730
93
  char marker_str[256];
731
93
  unsigned int marker_in_count, marker_in_size;
732
733
93
  int64_t in_image_size = 0;
734
93
  int64_t infilesize = 0;
735
93
  int64_t insize = 0, outsize = 0, lastsize = 0;
736
93
  int oldquality, searchdone;
737
93
  double ratio;
738
93
  size_t last_retry_size = 0;
739
93
  int retry_count = 0;
740
93
  int retry = 0;
741
93
  int ai_stripped = 0;
742
93
  int res = -1;
743
744
93
  jpeg_log_fh = log_fh;
745
93
  last_error[0] = 0;
746
747
  /* Initialize decompression object */
748
93
  dinfo.err = jpeg_std_error(&jderr.pub);
749
93
  jpeg_create_decompress(&dinfo);
750
93
  jderr.pub.error_exit=my_error_exit;
751
93
  jderr.pub.output_message=my_output_message;
752
93
  jderr.jump_set = 0;
753
754
  /* Initialize compression object */
755
93
  cinfo.err = jpeg_std_error(&jcerr.pub);
756
93
  jpeg_create_compress(&cinfo);
757
93
  jcerr.pub.error_exit=my_error_exit;
758
93
  jcerr.pub.output_message=my_output_message;
759
93
  jcerr.jump_set = 0;
760
761
93
  if (rate)
762
93
    *rate = 0.0;
763
93
  if (saved)
764
93
    *saved = 0.0;
765
766
93
  if (filename) {
767
93
    if ((infile = fopen(filename, "rb")) == NULL) {
768
0
      warn("cannot open file: %s", filename);
769
0
      res = 1;
770
0
      goto exit_point;
771
0
    }
772
93
    if ((infilesize = file_size(infile)) < 0) {
773
0
      fclose(infile);
774
0
      warn("failed to stat() input file: %s", filename);
775
0
      res = 1;
776
0
      goto exit_point;
777
0
    }
778
93
  } else {
779
0
    infile = stdin;
780
0
    set_filemode_binary(infile);
781
0
  }
782
783
102
retry_point:
784
785
102
  if (setjmp(jderr.setjmp_buffer)) {
786
    /* Error handler for decompress */
787
30
  abort_decompress:
788
30
    jpeg_abort_decompress(&dinfo);
789
30
    fclose(infile);
790
30
    free_line_buf(&buf, dinfo.output_height);
791
30
    if (!quiet_mode || csv)
792
30
      fprintf(log_fh,csv ? ",,,,,\"error: %s\"\n" : " [ERROR: %s]\n", last_error);
793
30
    jderr.jump_set=0;
794
30
    res = 1;
795
30
    goto exit_point;
796
72
  } else {
797
72
    jderr.jump_set=1;
798
72
  }
799
800
801
  /* Prepare to decompress */
802
93
  if (!retry) {
803
93
    if (!quiet_mode || csv) {
804
93
      if (csv) {
805
0
        fprint_csv_field(log_fh, (filename ? filename : "stdin"));
806
0
        fputc(',', log_fh);
807
93
      } else {
808
93
        fprintf(log_fh, "%s ", (filename ? filename : "stdin"));
809
93
      }
810
93
      fflush(log_fh);
811
93
    }
812
813
93
    if (stdin_mode || stdout_mode) {
814
0
      inbuffersize = IN_BUF_SIZE;
815
93
    } else {
816
93
      inbuffersize = (infilesize < IN_BUF_SIZE ? IN_BUF_SIZE : (size_t)infilesize);
817
93
    }
818
93
    if (inbuffer)
819
0
      free(inbuffer);
820
93
    if (!(inbuffer=calloc(inbuffersize, 1))) {
821
0
      strncopy(last_error, "not enough memory", sizeof(last_error));
822
0
      goto abort_decompress;
823
0
    }
824
93
  }
825
72
  global_error_counter=0;
826
72
  jpeg_save_markers(&dinfo, JPEG_COM, 0xffff);
827
1.70k
  for (int i = 0; i < 16; i++) {
828
1.63k
    jpeg_save_markers(&dinfo, JPEG_APP0 + i, 0xffff);
829
1.63k
  }
830
93
  if (!retry) {
831
93
    jpeg_custom_src(&dinfo, infile, &inbuffer, &inbuffersize, &inbufferused, IN_BUF_SIZE);
832
18.4E
  } else {
833
    /* Only the --retry shrink loop (retry == 2) deliberately re-compresses
834
       its own previous output. The lossless fallback (retry == 1) and the
835
       auto-mode alternate pass (retry == 3) must start from the original
836
       image, as recompressing already lossy-compressed data would cause
837
       generation loss. */
838
18.4E
    if (retry == 2)
839
0
      jpeg_custom_mem_src(&dinfo, tmpbuffer, tmpbuffersize);
840
18.4E
    else
841
18.4E
      jpeg_custom_mem_src(&dinfo, inbuffer, inbufferused);
842
18.4E
  }
843
72
  jpeg_read_header(&dinfo, TRUE);
844
845
846
  /* Check for known (Exif, IPTC, ICC , XMP, ...) markers */
847
72
  marker_in_count = parse_markers(&dinfo, marker_str, sizeof(marker_str),
848
72
          &marker_in_size);
849
850
84
  if (!retry) {
851
84
    if (verbose_mode > 1) {
852
0
      fprintf(log_fh,"%d markers found in input file (total size %d bytes)\n",
853
0
        marker_in_count,marker_in_size);
854
0
      fprintf(log_fh,"coding: %s\n", (dinfo.arith_code == TRUE ? "Arithmetic" : "Huffman"));
855
0
    }
856
857
84
    if (!quiet_mode || csv) {
858
84
      fprintf(log_fh,csv ? "%dx%d,%dbit,%c," : "%dx%d %dbit %c ",(int)dinfo.image_width,
859
84
        (int)dinfo.image_height,(int)dinfo.num_components*8,
860
84
        (dinfo.progressive_mode?'P':'N'));
861
84
      if (!csv)
862
84
        fprintf(log_fh,"%s",marker_str);
863
84
      fflush(log_fh);
864
84
    }
865
84
  }
866
867
72
  if (max_pixels > 0) {
868
0
    if ((uint64_t)dinfo.image_width * dinfo.image_height > max_pixels) {
869
0
      strncopy(last_error, "too large input image", sizeof(last_error));
870
0
      goto abort_decompress;
871
0
    }
872
0
  }
873
874
  /* Decompress the image */
875
91
  if (quality >= 0 && retry != 1) {
876
82
    jpeg_start_decompress(&dinfo);
877
878
    /* Allocate line buffer to store the decompressed image */
879
82
    if (!(buf = calloc(dinfo.output_height, sizeof(JSAMPROW)))) {
880
0
      strncopy(last_error, "not enough memory", sizeof(last_error));
881
0
      goto abort_decompress;
882
0
    }
883
156k
    for (int i = 0; i < dinfo.output_height; i++) {
884
156k
      if (!(buf[i]=calloc((size_t)dinfo.output_width * dinfo.out_color_components,
885
156k
              sizeof(JSAMPLE)))) {
886
0
        strncopy(last_error, "not enough memory", sizeof(last_error));
887
0
        goto abort_decompress;
888
0
      }
889
156k
    }
890
891
53.5k
    while (dinfo.output_scanline < dinfo.output_height) {
892
53.4k
      jpeg_read_scanlines(&dinfo,&buf[dinfo.output_scanline],
893
53.4k
          dinfo.output_height-dinfo.output_scanline);
894
53.4k
    }
895
18.4E
  } else {
896
18.4E
    coef_arrays = jpeg_read_coefficients(&dinfo);
897
18.4E
    if (!coef_arrays) {
898
0
      strncopy(last_error, "failed to read coefficients", sizeof(last_error));
899
0
      goto abort_decompress;
900
0
    }
901
18.4E
  }
902
72
  if (strip_ai) {
903
    /* All the markers are known only after reading the whole image */
904
0
    int n = strip_ai_markers(&dinfo);
905
906
0
    if (n > 0) {
907
0
      if (verbose_mode && !retry)
908
0
        fprintf(log_fh, " (%d AI metadata removed) ", n);
909
0
      ai_stripped = 1;
910
0
    }
911
0
  }
912
84
  if (!retry) {
913
84
    in_image_size = inbufferused - dinfo.src->bytes_in_buffer;
914
84
    if(verbose_mode > 2)
915
0
      fprintf(log_fh, " (input image size: %"PRId64" (%ld))", in_image_size, inbufferused);
916
84
    if (stdin_mode) {
917
0
      insize = in_image_size;
918
84
    } else {
919
84
      insize = infilesize;
920
84
      if (in_image_size > 0 && in_image_size < insize) {
921
56
        if (!quiet_mode)
922
56
          fprintf(log_fh, " (%"PRId64" bytes extraneous data found after end of image) ",
923
56
            insize - in_image_size);
924
56
        if (nofix_mode)
925
0
          global_error_counter++;
926
56
        if (save_extra) {
927
0
          extrabuffersize = insize - in_image_size;
928
0
          if (extrabuffer)
929
0
            free(extrabuffer);
930
0
          if (!(extrabuffer = calloc(extrabuffersize, 1))) {
931
0
            strncopy(last_error, "not enough memory", sizeof(last_error));
932
0
            goto abort_decompress;
933
0
          }
934
0
          if (fseek(infile, in_image_size, SEEK_SET)) {
935
0
            strncopy(last_error, "failed to seek input file", sizeof(last_error));
936
0
            goto abort_decompress;
937
0
          }
938
0
          if (fread(extrabuffer, extrabuffersize, 1, infile) != 1) {
939
0
            strncopy(last_error, "failed to read input file", sizeof(last_error));
940
0
            goto abort_decompress;
941
0
          }
942
0
        }
943
56
      }
944
84
    }
945
84
    if (!quiet_mode) {
946
84
      fprintf(log_fh,(global_error_counter==0 ? " [OK] " : " [WARNING] "));
947
84
      fflush(log_fh);
948
84
    }
949
950
84
    if (nofix_mode && global_error_counter != 0) {
951
      /* Skip files containing any errors (or warnings) */
952
0
      strncopy(last_error, "skipped due to decoding errors", sizeof(last_error));
953
0
      goto abort_decompress;
954
0
    }
955
956
84
    if (dest && !noaction) {
957
0
      if (file_exists(newname) && !overwrite_mode) {
958
0
        strncopy(last_error, "target file already exists", sizeof(last_error));
959
0
        goto abort_decompress;
960
0
      }
961
0
    }
962
84
  }
963
964
965
  /* Prepare to compress... */
966
72
  if (setjmp(jcerr.setjmp_buffer)) {
967
8
  abort_compress:
968
    /* Error handler for compress failures */
969
8
    if (!quiet_mode)
970
8
      fprintf(log_fh," [Compress ERROR: %s]\n",last_error);
971
8
    jpeg_abort_compress(&cinfo);
972
8
    jpeg_abort_decompress(&dinfo);
973
8
    fclose(infile);
974
8
    free_line_buf(&buf, dinfo.output_height);
975
8
    jcerr.jump_set=0;
976
8
    res = 2;
977
8
    goto exit_point;
978
64
  } else {
979
64
    jcerr.jump_set=1;
980
64
  }
981
982
64
  lastsize = 0;
983
64
  searchdone = 0;
984
84
  if (!retry) {
985
84
    oldquality = 200;
986
84
    if (target_size != 0) {
987
      /* Always start with quality 100 if -S option specified... */
988
84
      quality = 100;
989
84
    }
990
84
  }
991
992
993
356
binary_search_loop:
994
995
  /* Allocate memory buffer that should be large enough to store the output JPEG... */
996
356
  if (outbuffer)
997
272
    free(outbuffer);
998
356
  outbuffersize = insize + 32768;
999
356
  if (!(outbuffer=calloc(outbuffersize, 1))) {
1000
0
    warn("not enough memory");
1001
0
    strncopy(last_error, "not enough memory", sizeof(last_error));
1002
0
    goto abort_compress;
1003
0
  }
1004
1005
  /* setup custom "destination manager" for libjpeg to write to our buffer */
1006
356
  jpeg_memory_dest(&cinfo, &outbuffer, &outbuffersize, 65536);
1007
1008
1009
356
  if (quality >= 0 && retry != 1) {
1010
    /* Lossy "optimization" ... */
1011
1012
347
    cinfo.in_color_space=dinfo.out_color_space;
1013
347
    cinfo.input_components=dinfo.output_components;
1014
347
    cinfo.image_width=dinfo.image_width;
1015
347
    cinfo.image_height=dinfo.image_height;
1016
347
    jpeg_set_defaults(&cinfo);
1017
347
    jpeg_set_quality(&cinfo,quality,TRUE);
1018
#ifdef HAVE_JINT_DC_SCAN_OPT_MODE
1019
    if (jpeg_c_int_param_supported(&cinfo, JINT_DC_SCAN_OPT_MODE))
1020
      jpeg_c_set_int_param(&cinfo, JINT_DC_SCAN_OPT_MODE, 1);
1021
#endif
1022
347
    if (all_normal || (!dinfo.progressive_mode && !all_progressive)) {
1023
      /* Explicitly disable progressive mode. */
1024
291
      cinfo.scan_info = NULL;
1025
291
      cinfo.num_scans = 0;
1026
291
    } else if (all_progressive || dinfo.progressive_mode) {
1027
      /* Enable progressive mode. */
1028
56
      jpeg_simple_progression(&cinfo);
1029
56
    }
1030
347
    cinfo.optimize_coding = TRUE;
1031
347
#ifdef HAVE_ARITH_CODE
1032
347
    if (arith_mode >= 0)
1033
0
      cinfo.arith_code = (arith_mode > 0 ? TRUE : FALSE);
1034
347
#endif
1035
347
    if (dinfo.saw_JFIF_marker && (save_jfif || strip_none)) {
1036
209
      cinfo.write_JFIF_header = TRUE;
1037
209
    } else {
1038
138
      cinfo.write_JFIF_header = FALSE;
1039
138
    }
1040
347
    if (dinfo.saw_Adobe_marker && (save_adobe || strip_none)) {
1041
      /* If outputting Adobe marker, don't write JFIF marker... */
1042
0
      cinfo.write_JFIF_header = FALSE;
1043
0
    }
1044
1045
347
    jpeg_start_compress(&cinfo,TRUE);
1046
1047
    /* Write markers */
1048
347
    write_markers(&dinfo,&cinfo);
1049
1050
    /* Write image */
1051
692
    while (cinfo.next_scanline < cinfo.image_height) {
1052
345
      jpeg_write_scanlines(&cinfo,&buf[cinfo.next_scanline],
1053
345
          cinfo.image_height - cinfo.next_scanline);
1054
345
    }
1055
1056
347
  } else {
1057
    /* Lossless optimization ... */
1058
1059
9
    jpeg_copy_critical_parameters(&dinfo, &cinfo);
1060
#ifdef HAVE_JINT_DC_SCAN_OPT_MODE
1061
    if (jpeg_c_int_param_supported(&cinfo, JINT_DC_SCAN_OPT_MODE))
1062
      jpeg_c_set_int_param(&cinfo, JINT_DC_SCAN_OPT_MODE, 1);
1063
#endif
1064
9
    if (all_normal || (!dinfo.progressive_mode && !all_progressive)) {
1065
      /* Explicitly disable progressive mode. */
1066
9
      cinfo.scan_info = NULL;
1067
9
      cinfo.num_scans = 0;
1068
9
    } else if (all_progressive || dinfo.progressive_mode) {
1069
      /* Enable progressive mode. */
1070
0
      jpeg_simple_progression(&cinfo);
1071
0
    }
1072
9
    cinfo.optimize_coding = TRUE;
1073
9
#ifdef HAVE_ARITH_CODE
1074
9
    if (arith_mode >= 0)
1075
0
      cinfo.arith_code = (arith_mode > 0 ? TRUE : FALSE);
1076
9
#endif
1077
9
    if (dinfo.saw_JFIF_marker && (save_jfif || strip_none)) {
1078
8
      cinfo.write_JFIF_header = TRUE;
1079
8
    } else {
1080
1
      cinfo.write_JFIF_header = FALSE;
1081
1
    }
1082
9
    if (dinfo.saw_Adobe_marker && (save_adobe || strip_none)) {
1083
      /* If outputting Adobe marker, don't write JFIF marker... */
1084
0
      cinfo.write_JFIF_header = FALSE;
1085
0
    }
1086
1087
    /* Write image */
1088
9
    jpeg_write_coefficients(&cinfo, coef_arrays);
1089
1090
    /* Write markers */
1091
9
    write_markers(&dinfo,&cinfo);
1092
1093
9
  }
1094
1095
356
  jpeg_finish_compress(&cinfo);
1096
356
  outsize = outbuffersize + extrabuffersize;
1097
356
  if (verbose_mode > 2)
1098
0
    fprintf(log_fh, " (output image size: %"PRId64" (%lu))", outsize, extrabuffersize);
1099
1100
356
  if (target_size != 0 && !retry) {
1101
    /* Perform (binary) search to try to reach target file size... */
1102
1103
345
    int64_t osize = outsize/1024;
1104
345
    int64_t isize = insize/1024;
1105
345
    int64_t tsize = target_size;
1106
1107
345
    if (verbose_mode > 1)
1108
0
      fprintf(log_fh, "(size=%"PRId64")",outsize);
1109
345
    if (tsize < 0) {
1110
      /* 64-bit intermediate, as target_size * insize can overflow
1111
         a 32-bit long (files > ~21MB on ILP32/LLP64 platforms) */
1112
345
      tsize = ((int64_t)(-target_size) * insize / 100) / 1024;
1113
345
      if (tsize < 1)
1114
0
        tsize = 1;
1115
345
    }
1116
1117
345
    if (osize == tsize || searchdone || tsize > isize) {
1118
93
      if (searchdone < 42 && lastsize > 0) {
1119
82
        if (llabs(osize-tsize) > llabs(lastsize-tsize)) {
1120
11
          if (verbose_mode)
1121
0
            fprintf(log_fh,"(revert to %d)",oldquality);
1122
11
          searchdone = 42;
1123
11
          quality = oldquality;
1124
11
          goto binary_search_loop;
1125
11
        }
1126
82
      }
1127
82
      if (verbose_mode)
1128
0
        fprintf(log_fh," ");
1129
1130
252
    } else {
1131
252
      int newquality;
1132
252
      double dif = abs(oldquality-quality) / 2.0;
1133
1134
252
      if (osize > tsize)
1135
130
        newquality = quality - dif;
1136
122
      else
1137
122
        newquality = quality + dif + 0.5;
1138
1139
252
      if (dif < 1.0)
1140
15
        searchdone = 1;
1141
252
      if (newquality < 0) {
1142
7
        newquality = 0;
1143
7
        searchdone = 1;
1144
7
      }
1145
252
      if (newquality > 100) {
1146
50
        newquality = 100;
1147
50
        searchdone = 1;
1148
50
      }
1149
1150
252
      oldquality = quality;
1151
252
      quality = newquality;
1152
252
      lastsize = osize;
1153
252
      if (verbose_mode)
1154
0
        fprintf(log_fh,"(try %d)",quality);
1155
252
      goto binary_search_loop;
1156
252
    }
1157
345
  }
1158
1159
93
  jpeg_finish_decompress(&dinfo);
1160
93
  free_line_buf(&buf, dinfo.output_height);
1161
1162
93
  if (retry_mode) {
1163
0
    if ((retry == 0 || retry == 2) && quality >= 0 && outsize <= insize) {
1164
      /* Retry compression until output file stops getting smaller
1165
         or we hit max limit of iterations (10)... */
1166
0
      if (retry_count == 0)
1167
0
        last_retry_size = outsize + 1;
1168
0
      if (++retry_count < 10 && outsize < last_retry_size) {
1169
0
        if (tmpbuffer)
1170
0
          free(tmpbuffer);
1171
0
        tmpbuffer = outbuffer;
1172
0
        tmpbuffersize = outbuffersize;
1173
0
        outbuffer = NULL;
1174
0
        last_retry_size = outsize;
1175
0
        retry = 2;
1176
0
        if (verbose_mode)
1177
0
          fprintf(log_fh, "(retry%d: %"PRId64") ", retry_count, outsize);
1178
0
        goto retry_point;
1179
0
      }
1180
0
    }
1181
0
    if (retry == 2) {
1182
0
      if (verbose_mode)
1183
0
        fprintf(log_fh, "(retry done: %"PRId64") ", outsize);
1184
0
      if (outsize > last_retry_size) {
1185
0
        if (outbuffer)
1186
0
          free(outbuffer);
1187
0
        outbuffer = tmpbuffer;
1188
0
        outbuffersize = tmpbuffersize;
1189
0
        outsize = outbuffersize + extrabuffersize;
1190
0
        tmpbuffer = NULL;
1191
0
      }
1192
0
    }
1193
0
  }
1194
1195
  /* If auto_mode, try both progressive and non-progressive... */
1196
93
  if (auto_mode) {
1197
0
    int newmode = (dinfo.progressive_mode ? 0 : 1);
1198
0
    if (retry != 3) {
1199
0
      if (newmode)
1200
0
        all_progressive = 1;
1201
0
      else
1202
0
        all_normal = 1;
1203
0
      if (tmpbuffer)
1204
0
        free(tmpbuffer);
1205
0
      tmpbuffer = outbuffer;
1206
0
      tmpbuffersize = outbuffersize;
1207
0
      outbuffer = NULL;
1208
0
      last_retry_size = outsize;
1209
0
      retry = 3;
1210
0
      if (verbose_mode)
1211
0
        fprintf(log_fh, "(retry w/%s) ", (newmode ? "progressive" : "normal"));
1212
0
      goto retry_point;
1213
0
    } else {
1214
0
      if (verbose_mode > 1)
1215
0
        fprintf(log_fh, "(automode done: %"PRId64") ", outsize);
1216
0
      auto_mode = 0;
1217
0
      if (outsize > last_retry_size) {
1218
0
        if (verbose_mode)
1219
0
          fprintf(log_fh, "(revert to %s) ", (!newmode ? "progressive" : "normal"));
1220
0
        all_progressive = 0;
1221
0
        all_normal = 0;
1222
0
        if (outbuffer)
1223
0
          free(outbuffer);
1224
0
        outbuffer = tmpbuffer;
1225
0
        outbuffersize = tmpbuffersize;
1226
0
        outsize = outbuffersize + extrabuffersize;
1227
0
        tmpbuffer = NULL;
1228
0
      }
1229
0
    }
1230
0
  }
1231
1232
  /* In case "lossy" compression resulted larger file than original, retry with "lossless"... */
1233
93
  if (quality >= 0 && outsize >= insize && retry != 1) {
1234
9
    retry = 1;
1235
9
    if (verbose_mode)
1236
0
      fprintf(log_fh, "(retry w/lossless) ");
1237
9
    goto retry_point;
1238
9
  }
1239
1240
84
  fclose(infile);
1241
1242
84
  ratio = (insize - outsize) * 100.0 / insize;
1243
84
  if (!quiet_mode || csv)
1244
55
    fprintf(log_fh,csv ? "%"PRId64",%"PRId64",%0.2f," : "%"PRId64" --> %"PRId64" bytes (%0.2f%%), ",
1245
55
      insize, outsize, ratio);
1246
84
  if (rate) {
1247
55
    *rate = (ratio < 0 ? 0.0 : ratio);
1248
55
  }
1249
1250
  /* Removed AI metadata must not survive in the original file */
1251
84
  if ((outsize < insize && ratio >= threshold) || force || ai_stripped) {
1252
52
    if (saved) {
1253
52
      *saved = (insize - outsize) / 1024.0;
1254
52
    }
1255
52
    if (!quiet_mode || csv)
1256
52
      fprintf(log_fh,csv ? "optimized\n" : "optimized.\n");
1257
52
    if (noaction) {
1258
0
      res = 0;
1259
0
      goto exit_point;
1260
0
    }
1261
1262
52
    if (stdout_mode) {
1263
0
      outfname=NULL;
1264
0
      set_filemode_binary(stdout);
1265
0
      if (fwrite(outbuffer,outbuffersize,1,stdout) != 1)
1266
0
        fatal("%s, write failed to stdout",(stdin_mode ? "stdin" : filename));
1267
0
      if (save_extra && extrabuffersize > 0) {
1268
0
        if (fwrite(extrabuffer,extrabuffersize,1,stdout) != 1)
1269
0
          fatal("%s, write failed to stdout",(stdin_mode ? "stdin" : filename));
1270
0
      }
1271
52
    } else {
1272
52
      if (preserve_perms && !dest) {
1273
        /* make backup of the original file before overwriting it... */
1274
0
        int newlen = snprintf(tmpfilename, sizeof(tmpfilename),
1275
0
            "%s.jpegoptim.bak", newname);
1276
0
        if (newlen < 0 || (size_t)newlen >= sizeof(tmpfilename))
1277
0
          fatal("temp filename too long: %s", tmpfilename);
1278
1279
0
        if (verbose_mode > 1)
1280
0
          fprintf(log_fh,"%s, creating backup as: %s\n", filename, tmpfilename);
1281
0
        if (file_exists(tmpfilename))
1282
0
          fatal("%s, backup file already exists: %s", filename, tmpfilename);
1283
0
        if (copy_file(newname,tmpfilename))
1284
0
          fatal("%s, failed to create backup: %s", filename, tmpfilename);
1285
0
        if ((outfile=create_file(newname))==NULL)
1286
0
          fatal("%s, error opening output file: %s", filename, newname);
1287
0
        outfname = newname;
1288
52
      } else {
1289
52
        if (!(outfile = create_temp_file(tmpdir, "jpegoptim", tmpfilename, sizeof(tmpfilename))))
1290
0
          fatal("error creating temporary file: %s", tmpfilename);
1291
52
        outfname = tmpfilename;
1292
52
      }
1293
52
      int outfd = fileno(outfile);
1294
1295
      /* write "new" image to a file... */
1296
52
      if (verbose_mode > 1)
1297
0
        fprintf(log_fh,"writing %lu bytes to file: %s\n", outbuffersize, outfname);
1298
52
      if (fwrite(outbuffer, outbuffersize, 1, outfile) != 1) {
1299
0
        write_error = 1;
1300
52
      } else if (save_extra && extrabuffersize > 0) {
1301
0
        if (verbose_mode > 1)
1302
0
          fprintf(log_fh,"writing %lu bytes to file: %s\n", extrabuffersize, outfname);
1303
0
        if (fwrite(extrabuffer, extrabuffersize, 1, outfile) != 1)
1304
0
          write_error = 1;
1305
0
      }
1306
52
      if (fflush(outfile) != 0)
1307
0
        write_error = 1;
1308
1309
52
      if (!(preserve_perms && !dest) && !write_error) {
1310
        /* set file mode */
1311
52
        if (verbose_mode > 1)
1312
0
          fprintf(log_fh,"set file permissions same as in original: %s\n", outfname);
1313
52
        if (set_file_mode(outfd, outfname, file_stat->st_mode & 0777) != 0)
1314
0
          warn("failed to set output file mode");
1315
1316
        /* preserve file group (and owner if run by root) */
1317
52
        if (set_file_owner(outfd, outfname, (geteuid()==0 ? file_stat->st_uid : -1),
1318
52
               file_stat->st_gid) != 0)
1319
0
          warn("failed to reset output file group/owner");
1320
52
      }
1321
1322
52
      if (preserve_mtime && !write_error) {
1323
        /* preserve file modification time */
1324
0
        if (verbose_mode > 1)
1325
0
          fprintf(log_fh,"set file modification time same as in original: %s\n",
1326
0
            outfname);
1327
0
        if (set_file_times(outfd, outfname, file_stat) != 0)
1328
0
          warn("failed to reset output file time/date");
1329
0
      }
1330
1331
52
      if (fclose(outfile) != 0)
1332
0
        write_error = 1;
1333
1334
52
      if (write_error) {
1335
0
        if (preserve_perms && !dest) {
1336
          /* original file was truncated already, so restore it from the backup... */
1337
0
          warn("%s, write failed, restoring from backup: %s", filename, tmpfilename);
1338
0
          if (rename_file(tmpfilename, newname))
1339
0
            fatal("write failed to file: %s (failed to restore backup: %s)",
1340
0
              newname, tmpfilename);
1341
0
          if (set_file_mode(-1, newname, (file_stat->st_mode & 0777)) != 0)
1342
0
            warn("failed to restore file mode: %s", newname);
1343
0
          if (set_file_owner(-1, newname,
1344
0
                 (geteuid()==0 ? file_stat->st_uid : -1),
1345
0
                 file_stat->st_gid) != 0)
1346
0
            warn("failed to restore file group/owner: %s", newname);
1347
0
          fatal("write failed to file: %s (original restored)", newname);
1348
0
        }
1349
        /* remove the incomplete temporary file... */
1350
0
        delete_file(outfname);
1351
0
        fatal("write failed to temporary file: %s", outfname);
1352
0
      }
1353
1354
1355
52
      if (preserve_perms && !dest) {
1356
        /* original file was already replaced, remove backup... */
1357
0
        if (verbose_mode > 1)
1358
0
          fprintf(log_fh,"removing backup file: %s\n", tmpfilename);
1359
0
        if (delete_file(tmpfilename))
1360
0
          warn("failed to remove backup file: %s", tmpfilename);
1361
52
      } else {
1362
        /* make temp file to be the original file... */
1363
52
        if (verbose_mode > 1)
1364
0
          fprintf(log_fh,"renaming: %s to %s\n", outfname, newname);
1365
52
        if (rename_file(outfname, newname))
1366
0
          fatal("cannot rename temp file");
1367
52
      }
1368
52
    }
1369
52
  } else {
1370
32
    if (!quiet_mode || csv)
1371
3
      fprintf(log_fh,csv ? "skipped\n" : "skipped.\n");
1372
32
    if (stdout_mode) {
1373
0
      set_filemode_binary(stdout);
1374
0
      if (fwrite(inbuffer, in_image_size, 1, stdout) != 1)
1375
0
        fatal("%s, write failed to stdout",
1376
0
          (stdin_mode ? "stdin" : filename));
1377
0
    }
1378
32
  }
1379
1380
84
  res = 0;
1381
1382
93
 exit_point:
1383
93
  if (inbuffer)
1384
93
    free(inbuffer);
1385
93
  if (outbuffer)
1386
84
    free(outbuffer);
1387
93
  if (tmpbuffer)
1388
0
    free(tmpbuffer);
1389
93
  if (extrabuffer)
1390
0
    free(extrabuffer);
1391
93
  jpeg_destroy_compress(&cinfo);
1392
93
  jpeg_destroy_decompress(&dinfo);
1393
1394
93
  return res;
1395
84
}
optimize
Line
Count
Source
702
93
{
703
93
  FILE *infile = NULL;
704
93
  FILE *outfile = NULL;
705
93
  const char *outfname = NULL;
706
93
  char tmpfilename[MAXPATHLEN];
707
93
  struct jpeg_decompress_struct dinfo;
708
93
  struct jpeg_compress_struct cinfo;
709
93
  struct my_error_mgr jcerr, jderr;
710
711
  /* These buffers are (re)allocated between setjmp() and a possible
712
     longjmp() from the libjpeg error handlers, and then freed at
713
     exit_point after the jump. They must be volatile-qualified, as
714
     otherwise their values are indeterminate after longjmp()
715
     (C11 7.13.2.1), risking double-free or leak. */
716
93
  JSAMPARRAY volatile buf = NULL;
717
93
  unsigned char * volatile outbuffer = NULL;
718
93
  unsigned char * volatile inbuffer = NULL;
719
93
  unsigned char * volatile tmpbuffer = NULL;
720
93
  unsigned char * volatile extrabuffer = NULL;
721
722
93
  size_t outbuffersize = 0;
723
93
  size_t inbuffersize = 0;
724
93
  size_t inbufferused = 0;
725
93
  size_t tmpbuffersize = 0;
726
93
  size_t extrabuffersize = 0;
727
93
  int write_error = 0;
728
729
93
  jvirt_barray_ptr *coef_arrays = NULL;
730
93
  char marker_str[256];
731
93
  unsigned int marker_in_count, marker_in_size;
732
733
93
  int64_t in_image_size = 0;
734
93
  int64_t infilesize = 0;
735
93
  int64_t insize = 0, outsize = 0, lastsize = 0;
736
93
  int oldquality, searchdone;
737
93
  double ratio;
738
93
  size_t last_retry_size = 0;
739
93
  int retry_count = 0;
740
93
  int retry = 0;
741
93
  int ai_stripped = 0;
742
93
  int res = -1;
743
744
93
  jpeg_log_fh = log_fh;
745
93
  last_error[0] = 0;
746
747
  /* Initialize decompression object */
748
93
  dinfo.err = jpeg_std_error(&jderr.pub);
749
93
  jpeg_create_decompress(&dinfo);
750
93
  jderr.pub.error_exit=my_error_exit;
751
93
  jderr.pub.output_message=my_output_message;
752
93
  jderr.jump_set = 0;
753
754
  /* Initialize compression object */
755
93
  cinfo.err = jpeg_std_error(&jcerr.pub);
756
93
  jpeg_create_compress(&cinfo);
757
93
  jcerr.pub.error_exit=my_error_exit;
758
93
  jcerr.pub.output_message=my_output_message;
759
93
  jcerr.jump_set = 0;
760
761
93
  if (rate)
762
93
    *rate = 0.0;
763
93
  if (saved)
764
93
    *saved = 0.0;
765
766
93
  if (filename) {
767
93
    if ((infile = fopen(filename, "rb")) == NULL) {
768
0
      warn("cannot open file: %s", filename);
769
0
      res = 1;
770
0
      goto exit_point;
771
0
    }
772
93
    if ((infilesize = file_size(infile)) < 0) {
773
0
      fclose(infile);
774
0
      warn("failed to stat() input file: %s", filename);
775
0
      res = 1;
776
0
      goto exit_point;
777
0
    }
778
93
  } else {
779
0
    infile = stdin;
780
0
    set_filemode_binary(infile);
781
0
  }
782
783
102
retry_point:
784
785
102
  if (setjmp(jderr.setjmp_buffer)) {
786
    /* Error handler for decompress */
787
30
  abort_decompress:
788
30
    jpeg_abort_decompress(&dinfo);
789
30
    fclose(infile);
790
30
    free_line_buf(&buf, dinfo.output_height);
791
30
    if (!quiet_mode || csv)
792
30
      fprintf(log_fh,csv ? ",,,,,\"error: %s\"\n" : " [ERROR: %s]\n", last_error);
793
30
    jderr.jump_set=0;
794
30
    res = 1;
795
30
    goto exit_point;
796
72
  } else {
797
72
    jderr.jump_set=1;
798
72
  }
799
800
801
  /* Prepare to decompress */
802
93
  if (!retry) {
803
93
    if (!quiet_mode || csv) {
804
93
      if (csv) {
805
0
        fprint_csv_field(log_fh, (filename ? filename : "stdin"));
806
0
        fputc(',', log_fh);
807
93
      } else {
808
93
        fprintf(log_fh, "%s ", (filename ? filename : "stdin"));
809
93
      }
810
93
      fflush(log_fh);
811
93
    }
812
813
93
    if (stdin_mode || stdout_mode) {
814
0
      inbuffersize = IN_BUF_SIZE;
815
93
    } else {
816
93
      inbuffersize = (infilesize < IN_BUF_SIZE ? IN_BUF_SIZE : (size_t)infilesize);
817
93
    }
818
93
    if (inbuffer)
819
0
      free(inbuffer);
820
93
    if (!(inbuffer=calloc(inbuffersize, 1))) {
821
0
      strncopy(last_error, "not enough memory", sizeof(last_error));
822
0
      goto abort_decompress;
823
0
    }
824
93
  }
825
72
  global_error_counter=0;
826
72
  jpeg_save_markers(&dinfo, JPEG_COM, 0xffff);
827
1.70k
  for (int i = 0; i < 16; i++) {
828
1.63k
    jpeg_save_markers(&dinfo, JPEG_APP0 + i, 0xffff);
829
1.63k
  }
830
93
  if (!retry) {
831
93
    jpeg_custom_src(&dinfo, infile, &inbuffer, &inbuffersize, &inbufferused, IN_BUF_SIZE);
832
18.4E
  } else {
833
    /* Only the --retry shrink loop (retry == 2) deliberately re-compresses
834
       its own previous output. The lossless fallback (retry == 1) and the
835
       auto-mode alternate pass (retry == 3) must start from the original
836
       image, as recompressing already lossy-compressed data would cause
837
       generation loss. */
838
18.4E
    if (retry == 2)
839
0
      jpeg_custom_mem_src(&dinfo, tmpbuffer, tmpbuffersize);
840
18.4E
    else
841
18.4E
      jpeg_custom_mem_src(&dinfo, inbuffer, inbufferused);
842
18.4E
  }
843
72
  jpeg_read_header(&dinfo, TRUE);
844
845
846
  /* Check for known (Exif, IPTC, ICC , XMP, ...) markers */
847
72
  marker_in_count = parse_markers(&dinfo, marker_str, sizeof(marker_str),
848
72
          &marker_in_size);
849
850
84
  if (!retry) {
851
84
    if (verbose_mode > 1) {
852
0
      fprintf(log_fh,"%d markers found in input file (total size %d bytes)\n",
853
0
        marker_in_count,marker_in_size);
854
0
      fprintf(log_fh,"coding: %s\n", (dinfo.arith_code == TRUE ? "Arithmetic" : "Huffman"));
855
0
    }
856
857
84
    if (!quiet_mode || csv) {
858
84
      fprintf(log_fh,csv ? "%dx%d,%dbit,%c," : "%dx%d %dbit %c ",(int)dinfo.image_width,
859
84
        (int)dinfo.image_height,(int)dinfo.num_components*8,
860
84
        (dinfo.progressive_mode?'P':'N'));
861
84
      if (!csv)
862
84
        fprintf(log_fh,"%s",marker_str);
863
84
      fflush(log_fh);
864
84
    }
865
84
  }
866
867
72
  if (max_pixels > 0) {
868
0
    if ((uint64_t)dinfo.image_width * dinfo.image_height > max_pixels) {
869
0
      strncopy(last_error, "too large input image", sizeof(last_error));
870
0
      goto abort_decompress;
871
0
    }
872
0
  }
873
874
  /* Decompress the image */
875
91
  if (quality >= 0 && retry != 1) {
876
82
    jpeg_start_decompress(&dinfo);
877
878
    /* Allocate line buffer to store the decompressed image */
879
82
    if (!(buf = calloc(dinfo.output_height, sizeof(JSAMPROW)))) {
880
0
      strncopy(last_error, "not enough memory", sizeof(last_error));
881
0
      goto abort_decompress;
882
0
    }
883
156k
    for (int i = 0; i < dinfo.output_height; i++) {
884
156k
      if (!(buf[i]=calloc((size_t)dinfo.output_width * dinfo.out_color_components,
885
156k
              sizeof(JSAMPLE)))) {
886
0
        strncopy(last_error, "not enough memory", sizeof(last_error));
887
0
        goto abort_decompress;
888
0
      }
889
156k
    }
890
891
53.5k
    while (dinfo.output_scanline < dinfo.output_height) {
892
53.4k
      jpeg_read_scanlines(&dinfo,&buf[dinfo.output_scanline],
893
53.4k
          dinfo.output_height-dinfo.output_scanline);
894
53.4k
    }
895
18.4E
  } else {
896
18.4E
    coef_arrays = jpeg_read_coefficients(&dinfo);
897
18.4E
    if (!coef_arrays) {
898
0
      strncopy(last_error, "failed to read coefficients", sizeof(last_error));
899
0
      goto abort_decompress;
900
0
    }
901
18.4E
  }
902
72
  if (strip_ai) {
903
    /* All the markers are known only after reading the whole image */
904
0
    int n = strip_ai_markers(&dinfo);
905
906
0
    if (n > 0) {
907
0
      if (verbose_mode && !retry)
908
0
        fprintf(log_fh, " (%d AI metadata removed) ", n);
909
0
      ai_stripped = 1;
910
0
    }
911
0
  }
912
84
  if (!retry) {
913
84
    in_image_size = inbufferused - dinfo.src->bytes_in_buffer;
914
84
    if(verbose_mode > 2)
915
0
      fprintf(log_fh, " (input image size: %"PRId64" (%ld))", in_image_size, inbufferused);
916
84
    if (stdin_mode) {
917
0
      insize = in_image_size;
918
84
    } else {
919
84
      insize = infilesize;
920
84
      if (in_image_size > 0 && in_image_size < insize) {
921
56
        if (!quiet_mode)
922
56
          fprintf(log_fh, " (%"PRId64" bytes extraneous data found after end of image) ",
923
56
            insize - in_image_size);
924
56
        if (nofix_mode)
925
0
          global_error_counter++;
926
56
        if (save_extra) {
927
0
          extrabuffersize = insize - in_image_size;
928
0
          if (extrabuffer)
929
0
            free(extrabuffer);
930
0
          if (!(extrabuffer = calloc(extrabuffersize, 1))) {
931
0
            strncopy(last_error, "not enough memory", sizeof(last_error));
932
0
            goto abort_decompress;
933
0
          }
934
0
          if (fseek(infile, in_image_size, SEEK_SET)) {
935
0
            strncopy(last_error, "failed to seek input file", sizeof(last_error));
936
0
            goto abort_decompress;
937
0
          }
938
0
          if (fread(extrabuffer, extrabuffersize, 1, infile) != 1) {
939
0
            strncopy(last_error, "failed to read input file", sizeof(last_error));
940
0
            goto abort_decompress;
941
0
          }
942
0
        }
943
56
      }
944
84
    }
945
84
    if (!quiet_mode) {
946
84
      fprintf(log_fh,(global_error_counter==0 ? " [OK] " : " [WARNING] "));
947
84
      fflush(log_fh);
948
84
    }
949
950
84
    if (nofix_mode && global_error_counter != 0) {
951
      /* Skip files containing any errors (or warnings) */
952
0
      strncopy(last_error, "skipped due to decoding errors", sizeof(last_error));
953
0
      goto abort_decompress;
954
0
    }
955
956
84
    if (dest && !noaction) {
957
0
      if (file_exists(newname) && !overwrite_mode) {
958
0
        strncopy(last_error, "target file already exists", sizeof(last_error));
959
0
        goto abort_decompress;
960
0
      }
961
0
    }
962
84
  }
963
964
965
  /* Prepare to compress... */
966
72
  if (setjmp(jcerr.setjmp_buffer)) {
967
8
  abort_compress:
968
    /* Error handler for compress failures */
969
8
    if (!quiet_mode)
970
8
      fprintf(log_fh," [Compress ERROR: %s]\n",last_error);
971
8
    jpeg_abort_compress(&cinfo);
972
8
    jpeg_abort_decompress(&dinfo);
973
8
    fclose(infile);
974
8
    free_line_buf(&buf, dinfo.output_height);
975
8
    jcerr.jump_set=0;
976
8
    res = 2;
977
8
    goto exit_point;
978
64
  } else {
979
64
    jcerr.jump_set=1;
980
64
  }
981
982
64
  lastsize = 0;
983
64
  searchdone = 0;
984
84
  if (!retry) {
985
84
    oldquality = 200;
986
84
    if (target_size != 0) {
987
      /* Always start with quality 100 if -S option specified... */
988
84
      quality = 100;
989
84
    }
990
84
  }
991
992
993
356
binary_search_loop:
994
995
  /* Allocate memory buffer that should be large enough to store the output JPEG... */
996
356
  if (outbuffer)
997
272
    free(outbuffer);
998
356
  outbuffersize = insize + 32768;
999
356
  if (!(outbuffer=calloc(outbuffersize, 1))) {
1000
0
    warn("not enough memory");
1001
0
    strncopy(last_error, "not enough memory", sizeof(last_error));
1002
0
    goto abort_compress;
1003
0
  }
1004
1005
  /* setup custom "destination manager" for libjpeg to write to our buffer */
1006
356
  jpeg_memory_dest(&cinfo, &outbuffer, &outbuffersize, 65536);
1007
1008
1009
356
  if (quality >= 0 && retry != 1) {
1010
    /* Lossy "optimization" ... */
1011
1012
347
    cinfo.in_color_space=dinfo.out_color_space;
1013
347
    cinfo.input_components=dinfo.output_components;
1014
347
    cinfo.image_width=dinfo.image_width;
1015
347
    cinfo.image_height=dinfo.image_height;
1016
347
    jpeg_set_defaults(&cinfo);
1017
347
    jpeg_set_quality(&cinfo,quality,TRUE);
1018
#ifdef HAVE_JINT_DC_SCAN_OPT_MODE
1019
    if (jpeg_c_int_param_supported(&cinfo, JINT_DC_SCAN_OPT_MODE))
1020
      jpeg_c_set_int_param(&cinfo, JINT_DC_SCAN_OPT_MODE, 1);
1021
#endif
1022
347
    if (all_normal || (!dinfo.progressive_mode && !all_progressive)) {
1023
      /* Explicitly disable progressive mode. */
1024
291
      cinfo.scan_info = NULL;
1025
291
      cinfo.num_scans = 0;
1026
291
    } else if (all_progressive || dinfo.progressive_mode) {
1027
      /* Enable progressive mode. */
1028
56
      jpeg_simple_progression(&cinfo);
1029
56
    }
1030
347
    cinfo.optimize_coding = TRUE;
1031
347
#ifdef HAVE_ARITH_CODE
1032
347
    if (arith_mode >= 0)
1033
0
      cinfo.arith_code = (arith_mode > 0 ? TRUE : FALSE);
1034
347
#endif
1035
347
    if (dinfo.saw_JFIF_marker && (save_jfif || strip_none)) {
1036
209
      cinfo.write_JFIF_header = TRUE;
1037
209
    } else {
1038
138
      cinfo.write_JFIF_header = FALSE;
1039
138
    }
1040
347
    if (dinfo.saw_Adobe_marker && (save_adobe || strip_none)) {
1041
      /* If outputting Adobe marker, don't write JFIF marker... */
1042
0
      cinfo.write_JFIF_header = FALSE;
1043
0
    }
1044
1045
347
    jpeg_start_compress(&cinfo,TRUE);
1046
1047
    /* Write markers */
1048
347
    write_markers(&dinfo,&cinfo);
1049
1050
    /* Write image */
1051
692
    while (cinfo.next_scanline < cinfo.image_height) {
1052
345
      jpeg_write_scanlines(&cinfo,&buf[cinfo.next_scanline],
1053
345
          cinfo.image_height - cinfo.next_scanline);
1054
345
    }
1055
1056
347
  } else {
1057
    /* Lossless optimization ... */
1058
1059
9
    jpeg_copy_critical_parameters(&dinfo, &cinfo);
1060
#ifdef HAVE_JINT_DC_SCAN_OPT_MODE
1061
    if (jpeg_c_int_param_supported(&cinfo, JINT_DC_SCAN_OPT_MODE))
1062
      jpeg_c_set_int_param(&cinfo, JINT_DC_SCAN_OPT_MODE, 1);
1063
#endif
1064
9
    if (all_normal || (!dinfo.progressive_mode && !all_progressive)) {
1065
      /* Explicitly disable progressive mode. */
1066
9
      cinfo.scan_info = NULL;
1067
9
      cinfo.num_scans = 0;
1068
9
    } else if (all_progressive || dinfo.progressive_mode) {
1069
      /* Enable progressive mode. */
1070
0
      jpeg_simple_progression(&cinfo);
1071
0
    }
1072
9
    cinfo.optimize_coding = TRUE;
1073
9
#ifdef HAVE_ARITH_CODE
1074
9
    if (arith_mode >= 0)
1075
0
      cinfo.arith_code = (arith_mode > 0 ? TRUE : FALSE);
1076
9
#endif
1077
9
    if (dinfo.saw_JFIF_marker && (save_jfif || strip_none)) {
1078
8
      cinfo.write_JFIF_header = TRUE;
1079
8
    } else {
1080
1
      cinfo.write_JFIF_header = FALSE;
1081
1
    }
1082
9
    if (dinfo.saw_Adobe_marker && (save_adobe || strip_none)) {
1083
      /* If outputting Adobe marker, don't write JFIF marker... */
1084
0
      cinfo.write_JFIF_header = FALSE;
1085
0
    }
1086
1087
    /* Write image */
1088
9
    jpeg_write_coefficients(&cinfo, coef_arrays);
1089
1090
    /* Write markers */
1091
9
    write_markers(&dinfo,&cinfo);
1092
1093
9
  }
1094
1095
356
  jpeg_finish_compress(&cinfo);
1096
356
  outsize = outbuffersize + extrabuffersize;
1097
356
  if (verbose_mode > 2)
1098
0
    fprintf(log_fh, " (output image size: %"PRId64" (%lu))", outsize, extrabuffersize);
1099
1100
356
  if (target_size != 0 && !retry) {
1101
    /* Perform (binary) search to try to reach target file size... */
1102
1103
345
    int64_t osize = outsize/1024;
1104
345
    int64_t isize = insize/1024;
1105
345
    int64_t tsize = target_size;
1106
1107
345
    if (verbose_mode > 1)
1108
0
      fprintf(log_fh, "(size=%"PRId64")",outsize);
1109
345
    if (tsize < 0) {
1110
      /* 64-bit intermediate, as target_size * insize can overflow
1111
         a 32-bit long (files > ~21MB on ILP32/LLP64 platforms) */
1112
345
      tsize = ((int64_t)(-target_size) * insize / 100) / 1024;
1113
345
      if (tsize < 1)
1114
0
        tsize = 1;
1115
345
    }
1116
1117
345
    if (osize == tsize || searchdone || tsize > isize) {
1118
93
      if (searchdone < 42 && lastsize > 0) {
1119
82
        if (llabs(osize-tsize) > llabs(lastsize-tsize)) {
1120
11
          if (verbose_mode)
1121
0
            fprintf(log_fh,"(revert to %d)",oldquality);
1122
11
          searchdone = 42;
1123
11
          quality = oldquality;
1124
11
          goto binary_search_loop;
1125
11
        }
1126
82
      }
1127
82
      if (verbose_mode)
1128
0
        fprintf(log_fh," ");
1129
1130
252
    } else {
1131
252
      int newquality;
1132
252
      double dif = abs(oldquality-quality) / 2.0;
1133
1134
252
      if (osize > tsize)
1135
130
        newquality = quality - dif;
1136
122
      else
1137
122
        newquality = quality + dif + 0.5;
1138
1139
252
      if (dif < 1.0)
1140
15
        searchdone = 1;
1141
252
      if (newquality < 0) {
1142
7
        newquality = 0;
1143
7
        searchdone = 1;
1144
7
      }
1145
252
      if (newquality > 100) {
1146
50
        newquality = 100;
1147
50
        searchdone = 1;
1148
50
      }
1149
1150
252
      oldquality = quality;
1151
252
      quality = newquality;
1152
252
      lastsize = osize;
1153
252
      if (verbose_mode)
1154
0
        fprintf(log_fh,"(try %d)",quality);
1155
252
      goto binary_search_loop;
1156
252
    }
1157
345
  }
1158
1159
93
  jpeg_finish_decompress(&dinfo);
1160
93
  free_line_buf(&buf, dinfo.output_height);
1161
1162
93
  if (retry_mode) {
1163
0
    if ((retry == 0 || retry == 2) && quality >= 0 && outsize <= insize) {
1164
      /* Retry compression until output file stops getting smaller
1165
         or we hit max limit of iterations (10)... */
1166
0
      if (retry_count == 0)
1167
0
        last_retry_size = outsize + 1;
1168
0
      if (++retry_count < 10 && outsize < last_retry_size) {
1169
0
        if (tmpbuffer)
1170
0
          free(tmpbuffer);
1171
0
        tmpbuffer = outbuffer;
1172
0
        tmpbuffersize = outbuffersize;
1173
0
        outbuffer = NULL;
1174
0
        last_retry_size = outsize;
1175
0
        retry = 2;
1176
0
        if (verbose_mode)
1177
0
          fprintf(log_fh, "(retry%d: %"PRId64") ", retry_count, outsize);
1178
0
        goto retry_point;
1179
0
      }
1180
0
    }
1181
0
    if (retry == 2) {
1182
0
      if (verbose_mode)
1183
0
        fprintf(log_fh, "(retry done: %"PRId64") ", outsize);
1184
0
      if (outsize > last_retry_size) {
1185
0
        if (outbuffer)
1186
0
          free(outbuffer);
1187
0
        outbuffer = tmpbuffer;
1188
0
        outbuffersize = tmpbuffersize;
1189
0
        outsize = outbuffersize + extrabuffersize;
1190
0
        tmpbuffer = NULL;
1191
0
      }
1192
0
    }
1193
0
  }
1194
1195
  /* If auto_mode, try both progressive and non-progressive... */
1196
93
  if (auto_mode) {
1197
0
    int newmode = (dinfo.progressive_mode ? 0 : 1);
1198
0
    if (retry != 3) {
1199
0
      if (newmode)
1200
0
        all_progressive = 1;
1201
0
      else
1202
0
        all_normal = 1;
1203
0
      if (tmpbuffer)
1204
0
        free(tmpbuffer);
1205
0
      tmpbuffer = outbuffer;
1206
0
      tmpbuffersize = outbuffersize;
1207
0
      outbuffer = NULL;
1208
0
      last_retry_size = outsize;
1209
0
      retry = 3;
1210
0
      if (verbose_mode)
1211
0
        fprintf(log_fh, "(retry w/%s) ", (newmode ? "progressive" : "normal"));
1212
0
      goto retry_point;
1213
0
    } else {
1214
0
      if (verbose_mode > 1)
1215
0
        fprintf(log_fh, "(automode done: %"PRId64") ", outsize);
1216
0
      auto_mode = 0;
1217
0
      if (outsize > last_retry_size) {
1218
0
        if (verbose_mode)
1219
0
          fprintf(log_fh, "(revert to %s) ", (!newmode ? "progressive" : "normal"));
1220
0
        all_progressive = 0;
1221
0
        all_normal = 0;
1222
0
        if (outbuffer)
1223
0
          free(outbuffer);
1224
0
        outbuffer = tmpbuffer;
1225
0
        outbuffersize = tmpbuffersize;
1226
0
        outsize = outbuffersize + extrabuffersize;
1227
0
        tmpbuffer = NULL;
1228
0
      }
1229
0
    }
1230
0
  }
1231
1232
  /* In case "lossy" compression resulted larger file than original, retry with "lossless"... */
1233
93
  if (quality >= 0 && outsize >= insize && retry != 1) {
1234
9
    retry = 1;
1235
9
    if (verbose_mode)
1236
0
      fprintf(log_fh, "(retry w/lossless) ");
1237
9
    goto retry_point;
1238
9
  }
1239
1240
84
  fclose(infile);
1241
1242
84
  ratio = (insize - outsize) * 100.0 / insize;
1243
84
  if (!quiet_mode || csv)
1244
55
    fprintf(log_fh,csv ? "%"PRId64",%"PRId64",%0.2f," : "%"PRId64" --> %"PRId64" bytes (%0.2f%%), ",
1245
55
      insize, outsize, ratio);
1246
84
  if (rate) {
1247
55
    *rate = (ratio < 0 ? 0.0 : ratio);
1248
55
  }
1249
1250
  /* Removed AI metadata must not survive in the original file */
1251
84
  if ((outsize < insize && ratio >= threshold) || force || ai_stripped) {
1252
52
    if (saved) {
1253
52
      *saved = (insize - outsize) / 1024.0;
1254
52
    }
1255
52
    if (!quiet_mode || csv)
1256
52
      fprintf(log_fh,csv ? "optimized\n" : "optimized.\n");
1257
52
    if (noaction) {
1258
0
      res = 0;
1259
0
      goto exit_point;
1260
0
    }
1261
1262
52
    if (stdout_mode) {
1263
0
      outfname=NULL;
1264
0
      set_filemode_binary(stdout);
1265
0
      if (fwrite(outbuffer,outbuffersize,1,stdout) != 1)
1266
0
        fatal("%s, write failed to stdout",(stdin_mode ? "stdin" : filename));
1267
0
      if (save_extra && extrabuffersize > 0) {
1268
0
        if (fwrite(extrabuffer,extrabuffersize,1,stdout) != 1)
1269
0
          fatal("%s, write failed to stdout",(stdin_mode ? "stdin" : filename));
1270
0
      }
1271
52
    } else {
1272
52
      if (preserve_perms && !dest) {
1273
        /* make backup of the original file before overwriting it... */
1274
0
        int newlen = snprintf(tmpfilename, sizeof(tmpfilename),
1275
0
            "%s.jpegoptim.bak", newname);
1276
0
        if (newlen < 0 || (size_t)newlen >= sizeof(tmpfilename))
1277
0
          fatal("temp filename too long: %s", tmpfilename);
1278
1279
0
        if (verbose_mode > 1)
1280
0
          fprintf(log_fh,"%s, creating backup as: %s\n", filename, tmpfilename);
1281
0
        if (file_exists(tmpfilename))
1282
0
          fatal("%s, backup file already exists: %s", filename, tmpfilename);
1283
0
        if (copy_file(newname,tmpfilename))
1284
0
          fatal("%s, failed to create backup: %s", filename, tmpfilename);
1285
0
        if ((outfile=create_file(newname))==NULL)
1286
0
          fatal("%s, error opening output file: %s", filename, newname);
1287
0
        outfname = newname;
1288
52
      } else {
1289
52
        if (!(outfile = create_temp_file(tmpdir, "jpegoptim", tmpfilename, sizeof(tmpfilename))))
1290
0
          fatal("error creating temporary file: %s", tmpfilename);
1291
52
        outfname = tmpfilename;
1292
52
      }
1293
52
      int outfd = fileno(outfile);
1294
1295
      /* write "new" image to a file... */
1296
52
      if (verbose_mode > 1)
1297
0
        fprintf(log_fh,"writing %lu bytes to file: %s\n", outbuffersize, outfname);
1298
52
      if (fwrite(outbuffer, outbuffersize, 1, outfile) != 1) {
1299
0
        write_error = 1;
1300
52
      } else if (save_extra && extrabuffersize > 0) {
1301
0
        if (verbose_mode > 1)
1302
0
          fprintf(log_fh,"writing %lu bytes to file: %s\n", extrabuffersize, outfname);
1303
0
        if (fwrite(extrabuffer, extrabuffersize, 1, outfile) != 1)
1304
0
          write_error = 1;
1305
0
      }
1306
52
      if (fflush(outfile) != 0)
1307
0
        write_error = 1;
1308
1309
52
      if (!(preserve_perms && !dest) && !write_error) {
1310
        /* set file mode */
1311
52
        if (verbose_mode > 1)
1312
0
          fprintf(log_fh,"set file permissions same as in original: %s\n", outfname);
1313
52
        if (set_file_mode(outfd, outfname, file_stat->st_mode & 0777) != 0)
1314
0
          warn("failed to set output file mode");
1315
1316
        /* preserve file group (and owner if run by root) */
1317
52
        if (set_file_owner(outfd, outfname, (geteuid()==0 ? file_stat->st_uid : -1),
1318
52
               file_stat->st_gid) != 0)
1319
0
          warn("failed to reset output file group/owner");
1320
52
      }
1321
1322
52
      if (preserve_mtime && !write_error) {
1323
        /* preserve file modification time */
1324
0
        if (verbose_mode > 1)
1325
0
          fprintf(log_fh,"set file modification time same as in original: %s\n",
1326
0
            outfname);
1327
0
        if (set_file_times(outfd, outfname, file_stat) != 0)
1328
0
          warn("failed to reset output file time/date");
1329
0
      }
1330
1331
52
      if (fclose(outfile) != 0)
1332
0
        write_error = 1;
1333
1334
52
      if (write_error) {
1335
0
        if (preserve_perms && !dest) {
1336
          /* original file was truncated already, so restore it from the backup... */
1337
0
          warn("%s, write failed, restoring from backup: %s", filename, tmpfilename);
1338
0
          if (rename_file(tmpfilename, newname))
1339
0
            fatal("write failed to file: %s (failed to restore backup: %s)",
1340
0
              newname, tmpfilename);
1341
0
          if (set_file_mode(-1, newname, (file_stat->st_mode & 0777)) != 0)
1342
0
            warn("failed to restore file mode: %s", newname);
1343
0
          if (set_file_owner(-1, newname,
1344
0
                 (geteuid()==0 ? file_stat->st_uid : -1),
1345
0
                 file_stat->st_gid) != 0)
1346
0
            warn("failed to restore file group/owner: %s", newname);
1347
0
          fatal("write failed to file: %s (original restored)", newname);
1348
0
        }
1349
        /* remove the incomplete temporary file... */
1350
0
        delete_file(outfname);
1351
0
        fatal("write failed to temporary file: %s", outfname);
1352
0
      }
1353
1354
1355
52
      if (preserve_perms && !dest) {
1356
        /* original file was already replaced, remove backup... */
1357
0
        if (verbose_mode > 1)
1358
0
          fprintf(log_fh,"removing backup file: %s\n", tmpfilename);
1359
0
        if (delete_file(tmpfilename))
1360
0
          warn("failed to remove backup file: %s", tmpfilename);
1361
52
      } else {
1362
        /* make temp file to be the original file... */
1363
52
        if (verbose_mode > 1)
1364
0
          fprintf(log_fh,"renaming: %s to %s\n", outfname, newname);
1365
52
        if (rename_file(outfname, newname))
1366
0
          fatal("cannot rename temp file");
1367
52
      }
1368
52
    }
1369
52
  } else {
1370
32
    if (!quiet_mode || csv)
1371
3
      fprintf(log_fh,csv ? "skipped\n" : "skipped.\n");
1372
32
    if (stdout_mode) {
1373
0
      set_filemode_binary(stdout);
1374
0
      if (fwrite(inbuffer, in_image_size, 1, stdout) != 1)
1375
0
        fatal("%s, write failed to stdout",
1376
0
          (stdin_mode ? "stdin" : filename));
1377
0
    }
1378
32
  }
1379
1380
84
  res = 0;
1381
1382
93
 exit_point:
1383
93
  if (inbuffer)
1384
93
    free(inbuffer);
1385
93
  if (outbuffer)
1386
84
    free(outbuffer);
1387
93
  if (tmpbuffer)
1388
0
    free(tmpbuffer);
1389
93
  if (extrabuffer)
1390
0
    free(extrabuffer);
1391
93
  jpeg_destroy_compress(&cinfo);
1392
93
  jpeg_destroy_decompress(&dinfo);
1393
1394
93
  return res;
1395
84
}
optimize
Line
Count
Source
702
591
{
703
591
  FILE *infile = NULL;
704
591
  FILE *outfile = NULL;
705
591
  const char *outfname = NULL;
706
591
  char tmpfilename[MAXPATHLEN];
707
591
  struct jpeg_decompress_struct dinfo;
708
591
  struct jpeg_compress_struct cinfo;
709
591
  struct my_error_mgr jcerr, jderr;
710
711
  /* These buffers are (re)allocated between setjmp() and a possible
712
     longjmp() from the libjpeg error handlers, and then freed at
713
     exit_point after the jump. They must be volatile-qualified, as
714
     otherwise their values are indeterminate after longjmp()
715
     (C11 7.13.2.1), risking double-free or leak. */
716
591
  JSAMPARRAY volatile buf = NULL;
717
591
  unsigned char * volatile outbuffer = NULL;
718
591
  unsigned char * volatile inbuffer = NULL;
719
591
  unsigned char * volatile tmpbuffer = NULL;
720
591
  unsigned char * volatile extrabuffer = NULL;
721
722
591
  size_t outbuffersize = 0;
723
591
  size_t inbuffersize = 0;
724
591
  size_t inbufferused = 0;
725
591
  size_t tmpbuffersize = 0;
726
591
  size_t extrabuffersize = 0;
727
591
  int write_error = 0;
728
729
591
  jvirt_barray_ptr *coef_arrays = NULL;
730
591
  char marker_str[256];
731
591
  unsigned int marker_in_count, marker_in_size;
732
733
591
  int64_t in_image_size = 0;
734
591
  int64_t infilesize = 0;
735
591
  int64_t insize = 0, outsize = 0, lastsize = 0;
736
591
  int oldquality, searchdone;
737
591
  double ratio;
738
591
  size_t last_retry_size = 0;
739
591
  int retry_count = 0;
740
591
  int retry = 0;
741
591
  int ai_stripped = 0;
742
591
  int res = -1;
743
744
591
  jpeg_log_fh = log_fh;
745
591
  last_error[0] = 0;
746
747
  /* Initialize decompression object */
748
591
  dinfo.err = jpeg_std_error(&jderr.pub);
749
591
  jpeg_create_decompress(&dinfo);
750
591
  jderr.pub.error_exit=my_error_exit;
751
591
  jderr.pub.output_message=my_output_message;
752
591
  jderr.jump_set = 0;
753
754
  /* Initialize compression object */
755
591
  cinfo.err = jpeg_std_error(&jcerr.pub);
756
591
  jpeg_create_compress(&cinfo);
757
591
  jcerr.pub.error_exit=my_error_exit;
758
591
  jcerr.pub.output_message=my_output_message;
759
591
  jcerr.jump_set = 0;
760
761
591
  if (rate)
762
591
    *rate = 0.0;
763
591
  if (saved)
764
591
    *saved = 0.0;
765
766
591
  if (filename) {
767
591
    if ((infile = fopen(filename, "rb")) == NULL) {
768
0
      warn("cannot open file: %s", filename);
769
0
      res = 1;
770
0
      goto exit_point;
771
0
    }
772
591
    if ((infilesize = file_size(infile)) < 0) {
773
0
      fclose(infile);
774
0
      warn("failed to stat() input file: %s", filename);
775
0
      res = 1;
776
0
      goto exit_point;
777
0
    }
778
591
  } else {
779
0
    infile = stdin;
780
0
    set_filemode_binary(infile);
781
0
  }
782
783
880
retry_point:
784
785
880
  if (setjmp(jderr.setjmp_buffer)) {
786
    /* Error handler for decompress */
787
206
  abort_decompress:
788
206
    jpeg_abort_decompress(&dinfo);
789
206
    fclose(infile);
790
206
    free_line_buf(&buf, dinfo.output_height);
791
206
    if (!quiet_mode || csv)
792
206
      fprintf(log_fh,csv ? ",,,,,\"error: %s\"\n" : " [ERROR: %s]\n", last_error);
793
206
    jderr.jump_set=0;
794
206
    res = 1;
795
206
    goto exit_point;
796
674
  } else {
797
674
    jderr.jump_set=1;
798
674
  }
799
800
801
  /* Prepare to decompress */
802
674
  if (!retry) {
803
591
    if (!quiet_mode || csv) {
804
591
      if (csv) {
805
0
        fprint_csv_field(log_fh, (filename ? filename : "stdin"));
806
0
        fputc(',', log_fh);
807
591
      } else {
808
591
        fprintf(log_fh, "%s ", (filename ? filename : "stdin"));
809
591
      }
810
591
      fflush(log_fh);
811
591
    }
812
813
591
    if (stdin_mode || stdout_mode) {
814
0
      inbuffersize = IN_BUF_SIZE;
815
591
    } else {
816
591
      inbuffersize = (infilesize < IN_BUF_SIZE ? IN_BUF_SIZE : (size_t)infilesize);
817
591
    }
818
591
    if (inbuffer)
819
0
      free(inbuffer);
820
591
    if (!(inbuffer=calloc(inbuffersize, 1))) {
821
0
      strncopy(last_error, "not enough memory", sizeof(last_error));
822
0
      goto abort_decompress;
823
0
    }
824
591
  }
825
674
  global_error_counter=0;
826
674
  jpeg_save_markers(&dinfo, JPEG_COM, 0xffff);
827
14.7k
  for (int i = 0; i < 16; i++) {
828
14.0k
    jpeg_save_markers(&dinfo, JPEG_APP0 + i, 0xffff);
829
14.0k
  }
830
674
  if (!retry) {
831
591
    jpeg_custom_src(&dinfo, infile, &inbuffer, &inbuffersize, &inbufferused, IN_BUF_SIZE);
832
591
  } else {
833
    /* Only the --retry shrink loop (retry == 2) deliberately re-compresses
834
       its own previous output. The lossless fallback (retry == 1) and the
835
       auto-mode alternate pass (retry == 3) must start from the original
836
       image, as recompressing already lossy-compressed data would cause
837
       generation loss. */
838
83
    if (retry == 2)
839
0
      jpeg_custom_mem_src(&dinfo, tmpbuffer, tmpbuffersize);
840
83
    else
841
83
      jpeg_custom_mem_src(&dinfo, inbuffer, inbufferused);
842
83
  }
843
674
  jpeg_read_header(&dinfo, TRUE);
844
845
846
  /* Check for known (Exif, IPTC, ICC , XMP, ...) markers */
847
674
  marker_in_count = parse_markers(&dinfo, marker_str, sizeof(marker_str),
848
674
          &marker_in_size);
849
850
674
  if (!retry) {
851
532
    if (verbose_mode > 1) {
852
0
      fprintf(log_fh,"%d markers found in input file (total size %d bytes)\n",
853
0
        marker_in_count,marker_in_size);
854
0
      fprintf(log_fh,"coding: %s\n", (dinfo.arith_code == TRUE ? "Arithmetic" : "Huffman"));
855
0
    }
856
857
532
    if (!quiet_mode || csv) {
858
532
      fprintf(log_fh,csv ? "%dx%d,%dbit,%c," : "%dx%d %dbit %c ",(int)dinfo.image_width,
859
532
        (int)dinfo.image_height,(int)dinfo.num_components*8,
860
532
        (dinfo.progressive_mode?'P':'N'));
861
532
      if (!csv)
862
532
        fprintf(log_fh,"%s",marker_str);
863
532
      fflush(log_fh);
864
532
    }
865
532
  }
866
867
674
  if (max_pixels > 0) {
868
0
    if ((uint64_t)dinfo.image_width * dinfo.image_height > max_pixels) {
869
0
      strncopy(last_error, "too large input image", sizeof(last_error));
870
0
      goto abort_decompress;
871
0
    }
872
0
  }
873
874
  /* Decompress the image */
875
750
  if (quality >= 0 && retry != 1) {
876
461
    jpeg_start_decompress(&dinfo);
877
878
    /* Allocate line buffer to store the decompressed image */
879
461
    if (!(buf = calloc(dinfo.output_height, sizeof(JSAMPROW)))) {
880
0
      strncopy(last_error, "not enough memory", sizeof(last_error));
881
0
      goto abort_decompress;
882
0
    }
883
2.03M
    for (int i = 0; i < dinfo.output_height; i++) {
884
2.03M
      if (!(buf[i]=calloc((size_t)dinfo.output_width * dinfo.out_color_components,
885
2.03M
              sizeof(JSAMPLE)))) {
886
0
        strncopy(last_error, "not enough memory", sizeof(last_error));
887
0
        goto abort_decompress;
888
0
      }
889
2.03M
    }
890
891
920k
    while (dinfo.output_scanline < dinfo.output_height) {
892
920k
      jpeg_read_scanlines(&dinfo,&buf[dinfo.output_scanline],
893
920k
          dinfo.output_height-dinfo.output_scanline);
894
920k
    }
895
461
  } else {
896
213
    coef_arrays = jpeg_read_coefficients(&dinfo);
897
213
    if (!coef_arrays) {
898
0
      strncopy(last_error, "failed to read coefficients", sizeof(last_error));
899
0
      goto abort_decompress;
900
0
    }
901
213
  }
902
674
  if (strip_ai) {
903
    /* All the markers are known only after reading the whole image */
904
0
    int n = strip_ai_markers(&dinfo);
905
906
0
    if (n > 0) {
907
0
      if (verbose_mode && !retry)
908
0
        fprintf(log_fh, " (%d AI metadata removed) ", n);
909
0
      ai_stripped = 1;
910
0
    }
911
0
  }
912
674
  if (!retry) {
913
416
    in_image_size = inbufferused - dinfo.src->bytes_in_buffer;
914
416
    if(verbose_mode > 2)
915
0
      fprintf(log_fh, " (input image size: %"PRId64" (%ld))", in_image_size, inbufferused);
916
416
    if (stdin_mode) {
917
0
      insize = in_image_size;
918
416
    } else {
919
416
      insize = infilesize;
920
416
      if (in_image_size > 0 && in_image_size < insize) {
921
75
        if (!quiet_mode)
922
75
          fprintf(log_fh, " (%"PRId64" bytes extraneous data found after end of image) ",
923
75
            insize - in_image_size);
924
75
        if (nofix_mode)
925
0
          global_error_counter++;
926
75
        if (save_extra) {
927
0
          extrabuffersize = insize - in_image_size;
928
0
          if (extrabuffer)
929
0
            free(extrabuffer);
930
0
          if (!(extrabuffer = calloc(extrabuffersize, 1))) {
931
0
            strncopy(last_error, "not enough memory", sizeof(last_error));
932
0
            goto abort_decompress;
933
0
          }
934
0
          if (fseek(infile, in_image_size, SEEK_SET)) {
935
0
            strncopy(last_error, "failed to seek input file", sizeof(last_error));
936
0
            goto abort_decompress;
937
0
          }
938
0
          if (fread(extrabuffer, extrabuffersize, 1, infile) != 1) {
939
0
            strncopy(last_error, "failed to read input file", sizeof(last_error));
940
0
            goto abort_decompress;
941
0
          }
942
0
        }
943
75
      }
944
416
    }
945
416
    if (!quiet_mode) {
946
416
      fprintf(log_fh,(global_error_counter==0 ? " [OK] " : " [WARNING] "));
947
416
      fflush(log_fh);
948
416
    }
949
950
416
    if (nofix_mode && global_error_counter != 0) {
951
      /* Skip files containing any errors (or warnings) */
952
0
      strncopy(last_error, "skipped due to decoding errors", sizeof(last_error));
953
0
      goto abort_decompress;
954
0
    }
955
956
416
    if (dest && !noaction) {
957
0
      if (file_exists(newname) && !overwrite_mode) {
958
0
        strncopy(last_error, "target file already exists", sizeof(last_error));
959
0
        goto abort_decompress;
960
0
      }
961
0
    }
962
416
  }
963
964
965
  /* Prepare to compress... */
966
674
  if (setjmp(jcerr.setjmp_buffer)) {
967
158
  abort_compress:
968
    /* Error handler for compress failures */
969
158
    if (!quiet_mode)
970
158
      fprintf(log_fh," [Compress ERROR: %s]\n",last_error);
971
158
    jpeg_abort_compress(&cinfo);
972
158
    jpeg_abort_decompress(&dinfo);
973
158
    fclose(infile);
974
158
    free_line_buf(&buf, dinfo.output_height);
975
158
    jcerr.jump_set=0;
976
158
    res = 2;
977
158
    goto exit_point;
978
516
  } else {
979
516
    jcerr.jump_set=1;
980
516
  }
981
982
516
  lastsize = 0;
983
516
  searchdone = 0;
984
516
  if (!retry) {
985
416
    oldquality = 200;
986
416
    if (target_size != 0) {
987
      /* Always start with quality 100 if -S option specified... */
988
416
      quality = 100;
989
416
    }
990
416
  }
991
992
993
1.32k
binary_search_loop:
994
995
  /* Allocate memory buffer that should be large enough to store the output JPEG... */
996
1.32k
  if (outbuffer)
997
909
    free(outbuffer);
998
1.32k
  outbuffersize = insize + 32768;
999
1.32k
  if (!(outbuffer=calloc(outbuffersize, 1))) {
1000
0
    warn("not enough memory");
1001
0
    strncopy(last_error, "not enough memory", sizeof(last_error));
1002
0
    goto abort_compress;
1003
0
  }
1004
1005
  /* setup custom "destination manager" for libjpeg to write to our buffer */
1006
1.32k
  jpeg_memory_dest(&cinfo, &outbuffer, &outbuffersize, 65536);
1007
1008
1009
1.32k
  if (quality >= 0 && retry != 1) {
1010
    /* Lossy "optimization" ... */
1011
1012
1.03k
    cinfo.in_color_space=dinfo.out_color_space;
1013
1.03k
    cinfo.input_components=dinfo.output_components;
1014
1.03k
    cinfo.image_width=dinfo.image_width;
1015
1.03k
    cinfo.image_height=dinfo.image_height;
1016
1.03k
    jpeg_set_defaults(&cinfo);
1017
1.03k
    jpeg_set_quality(&cinfo,quality,TRUE);
1018
1.03k
#ifdef HAVE_JINT_DC_SCAN_OPT_MODE
1019
1.03k
    if (jpeg_c_int_param_supported(&cinfo, JINT_DC_SCAN_OPT_MODE))
1020
1.03k
      jpeg_c_set_int_param(&cinfo, JINT_DC_SCAN_OPT_MODE, 1);
1021
1.03k
#endif
1022
1.03k
    if (all_normal || (!dinfo.progressive_mode && !all_progressive)) {
1023
      /* Explicitly disable progressive mode. */
1024
607
      cinfo.scan_info = NULL;
1025
607
      cinfo.num_scans = 0;
1026
607
    } else if (all_progressive || dinfo.progressive_mode) {
1027
      /* Enable progressive mode. */
1028
430
      jpeg_simple_progression(&cinfo);
1029
430
    }
1030
1.03k
    cinfo.optimize_coding = TRUE;
1031
1.03k
#ifdef HAVE_ARITH_CODE
1032
1.03k
    if (arith_mode >= 0)
1033
0
      cinfo.arith_code = (arith_mode > 0 ? TRUE : FALSE);
1034
1.03k
#endif
1035
1.03k
    if (dinfo.saw_JFIF_marker && (save_jfif || strip_none)) {
1036
374
      cinfo.write_JFIF_header = TRUE;
1037
663
    } else {
1038
663
      cinfo.write_JFIF_header = FALSE;
1039
663
    }
1040
1.03k
    if (dinfo.saw_Adobe_marker && (save_adobe || strip_none)) {
1041
      /* If outputting Adobe marker, don't write JFIF marker... */
1042
0
      cinfo.write_JFIF_header = FALSE;
1043
0
    }
1044
1045
1.03k
    jpeg_start_compress(&cinfo,TRUE);
1046
1047
    /* Write markers */
1048
1.03k
    write_markers(&dinfo,&cinfo);
1049
1050
    /* Write image */
1051
2.07k
    while (cinfo.next_scanline < cinfo.image_height) {
1052
1.03k
      jpeg_write_scanlines(&cinfo,&buf[cinfo.next_scanline],
1053
1.03k
          cinfo.image_height - cinfo.next_scanline);
1054
1.03k
    }
1055
1056
1.03k
  } else {
1057
    /* Lossless optimization ... */
1058
1059
288
    jpeg_copy_critical_parameters(&dinfo, &cinfo);
1060
288
#ifdef HAVE_JINT_DC_SCAN_OPT_MODE
1061
288
    if (jpeg_c_int_param_supported(&cinfo, JINT_DC_SCAN_OPT_MODE))
1062
199
      jpeg_c_set_int_param(&cinfo, JINT_DC_SCAN_OPT_MODE, 1);
1063
288
#endif
1064
288
    if (all_normal || (!dinfo.progressive_mode && !all_progressive)) {
1065
      /* Explicitly disable progressive mode. */
1066
97
      cinfo.scan_info = NULL;
1067
97
      cinfo.num_scans = 0;
1068
191
    } else if (all_progressive || dinfo.progressive_mode) {
1069
      /* Enable progressive mode. */
1070
102
      jpeg_simple_progression(&cinfo);
1071
102
    }
1072
288
    cinfo.optimize_coding = TRUE;
1073
288
#ifdef HAVE_ARITH_CODE
1074
288
    if (arith_mode >= 0)
1075
0
      cinfo.arith_code = (arith_mode > 0 ? TRUE : FALSE);
1076
288
#endif
1077
288
    if (dinfo.saw_JFIF_marker && (save_jfif || strip_none)) {
1078
33
      cinfo.write_JFIF_header = TRUE;
1079
255
    } else {
1080
255
      cinfo.write_JFIF_header = FALSE;
1081
255
    }
1082
288
    if (dinfo.saw_Adobe_marker && (save_adobe || strip_none)) {
1083
      /* If outputting Adobe marker, don't write JFIF marker... */
1084
0
      cinfo.write_JFIF_header = FALSE;
1085
0
    }
1086
1087
    /* Write image */
1088
288
    jpeg_write_coefficients(&cinfo, coef_arrays);
1089
1090
    /* Write markers */
1091
288
    write_markers(&dinfo,&cinfo);
1092
1093
288
  }
1094
1095
1.32k
  jpeg_finish_compress(&cinfo);
1096
1.32k
  outsize = outbuffersize + extrabuffersize;
1097
1.32k
  if (verbose_mode > 2)
1098
0
    fprintf(log_fh, " (output image size: %"PRId64" (%lu))", outsize, extrabuffersize);
1099
1100
1.32k
  if (target_size != 0 && !retry) {
1101
    /* Perform (binary) search to try to reach target file size... */
1102
1103
1.02k
    int64_t osize = outsize/1024;
1104
1.02k
    int64_t isize = insize/1024;
1105
1.02k
    int64_t tsize = target_size;
1106
1107
1.02k
    if (verbose_mode > 1)
1108
0
      fprintf(log_fh, "(size=%"PRId64")",outsize);
1109
1.02k
    if (tsize < 0) {
1110
      /* 64-bit intermediate, as target_size * insize can overflow
1111
         a 32-bit long (files > ~21MB on ILP32/LLP64 platforms) */
1112
1.02k
      tsize = ((int64_t)(-target_size) * insize / 100) / 1024;
1113
1.02k
      if (tsize < 1)
1114
524
        tsize = 1;
1115
1.02k
    }
1116
1117
1.02k
    if (osize == tsize || searchdone || tsize > isize) {
1118
413
      if (searchdone < 42 && lastsize > 0) {
1119
138
        if (llabs(osize-tsize) > llabs(lastsize-tsize)) {
1120
10
          if (verbose_mode)
1121
0
            fprintf(log_fh,"(revert to %d)",oldquality);
1122
10
          searchdone = 42;
1123
10
          quality = oldquality;
1124
10
          goto binary_search_loop;
1125
10
        }
1126
138
      }
1127
403
      if (verbose_mode)
1128
0
        fprintf(log_fh," ");
1129
1130
611
    } else {
1131
611
      int newquality;
1132
611
      double dif = abs(oldquality-quality) / 2.0;
1133
1134
611
      if (osize > tsize)
1135
477
        newquality = quality - dif;
1136
134
      else
1137
134
        newquality = quality + dif + 0.5;
1138
1139
611
      if (dif < 1.0)
1140
10
        searchdone = 1;
1141
611
      if (newquality < 0) {
1142
57
        newquality = 0;
1143
57
        searchdone = 1;
1144
57
      }
1145
611
      if (newquality > 100) {
1146
56
        newquality = 100;
1147
56
        searchdone = 1;
1148
56
      }
1149
1150
611
      oldquality = quality;
1151
611
      quality = newquality;
1152
611
      lastsize = osize;
1153
611
      if (verbose_mode)
1154
0
        fprintf(log_fh,"(try %d)",quality);
1155
611
      goto binary_search_loop;
1156
611
    }
1157
1.02k
  }
1158
1159
704
  jpeg_finish_decompress(&dinfo);
1160
704
  free_line_buf(&buf, dinfo.output_height);
1161
1162
704
  if (retry_mode) {
1163
0
    if ((retry == 0 || retry == 2) && quality >= 0 && outsize <= insize) {
1164
      /* Retry compression until output file stops getting smaller
1165
         or we hit max limit of iterations (10)... */
1166
0
      if (retry_count == 0)
1167
0
        last_retry_size = outsize + 1;
1168
0
      if (++retry_count < 10 && outsize < last_retry_size) {
1169
0
        if (tmpbuffer)
1170
0
          free(tmpbuffer);
1171
0
        tmpbuffer = outbuffer;
1172
0
        tmpbuffersize = outbuffersize;
1173
0
        outbuffer = NULL;
1174
0
        last_retry_size = outsize;
1175
0
        retry = 2;
1176
0
        if (verbose_mode)
1177
0
          fprintf(log_fh, "(retry%d: %"PRId64") ", retry_count, outsize);
1178
0
        goto retry_point;
1179
0
      }
1180
0
    }
1181
0
    if (retry == 2) {
1182
0
      if (verbose_mode)
1183
0
        fprintf(log_fh, "(retry done: %"PRId64") ", outsize);
1184
0
      if (outsize > last_retry_size) {
1185
0
        if (outbuffer)
1186
0
          free(outbuffer);
1187
0
        outbuffer = tmpbuffer;
1188
0
        outbuffersize = tmpbuffersize;
1189
0
        outsize = outbuffersize + extrabuffersize;
1190
0
        tmpbuffer = NULL;
1191
0
      }
1192
0
    }
1193
0
  }
1194
1195
  /* If auto_mode, try both progressive and non-progressive... */
1196
704
  if (auto_mode) {
1197
0
    int newmode = (dinfo.progressive_mode ? 0 : 1);
1198
0
    if (retry != 3) {
1199
0
      if (newmode)
1200
0
        all_progressive = 1;
1201
0
      else
1202
0
        all_normal = 1;
1203
0
      if (tmpbuffer)
1204
0
        free(tmpbuffer);
1205
0
      tmpbuffer = outbuffer;
1206
0
      tmpbuffersize = outbuffersize;
1207
0
      outbuffer = NULL;
1208
0
      last_retry_size = outsize;
1209
0
      retry = 3;
1210
0
      if (verbose_mode)
1211
0
        fprintf(log_fh, "(retry w/%s) ", (newmode ? "progressive" : "normal"));
1212
0
      goto retry_point;
1213
0
    } else {
1214
0
      if (verbose_mode > 1)
1215
0
        fprintf(log_fh, "(automode done: %"PRId64") ", outsize);
1216
0
      auto_mode = 0;
1217
0
      if (outsize > last_retry_size) {
1218
0
        if (verbose_mode)
1219
0
          fprintf(log_fh, "(revert to %s) ", (!newmode ? "progressive" : "normal"));
1220
0
        all_progressive = 0;
1221
0
        all_normal = 0;
1222
0
        if (outbuffer)
1223
0
          free(outbuffer);
1224
0
        outbuffer = tmpbuffer;
1225
0
        outbuffersize = tmpbuffersize;
1226
0
        outsize = outbuffersize + extrabuffersize;
1227
0
        tmpbuffer = NULL;
1228
0
      }
1229
0
    }
1230
0
  }
1231
1232
  /* In case "lossy" compression resulted larger file than original, retry with "lossless"... */
1233
704
  if (quality >= 0 && outsize >= insize && retry != 1) {
1234
289
    retry = 1;
1235
289
    if (verbose_mode)
1236
0
      fprintf(log_fh, "(retry w/lossless) ");
1237
289
    goto retry_point;
1238
289
  }
1239
1240
415
  fclose(infile);
1241
1242
415
  ratio = (insize - outsize) * 100.0 / insize;
1243
415
  if (!quiet_mode || csv)
1244
227
    fprintf(log_fh,csv ? "%"PRId64",%"PRId64",%0.2f," : "%"PRId64" --> %"PRId64" bytes (%0.2f%%), ",
1245
227
      insize, outsize, ratio);
1246
415
  if (rate) {
1247
227
    *rate = (ratio < 0 ? 0.0 : ratio);
1248
227
  }
1249
1250
  /* Removed AI metadata must not survive in the original file */
1251
415
  if ((outsize < insize && ratio >= threshold) || force || ai_stripped) {
1252
91
    if (saved) {
1253
91
      *saved = (insize - outsize) / 1024.0;
1254
91
    }
1255
91
    if (!quiet_mode || csv)
1256
91
      fprintf(log_fh,csv ? "optimized\n" : "optimized.\n");
1257
91
    if (noaction) {
1258
0
      res = 0;
1259
0
      goto exit_point;
1260
0
    }
1261
1262
91
    if (stdout_mode) {
1263
0
      outfname=NULL;
1264
0
      set_filemode_binary(stdout);
1265
0
      if (fwrite(outbuffer,outbuffersize,1,stdout) != 1)
1266
0
        fatal("%s, write failed to stdout",(stdin_mode ? "stdin" : filename));
1267
0
      if (save_extra && extrabuffersize > 0) {
1268
0
        if (fwrite(extrabuffer,extrabuffersize,1,stdout) != 1)
1269
0
          fatal("%s, write failed to stdout",(stdin_mode ? "stdin" : filename));
1270
0
      }
1271
91
    } else {
1272
91
      if (preserve_perms && !dest) {
1273
        /* make backup of the original file before overwriting it... */
1274
0
        int newlen = snprintf(tmpfilename, sizeof(tmpfilename),
1275
0
            "%s.jpegoptim.bak", newname);
1276
0
        if (newlen < 0 || (size_t)newlen >= sizeof(tmpfilename))
1277
0
          fatal("temp filename too long: %s", tmpfilename);
1278
1279
0
        if (verbose_mode > 1)
1280
0
          fprintf(log_fh,"%s, creating backup as: %s\n", filename, tmpfilename);
1281
0
        if (file_exists(tmpfilename))
1282
0
          fatal("%s, backup file already exists: %s", filename, tmpfilename);
1283
0
        if (copy_file(newname,tmpfilename))
1284
0
          fatal("%s, failed to create backup: %s", filename, tmpfilename);
1285
0
        if ((outfile=create_file(newname))==NULL)
1286
0
          fatal("%s, error opening output file: %s", filename, newname);
1287
0
        outfname = newname;
1288
91
      } else {
1289
91
        if (!(outfile = create_temp_file(tmpdir, "jpegoptim", tmpfilename, sizeof(tmpfilename))))
1290
0
          fatal("error creating temporary file: %s", tmpfilename);
1291
91
        outfname = tmpfilename;
1292
91
      }
1293
91
      int outfd = fileno(outfile);
1294
1295
      /* write "new" image to a file... */
1296
91
      if (verbose_mode > 1)
1297
0
        fprintf(log_fh,"writing %lu bytes to file: %s\n", outbuffersize, outfname);
1298
91
      if (fwrite(outbuffer, outbuffersize, 1, outfile) != 1) {
1299
0
        write_error = 1;
1300
91
      } else if (save_extra && extrabuffersize > 0) {
1301
0
        if (verbose_mode > 1)
1302
0
          fprintf(log_fh,"writing %lu bytes to file: %s\n", extrabuffersize, outfname);
1303
0
        if (fwrite(extrabuffer, extrabuffersize, 1, outfile) != 1)
1304
0
          write_error = 1;
1305
0
      }
1306
91
      if (fflush(outfile) != 0)
1307
0
        write_error = 1;
1308
1309
91
      if (!(preserve_perms && !dest) && !write_error) {
1310
        /* set file mode */
1311
91
        if (verbose_mode > 1)
1312
0
          fprintf(log_fh,"set file permissions same as in original: %s\n", outfname);
1313
91
        if (set_file_mode(outfd, outfname, file_stat->st_mode & 0777) != 0)
1314
0
          warn("failed to set output file mode");
1315
1316
        /* preserve file group (and owner if run by root) */
1317
91
        if (set_file_owner(outfd, outfname, (geteuid()==0 ? file_stat->st_uid : -1),
1318
91
               file_stat->st_gid) != 0)
1319
0
          warn("failed to reset output file group/owner");
1320
91
      }
1321
1322
91
      if (preserve_mtime && !write_error) {
1323
        /* preserve file modification time */
1324
0
        if (verbose_mode > 1)
1325
0
          fprintf(log_fh,"set file modification time same as in original: %s\n",
1326
0
            outfname);
1327
0
        if (set_file_times(outfd, outfname, file_stat) != 0)
1328
0
          warn("failed to reset output file time/date");
1329
0
      }
1330
1331
91
      if (fclose(outfile) != 0)
1332
0
        write_error = 1;
1333
1334
91
      if (write_error) {
1335
0
        if (preserve_perms && !dest) {
1336
          /* original file was truncated already, so restore it from the backup... */
1337
0
          warn("%s, write failed, restoring from backup: %s", filename, tmpfilename);
1338
0
          if (rename_file(tmpfilename, newname))
1339
0
            fatal("write failed to file: %s (failed to restore backup: %s)",
1340
0
              newname, tmpfilename);
1341
0
          if (set_file_mode(-1, newname, (file_stat->st_mode & 0777)) != 0)
1342
0
            warn("failed to restore file mode: %s", newname);
1343
0
          if (set_file_owner(-1, newname,
1344
0
                 (geteuid()==0 ? file_stat->st_uid : -1),
1345
0
                 file_stat->st_gid) != 0)
1346
0
            warn("failed to restore file group/owner: %s", newname);
1347
0
          fatal("write failed to file: %s (original restored)", newname);
1348
0
        }
1349
        /* remove the incomplete temporary file... */
1350
0
        delete_file(outfname);
1351
0
        fatal("write failed to temporary file: %s", outfname);
1352
0
      }
1353
1354
1355
91
      if (preserve_perms && !dest) {
1356
        /* original file was already replaced, remove backup... */
1357
0
        if (verbose_mode > 1)
1358
0
          fprintf(log_fh,"removing backup file: %s\n", tmpfilename);
1359
0
        if (delete_file(tmpfilename))
1360
0
          warn("failed to remove backup file: %s", tmpfilename);
1361
91
      } else {
1362
        /* make temp file to be the original file... */
1363
91
        if (verbose_mode > 1)
1364
0
          fprintf(log_fh,"renaming: %s to %s\n", outfname, newname);
1365
91
        if (rename_file(outfname, newname))
1366
0
          fatal("cannot rename temp file");
1367
91
      }
1368
91
    }
1369
324
  } else {
1370
324
    if (!quiet_mode || csv)
1371
136
      fprintf(log_fh,csv ? "skipped\n" : "skipped.\n");
1372
324
    if (stdout_mode) {
1373
0
      set_filemode_binary(stdout);
1374
0
      if (fwrite(inbuffer, in_image_size, 1, stdout) != 1)
1375
0
        fatal("%s, write failed to stdout",
1376
0
          (stdin_mode ? "stdin" : filename));
1377
0
    }
1378
324
  }
1379
1380
415
  res = 0;
1381
1382
591
 exit_point:
1383
591
  if (inbuffer)
1384
591
    free(inbuffer);
1385
591
  if (outbuffer)
1386
416
    free(outbuffer);
1387
591
  if (tmpbuffer)
1388
0
    free(tmpbuffer);
1389
591
  if (extrabuffer)
1390
0
    free(extrabuffer);
1391
591
  jpeg_destroy_compress(&cinfo);
1392
591
  jpeg_destroy_decompress(&dinfo);
1393
1394
591
  return res;
1395
415
}
1396
1397
1398
#ifdef PARALLEL_PROCESSING
1399
int wait_for_worker(FILE *log_fh)
1400
0
{
1401
0
  FILE *p;
1402
0
  struct worker *w;
1403
0
  struct pollfd pfds[MAX_WORKERS];
1404
0
  int pfd_slot[MAX_WORKERS];
1405
0
  char buf[1024];
1406
0
  int wstatus;
1407
0
  pid_t pid;
1408
0
  int nfds, i, j, e;
1409
0
  int state = 0;
1410
0
  double val;
1411
0
  double rate = 0.0;
1412
0
  double saved = 0.0;
1413
1414
1415
  /* Wait for activity on worker pipes. Pipe must be drained before
1416
     calling wait(), as worker cannot exit if it is blocked writing
1417
     to a full pipe... */
1418
0
  nfds = 0;
1419
0
  for (j = 0; j < MAX_WORKERS; j++) {
1420
0
    if (workers[j].pid < 0)
1421
0
      continue;
1422
0
    pfds[nfds].fd = workers[j].read_pipe;
1423
0
    pfds[nfds].events = POLLIN;
1424
0
    pfd_slot[nfds] = j;
1425
0
    nfds++;
1426
0
  }
1427
0
  if (nfds < 1)
1428
0
    return -1;
1429
1430
0
  while (poll(pfds, nfds, -1) < 0) {
1431
0
    if (errno != EINTR)
1432
0
      fatal("poll() failed");
1433
0
  }
1434
1435
  /* Prefer a worker that has already exited (closed its pipe)... */
1436
0
  w = NULL;
1437
0
  for (i = 0; i < nfds; i++) {
1438
0
    if (pfds[i].revents & POLLHUP) {
1439
0
      j = pfd_slot[i];
1440
0
      w = &workers[j];
1441
0
      break;
1442
0
    }
1443
0
  }
1444
0
  if (!w) {
1445
0
    for (i = 0; i < nfds; i++) {
1446
0
      if (pfds[i].revents & (POLLIN | POLLERR)) {
1447
0
        j = pfd_slot[i];
1448
0
        w = &workers[j];
1449
0
        break;
1450
0
      }
1451
0
    }
1452
0
  }
1453
0
  if (!w)
1454
0
    fatal("poll() returned no active worker");
1455
0
  pid = w->pid;
1456
1457
0
  p = fdopen(w->read_pipe, "r");
1458
0
  if (!p) fatal("fdopen failed()");
1459
0
  while (fgets(buf, sizeof(buf), p)) {
1460
0
    if (verbose_mode > 2)
1461
0
      fprintf(log_fh, "worker[%d] PIPE: %s", pid, buf);
1462
0
    if (state == 0 && buf[0] == '\n') {
1463
0
      state=1;
1464
0
      continue;
1465
0
    }
1466
0
    if (state == 1 && !strncmp(buf, "STAT", 4)) {
1467
0
      state=2;
1468
0
      continue;
1469
0
    }
1470
0
    if (state >= 2) {
1471
0
      if (sscanf(buf, "%lf", &val) == 1) {
1472
0
        if (state == 2) {
1473
0
          rate = val;
1474
0
        }
1475
0
        else if (state == 3) {
1476
0
          saved = val;
1477
0
          average_count++;
1478
0
          average_rate += rate;
1479
0
          total_save += saved;
1480
0
        }
1481
0
      }
1482
0
      state++;
1483
0
      continue;
1484
0
    }
1485
0
    if (state == 0)
1486
0
      fprintf(log_fh, "%s", buf);
1487
0
  }
1488
0
  fclose(p);
1489
1490
0
  if (waitpid(pid, &wstatus, 0) < 0)
1491
0
    fatal("waitpid() failed for worker[%d]", pid);
1492
1493
0
  if (WIFEXITED(wstatus)) {
1494
0
    e = WEXITSTATUS(wstatus);
1495
0
    if (verbose_mode)
1496
0
      fprintf(log_fh, "worker[%d] [slot=%d] exited: %d\n",
1497
0
        pid, j, e);
1498
0
    if (e == 1) {
1499
0
      decompress_err_count++;
1500
0
    } else if (e == 2) {
1501
0
      compress_err_count++;
1502
0
    } else if (e != 0) {
1503
      /* worker died via fatal() or other unexpected error,
1504
         count it so program exit status reflects the failure... */
1505
0
      compress_err_count++;
1506
0
      warn("worker[%d] failed with status: %d", pid, e);
1507
0
    }
1508
0
  } else {
1509
0
    fatal("worker[%d] killed", pid);
1510
0
  }
1511
1512
0
  w->pid = -1;
1513
0
  w->read_pipe = -1;
1514
0
  worker_count --;
1515
1516
0
  return pid;
1517
0
}
1518
#endif
1519
1520
1521
#ifndef BUILD_FOR_OSS_FUZZ // Libfuzzer provides its own fuzzer
1522
/****************************************************************************/
1523
int main(int argc, char **argv)
1524
{
1525
  struct stat file_stat;
1526
  char tmpfilename[MAXPATHLEN + 1],tmpdir[MAXPATHLEN + 1];
1527
  char newname[MAXPATHLEN + 1], dest_path[MAXPATHLEN + 1];
1528
  char namebuf[MAXPATHLEN + 2];
1529
  const char *filename;
1530
  int arg_idx;
1531
  int res;
1532
  double rate, saved;
1533
  FILE *log_fh;
1534
#ifdef PARALLEL_PROCESSING
1535
  struct worker *w;
1536
  int pipe_fd[2];
1537
  pid_t pid;
1538
1539
1540
  /* Allocate table to keep track of child processes... */
1541
  if (!(workers = calloc(MAX_WORKERS, sizeof(struct worker))))
1542
    fatal("not enough memory");
1543
  for (int i = 0; i < MAX_WORKERS; i++) {
1544
    workers[i].pid = -1;
1545
    workers[i].read_pipe = -1;
1546
  }
1547
#endif
1548
1549
  umask(077);
1550
  signal(SIGINT,own_signal_handler);
1551
  signal(SIGTERM,own_signal_handler);
1552
1553
  /* Parse command line parameters */
1554
  parse_arguments(argc, argv, dest_path, sizeof(dest_path));
1555
  log_fh = (stdout_mode ? stderr : stdout);
1556
  if (quiet_mode)
1557
    verbose_mode = 0;
1558
1559
  if (verbose_mode) {
1560
    if (quality >= 0 && target_size == 0)
1561
      fprintf(log_fh, "Image quality limit set to: %d\n", quality);
1562
    if (threshold >= 0)
1563
      fprintf(log_fh, "Compression threshold (%%) set to: %0.1lf\n", threshold);
1564
    if (all_normal)
1565
      fprintf(log_fh, "All output files will be non-progressive\n");
1566
    if (all_progressive)
1567
      fprintf(log_fh, "All output files will be progressive\n");
1568
    if (target_size > 0)
1569
      fprintf(log_fh, "Target size for output files set to: %d Kbytes.\n",
1570
        target_size);
1571
    if (target_size < 0)
1572
      fprintf(log_fh, "Target size for output files set to: %d%%\n",
1573
        -target_size);
1574
#ifdef PARALLEL_PROCESSING
1575
    if (max_workers > 0)
1576
      fprintf(log_fh, "Using maximum of %d parallel threads\n", max_workers);
1577
#endif
1578
  }
1579
1580
1581
  if (stdin_mode) {
1582
    /* Process just one file, if source is stdin... */
1583
    res = optimize(stderr, NULL, NULL, NULL, &file_stat, NULL, NULL,
1584
      auto_mode, all_normal, all_progressive);
1585
    return (res == 0 ? 0 : 1);
1586
  }
1587
1588
  arg_idx = (optind > 0 ? optind : 1);
1589
  if (files_from == NULL && argc <= arg_idx) {
1590
    if (!quiet_mode)
1591
      fprintf(stderr, PROGRAMNAME ": file argument(s) missing\n"
1592
        "Try '" PROGRAMNAME " --help' for more information.\n");
1593
    exit(1);
1594
  }
1595
1596
1597
  /* Main loop to process input files */
1598
  do {
1599
    if (files_from) {
1600
      if (!fgetstr(namebuf, sizeof(namebuf), files_from))
1601
        break;
1602
      filename = namebuf;
1603
    } else {
1604
      filename = argv[arg_idx];
1605
    }
1606
1607
    if (*filename == 0)
1608
      continue;
1609
    if (verbose_mode > 1)
1610
      fprintf(log_fh, "processing file: %s\n", filename);
1611
    if (strnlen(filename, MAXPATHLEN + 1) > MAXPATHLEN) {
1612
      warn("skipping too long filename: %s", filename);
1613
      continue;
1614
    }
1615
1616
    if (noaction) {
1617
      newname[0] = 0;
1618
    } else {
1619
      /* generate tmp dir & new filename */
1620
      if (dest) {
1621
        strncopy(tmpdir, dest_path, sizeof(tmpdir));
1622
        strncopy(newname, dest_path, sizeof(newname));
1623
        if (!splitname(filename, tmpfilename, sizeof(tmpfilename)))
1624
          fatal("splitname() failed for: %s", filename);
1625
        /* Check that the destination path fits in the buffer, as
1626
           silent truncation could write to a wrong destination file... */
1627
        if (strlen(dest_path) + strlen(tmpfilename) >= sizeof(newname)) {
1628
          warn("skipping, destination path too long: %s%s",
1629
            dest_path, tmpfilename);
1630
          continue;
1631
        }
1632
        strncatenate(newname, tmpfilename, sizeof(newname));
1633
      } else {
1634
        if (!splitdir(filename, tmpdir, sizeof(tmpdir)))
1635
          fatal("splitdir() failed for: %s", filename);
1636
        strncopy(newname, filename, sizeof(newname));
1637
      }
1638
    }
1639
1640
    if (file_exists(filename)) {
1641
      if (!is_file(filename, &file_stat)) {
1642
        if (is_directory(filename))
1643
          warn("skipping directory: %s", filename);
1644
        else
1645
          warn("skipping special file: %s", filename);
1646
        continue;
1647
      }
1648
    } else {
1649
      warn("file not found: %s", filename);
1650
      continue;
1651
    }
1652
1653
#ifdef PARALLEL_PROCESSING
1654
    if (max_workers > 1) {
1655
      /* Multi process mode, run up to max_workers processes simultaneously... */
1656
1657
      if (worker_count >= max_workers) {
1658
        // wait for a worker to exit...
1659
        wait_for_worker(log_fh);
1660
      }
1661
      if (pipe(pipe_fd) < 0)
1662
        fatal("failed to open pipe");
1663
      /* flush any buffered output so child process does not
1664
         inherit it (and print it again when exiting) ... */
1665
      fflush(NULL);
1666
      pid = fork();
1667
      if (pid < 0)
1668
        fatal("fork() failed");
1669
      if (pid == 0) {
1670
        /* Child process starts here... */
1671
        if (files_from)
1672
          fclose(files_from);
1673
        close(pipe_fd[0]);
1674
        FILE *p;
1675
1676
        if (!(p = fdopen(pipe_fd[1],"w")))
1677
          fatal("worker: fdopen failed");
1678
1679
        res = optimize(p, filename, newname, tmpdir, &file_stat, &rate, &saved,
1680
          auto_mode, all_normal, all_progressive);
1681
        if (res == 0)
1682
          fprintf(p, "\n\nSTATS\n%lf\n%lf\n", rate, saved);
1683
        exit(res);
1684
      } else {
1685
        /* Parent continues here... */
1686
        int j;
1687
1688
        close(pipe_fd[1]);
1689
1690
        w = NULL;
1691
        for (j = 0; j < MAX_WORKERS; j++) {
1692
          if (workers[j].pid < 0) {
1693
            w = &workers[j];
1694
            break;
1695
          }
1696
        }
1697
        if (!w)
1698
          fatal("no space to start a new worker (%d)", worker_count);
1699
        w->pid = pid;
1700
        w->read_pipe = pipe_fd[0];
1701
        worker_count++;
1702
        if (verbose_mode > 0)
1703
          fprintf(log_fh, "worker[%d] [slot=%d] started\n", pid, j);;
1704
      }
1705
1706
    } else
1707
#endif
1708
    {
1709
      /* Single process mode, process one file at a time... */
1710
1711
      res = optimize(log_fh, filename, newname, tmpdir, &file_stat, &rate, &saved,
1712
        auto_mode, all_normal, all_progressive);
1713
      if (res == 0) {
1714
        average_count++;
1715
        average_rate += rate;
1716
        total_save += saved;
1717
      } else if (res == 1) {
1718
        decompress_err_count++;
1719
      } else if (res == 2) {
1720
        compress_err_count++;
1721
      }
1722
    }
1723
1724
  } while (files_from || ++arg_idx < argc);
1725
1726
1727
#ifdef PARALLEL_PROCESSING
1728
  /* Wait for any child processes to exit... */
1729
  if (max_workers > 1) {
1730
    if (verbose_mode) {
1731
      fprintf(log_fh, "Waiting for %d workers to finish...\n", worker_count);
1732
    }
1733
    while ((pid = wait_for_worker(log_fh)) > 0) {
1734
      if (verbose_mode > 2)
1735
        fprintf(log_fh, "worker[%d] done\n", pid);
1736
    }
1737
  }
1738
#endif
1739
1740
  if (totals_mode && !quiet_mode)
1741
    fprintf(log_fh, "Average ""compression"" (%"PRId64" files): %0.2f%% (total saved %0.0fk)\n",
1742
      average_count, (average_count == 0 ? 0.0 : average_rate/average_count), total_save);
1743
1744
1745
  return (decompress_err_count > 0 || compress_err_count > 0 ? 1 : 0);;
1746
}
1747
#else
1748
void fuzz_set_target_size(const int new_target_size)
1749
3
{
1750
3
  target_size = new_target_size;
1751
3
}
1752
#endif /* BUILD_FOR_OSS_FUZZ */
1753
/* eof :-) */