Coverage Report

Created: 2026-12-01 07:06

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