Coverage Report

Created: 2026-12-01 06:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libvips/libvips/foreign/jpeg2vips.c
Line
Count
Source
1
/* wrap jpeg library for read
2
 *
3
 * 28/11/03 JC
4
 *  - better no-overshoot on tile loop
5
 * 12/11/04
6
 *  - better demand size choice for eval
7
 * 30/6/05 JC
8
 *  - update im_error()/im_warn()
9
 *  - now loads and saves exif data
10
 * 30/7/05
11
 *  - now loads ICC profiles
12
 *  - now saves ICC profiles from the VIPS header
13
 * 24/8/05
14
 *  - jpeg load sets vips xres/yres from exif, if possible
15
 *  - jpeg save sets exif xres/yres from vips, if possible
16
 * 29/8/05
17
 *  - cut from old vips_jpeg.c
18
 * 13/10/06
19
 *  - add </libexif/ prefix if required
20
 * 11/2/08
21
 *  - spot CMYK jpegs and set Type
22
 *  - spot Adobe CMYK JPEG and invert ink density
23
 * 15/2/08
24
 *  - added "shrink" parameter
25
 * 16/6/09
26
 *  - added "fail" option ... fail on any warnings
27
 * 12/10/09
28
 *  - also set scale_num on shrink (thanks Guido)
29
 * 4/2/10
30
 *  - gtkdoc
31
 * 4/12/10
32
 *  - attach the jpeg thumbnail and multiscan fields (thanks Mike)
33
 * 21/2/10
34
 *  - only accept the first APP1 block which starts "Exif..." as exif
35
 *    data, some jpegs seem to have several APP1s, argh
36
 * 20/4/2011
37
 *  - added im_bufjpeg2vips()
38
 * 12/10/2011
39
 *  - read XMP data
40
 * 3/11/11
41
 *  - attach exif tags as coded values
42
 * 24/11/11
43
 *  - turn into a set of read fns ready to be called from a class
44
 * 9/1/12
45
 *  - read jfif resolution as well as exif
46
 * 19/2/12
47
 *  - switch to lazy reading
48
 * 7/8/12
49
 *  - note EXIF resolution unit in VIPS_META_RESOLUTION_UNIT
50
 * 16/11/12
51
 *  - tag exif fields with their ifd
52
 *  - attach rationals as a/b, don't convert to double
53
 * 21/11/12
54
 *  - don't insist exif must have data
55
 *  - attach IPTC data (app13), thanks Gary
56
 * 6/7/13
57
 *  - null-terminate exif strings, thanks Mike
58
 * 24/2/14
59
 *  - don't write to our input buffer, thanks Lovell
60
 * 9/9/14
61
 *  - support "none" as a resolution unit
62
 * 16/10/14
63
 *  - add "autorotate" option
64
 * 20/1/15
65
 *  - don't call jpeg_finish_decompress(), all it does is read and check
66
 *    the tail of the file
67
 * 26/2/15
68
 *  - close the jpeg read down early for a header read ... this saves an
69
 *    fd during jpg read, handy for large numbers of input images
70
 * 15/7/15
71
 *  - save exif tags using @name, not @title ... @title is subject to i18n
72
 * 21/2/16
73
 *  - _destroy the decompress object as soon as we can, frees loads of
74
 *    memory for progressive jpg files
75
 * 26/5/16
76
 *  - switch to new orientation tag
77
 * 11/7/16
78
 *  - new --fail handling
79
 * 07/09/16
80
 *      - don't use the exif resolution if x_resolution / y_resolution /
81
 *        resolution_unit is missing
82
 * 7/11/16
83
 *  - exif handling moved out to exif.c
84
 * 4/1/17
85
 *  - don't warn for missing exif res, since we fall back to jfif now
86
 * 17/1/17
87
 *  - invalidate operation on read error
88
 * 12/5/17
89
 *  - fail aborts on error, not warning
90
 * 25/8/17
91
 *  - revise read from buffer functions in line with latest libjpeg
92
 *    recommendations -- fixes a segv with crafted jpeg images
93
 * 29/8/17
94
 *  - revert previous warning change: libvips reports serious corruption,
95
 *    like a truncated file, as a warning and we need to be able to catch
96
 *    that
97
 * 9/4/18
98
 *  - set interlaced=1 for interlaced images
99
 * 10/4/18
100
 *  - strict round down on shrink-on-load
101
 * 16/8/18
102
 *  - shut down the input file as soon as we can [kleisauke]
103
 * 20/7/19
104
 *  - close input on minimise rather than Y read position
105
 * 3/10/19
106
 *  - restart after minimise
107
 * 14/10/19
108
 *  - revise for source IO
109
 * 5/5/20 angelmixu
110
 *  - better handling of JFIF res unit 0
111
 * 13/9/20
112
 *  - set resolution unit from JFIF
113
 * 24/7/21
114
 *  - add fail_on support
115
 * 2/8/22
116
 *      - add "unlimited"
117
 */
118
119
/*
120
121
  This file is part of VIPS.
122
123
  VIPS is free software; you can redistribute it and/or modify
124
  it under the terms of the GNU Lesser General Public License as published by
125
  the Free Software Foundation; either version 2 of the License, or
126
  (at your option) any later version.
127
128
  This program is distributed in the hope that it will be useful,
129
  but WITHOUT ANY WARRANTY; without even the implied warranty of
130
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
131
  GNU Lesser General Public License for more details.
132
133
  You should have received a copy of the GNU Lesser General Public License
134
  along with this program; if not, write to the Free Software
135
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
136
  02110-1301  USA
137
138
 */
139
140
/*
141
142
  These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
143
144
 */
145
146
/*
147
#define DEBUG_VERBOSE
148
#define DEBUG
149
 */
150
151
#ifdef HAVE_CONFIG_H
152
#include <config.h>
153
#endif /*HAVE_CONFIG_H*/
154
#include <glib/gi18n-lib.h>
155
156
#ifdef HAVE_JPEG
157
158
#include <stdio.h>
159
#include <stdlib.h>
160
#include <string.h>
161
162
#include <vips/vips.h>
163
#include <vips/buf.h>
164
#include <vips/internal.h>
165
166
#include "pforeign.h"
167
168
#include "jpeg.h"
169
170
0
#define SOURCE_BUFFER_SIZE (4096)
171
172
/* Private struct for source input.
173
 */
174
typedef struct {
175
  /* Public jpeg fields.
176
   */
177
  struct jpeg_source_mgr pub;
178
179
  /* Private stuff during read.
180
   */
181
  ReadJpeg *jpeg;
182
  VipsSource *source;
183
  unsigned char buf[SOURCE_BUFFER_SIZE];
184
185
} Source;
186
187
static void
188
source_init_source(j_decompress_ptr cinfo)
189
15.1k
{
190
  /* No work necessary here.
191
   */
192
15.1k
}
193
194
/* Fill the input buffer -- called whenever buffer is emptied.
195
 */
196
static boolean
197
source_fill_input_buffer(j_decompress_ptr cinfo)
198
0
{
199
0
  Source *src = (Source *) cinfo->src;
200
201
0
  gint64 n_bytes;
202
203
0
  if ((n_bytes =
204
0
    vips_source_read(src->source, src->buf, SOURCE_BUFFER_SIZE)) <= 0) {
205
0
    if (src->jpeg->fail_on >= VIPS_FAIL_ON_TRUNCATED) {
206
      /* Knock the output out of cache.
207
       */
208
0
      vips_foreign_load_invalidate(src->jpeg->out);
209
0
      ERREXIT(cinfo, JERR_VIPS_IMAGE_EOF);
210
0
    }
211
0
    else
212
0
      WARNMS(cinfo, JWRN_VIPS_IMAGE_EOF);
213
214
    /* Insert a fake EOI marker.
215
     */
216
0
    src->buf[0] = (JOCTET) 0xFF;
217
0
    src->buf[1] = (JOCTET) JPEG_EOI;
218
0
    n_bytes = 2;
219
0
  }
220
221
0
  src->pub.next_input_byte = src->buf;
222
0
  src->pub.bytes_in_buffer = n_bytes;
223
224
0
  return TRUE;
225
0
}
226
227
static boolean
228
source_fill_input_buffer_mappable(j_decompress_ptr cinfo)
229
21.2k
{
230
21.2k
  Source *src = (Source *) cinfo->src;
231
232
21.2k
  if (src->jpeg->fail_on >= VIPS_FAIL_ON_TRUNCATED) {
233
    /* Knock the output out of cache.
234
     */
235
0
    vips_foreign_load_invalidate(src->jpeg->out);
236
0
    ERREXIT(cinfo, JERR_VIPS_IMAGE_EOF);
237
0
  }
238
21.2k
  else
239
21.2k
    WARNMS(cinfo, JWRN_VIPS_IMAGE_EOF);
240
241
  /* Insert a fake EOI marker.
242
   */
243
21.2k
  src->buf[0] = (JOCTET) 0xFF;
244
21.2k
  src->buf[1] = (JOCTET) JPEG_EOI;
245
246
21.2k
  src->pub.next_input_byte = src->buf;
247
21.2k
  src->pub.bytes_in_buffer = 2;
248
249
21.2k
  return TRUE;
250
21.2k
}
251
252
static void
253
skip_input_data(j_decompress_ptr cinfo, long num_bytes)
254
0
{
255
0
  struct jpeg_source_mgr *src = cinfo->src;
256
257
0
  if (num_bytes > 0) {
258
0
    while (num_bytes > (long) src->bytes_in_buffer) {
259
0
      num_bytes -= (long) src->bytes_in_buffer;
260
0
      (void) (*src->fill_input_buffer)(cinfo);
261
262
      /* note we assume that fill_input_buffer will never
263
       * return FALSE, so suspension need not be handled.
264
       */
265
0
    }
266
267
0
    src->next_input_byte += (size_t) num_bytes;
268
0
    src->bytes_in_buffer -= (size_t) num_bytes;
269
0
  }
270
0
}
271
272
static void
273
skip_input_data_mappable(j_decompress_ptr cinfo, long num_bytes)
274
8.48k
{
275
8.48k
  struct jpeg_source_mgr *src = cinfo->src;
276
277
8.48k
  if (num_bytes > (long) src->bytes_in_buffer) {
278
304
    src->next_input_byte += src->bytes_in_buffer;
279
304
    src->bytes_in_buffer = 0;
280
304
  }
281
8.18k
  else {
282
8.18k
    src->next_input_byte += (size_t) num_bytes;
283
8.18k
    src->bytes_in_buffer -= (size_t) num_bytes;
284
8.18k
  }
285
8.48k
}
286
287
int
288
vips__readjpeg_open_input(ReadJpeg *jpeg)
289
15.1k
{
290
15.1k
  j_decompress_ptr cinfo = &jpeg->cinfo;
291
292
15.1k
  if (jpeg->source &&
293
15.1k
    !cinfo->src) {
294
15.1k
    Source *src;
295
296
15.1k
    if (vips_source_rewind(jpeg->source))
297
0
      return -1;
298
299
15.1k
    cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small)(
300
15.1k
        (j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(Source));
301
302
15.1k
    src = (Source *) cinfo->src;
303
15.1k
    src->jpeg = jpeg;
304
15.1k
    src->source = jpeg->source;
305
15.1k
    src->pub.init_source = source_init_source;
306
307
    /* Use default method.
308
     */
309
15.1k
    src->pub.resync_to_restart = jpeg_resync_to_restart;
310
311
15.1k
    if (vips_source_is_mappable(jpeg->source)) {
312
15.1k
      size_t src_len;
313
15.1k
      const unsigned char *src_data =
314
15.1k
        vips_source_map(jpeg->source, &src_len);
315
316
15.1k
      src->pub.fill_input_buffer = source_fill_input_buffer_mappable;
317
15.1k
      src->pub.skip_input_data = skip_input_data_mappable;
318
15.1k
      src->pub.bytes_in_buffer = src_len;
319
15.1k
      src->pub.next_input_byte = src_data;
320
15.1k
    }
321
0
    else {
322
0
      src->pub.fill_input_buffer = source_fill_input_buffer;
323
0
      src->pub.skip_input_data = skip_input_data;
324
325
      /* Forces fill_input_buffer on first read.
326
       */
327
0
      src->pub.bytes_in_buffer = 0;
328
329
      /* Until buffer loaded.
330
       */
331
0
      src->pub.next_input_byte = NULL;
332
0
    }
333
15.1k
  }
334
335
15.1k
  return 0;
336
15.1k
}
337
338
static void
339
readjpeg_emit_message(j_common_ptr cinfo, int msg_level)
340
338k
{
341
338k
  ReadJpeg *jpeg = (ReadJpeg *) cinfo->client_data;
342
343
338k
  long num_warnings;
344
345
338k
  if (msg_level < 0) {
346
    /* Always count warnings in num_warnings.
347
     */
348
100k
    num_warnings = ++cinfo->err->num_warnings;
349
350
    /* Corrupt files may give many warnings, the policy here is to
351
     * show only the first warning and treat many warnings as fatal,
352
     * unless unlimited is set.
353
     */
354
100k
    if (num_warnings == 1)
355
13.8k
      (*cinfo->err->output_message)(cinfo);
356
86.4k
    else if (!jpeg ||
357
86.4k
      (!jpeg->unlimited && num_warnings >= 100))
358
136
      cinfo->err->error_exit(cinfo);
359
100k
  }
360
237k
  else if (cinfo->err->trace_level >= msg_level)
361
    /* It's a trace message. Show it if trace_level >= msg_level.
362
     */
363
0
    (*cinfo->err->output_message)(cinfo);
364
338k
}
365
366
/* This can be called many times.
367
 */
368
static int
369
readjpeg_free(ReadJpeg *jpeg)
370
15.1k
{
371
15.1k
  if (jpeg->eman.pub.num_warnings != 0) {
372
13.8k
    g_warning("read gave %ld warnings", jpeg->eman.pub.num_warnings);
373
13.8k
    g_warning("%s", vips_error_buffer());
374
375
    /* Make the message only appear once.
376
     */
377
13.8k
    jpeg->eman.pub.num_warnings = 0;
378
13.8k
  }
379
380
  /* Don't call jpeg_finish_decompress(). It just checks the tail of the
381
   * file and who cares about that. All mem is freed in
382
   * jpeg_destroy_decompress().
383
   */
384
385
  /* I don't think this can fail. It's harmless to call many times.
386
   */
387
15.1k
  jpeg_destroy_decompress(&jpeg->cinfo);
388
389
15.1k
  VIPS_UNREF(jpeg->source);
390
391
15.1k
  return 0;
392
15.1k
}
393
394
static void
395
readjpeg_close_cb(VipsImage *image, ReadJpeg *jpeg)
396
15.1k
{
397
15.1k
  (void) readjpeg_free(jpeg);
398
15.1k
}
399
400
static void
401
readjpeg_minimise_cb(VipsImage *image, ReadJpeg *jpeg)
402
15.7k
{
403
15.7k
  vips_source_minimise(jpeg->source);
404
15.7k
}
405
406
/* Shared with uhdr load (for fast uhdr detect).
407
 */
408
ReadJpeg *
409
vips__readjpeg_new(VipsSource *source, VipsImage *out,
410
  int shrink, VipsFailOn fail_on, gboolean autorotate,
411
  gboolean unlimited)
412
15.1k
{
413
15.1k
  ReadJpeg *jpeg;
414
415
15.1k
  if (!(jpeg = VIPS_NEW(out, ReadJpeg)))
416
0
    return NULL;
417
418
15.1k
  jpeg->out = out;
419
15.1k
  jpeg->source = source;
420
15.1k
  g_object_ref(source);
421
15.1k
  jpeg->shrink = shrink;
422
15.1k
  jpeg->fail_on = fail_on;
423
15.1k
  jpeg->cinfo.err = jpeg_std_error(&jpeg->eman.pub);
424
15.1k
  jpeg->cinfo.err->addon_message_table = vips__jpeg_message_table;
425
15.1k
  jpeg->cinfo.err->first_addon_message = 1000;
426
15.1k
  jpeg->cinfo.err->last_addon_message = 1001;
427
15.1k
  jpeg->eman.pub.error_exit = vips__new_error_exit;
428
15.1k
  jpeg->eman.pub.emit_message = readjpeg_emit_message;
429
15.1k
  jpeg->eman.pub.output_message = vips__new_output_message;
430
15.1k
  jpeg->eman.fp = NULL;
431
15.1k
  jpeg->autorotate = autorotate;
432
15.1k
  jpeg->unlimited = unlimited;
433
15.1k
  jpeg->cinfo.client_data = jpeg;
434
435
  /* jpeg_create_decompress() can fail on some sanity checks. Don't
436
   * readjpeg_free() since we don't want to jpeg_destroy_decompress().
437
   */
438
15.1k
  if (setjmp(jpeg->eman.jmp))
439
0
    return NULL;
440
441
15.1k
  jpeg_create_decompress(&jpeg->cinfo);
442
443
15.1k
  g_signal_connect(out, "close", G_CALLBACK(readjpeg_close_cb), jpeg);
444
15.1k
  g_signal_connect(out, "minimise", G_CALLBACK(readjpeg_minimise_cb), jpeg);
445
446
15.1k
  return jpeg;
447
15.1k
}
448
449
static const char *
450
find_chroma_subsample(struct jpeg_decompress_struct *cinfo)
451
8.98k
{
452
  /* libjpeg only uses 4:4:4 and 4:2:0, confusingly.
453
   *
454
   * http://poynton.ca/PDFs/Chroma_subsampling_notation.pdf
455
   */
456
8.98k
  gboolean has_subsample = cinfo->max_h_samp_factor > 1 ||
457
2.21k
    cinfo->max_v_samp_factor > 1;
458
8.98k
  gboolean is_cmyk = cinfo->num_components > 3;
459
460
8.98k
  return is_cmyk
461
8.98k
    ? (has_subsample ? "4:2:0:4" : "4:4:4:4")
462
8.98k
    : (has_subsample ? "4:2:0" : "4:4:4");
463
8.98k
}
464
465
static void
466
attach_blob(VipsImage *im, const char *field, void *data, size_t data_length)
467
6.92k
{
468
  /* Only use the first one.
469
   */
470
6.92k
  if (vips_image_get_typeof(im, field)) {
471
#ifdef DEBUG
472
    printf("attach_blob: second %s block, ignoring\n", field);
473
#endif /*DEBUG*/
474
475
4.76k
    return;
476
4.76k
  }
477
478
#ifdef DEBUG
479
  printf("attach_blob: attaching %zd bytes of %s\n",
480
    data_length, field);
481
#endif /*DEBUG*/
482
483
2.15k
  vips_image_set_blob_copy(im, field, data, data_length);
484
2.15k
}
485
486
/* data is the XMP string ... it'll have something like
487
 * "http://ns.adobe.com/xap/1.0/" at the front, then a null character, then
488
 * the real XMP.
489
 */
490
static void
491
attach_xmp_blob(VipsImage *im, char *data, size_t data_length)
492
3.50k
{
493
  /* Search for a null char within the first few characters. 80
494
   * should be plenty for a basic URL.
495
   *
496
   * -2 for the extra null.
497
   */
498
3.50k
  char *p = memchr(data, '\0', VIPS_MIN(80, data_length - 2));
499
3.50k
  if (!p)
500
226
    return;
501
502
3.28k
  size_t i = p - data;
503
3.28k
  data_length -= i + 1;
504
505
3.28k
  attach_blob(im, VIPS_META_XMP_NAME,
506
3.28k
    data + i + 1, data_length);
507
3.28k
}
508
509
/* Number of app2 sections we can capture. Each one can be 64k, so 6400k should
510
 * be enough for anyone (haha).
511
 */
512
20.5k
#define MAX_APP2_SECTIONS (100)
513
514
/* Read a cinfo to a VIPS image. Set invert_pels if the pixel reader needs to
515
 * do 255-pel.
516
 */
517
static int
518
read_jpeg_header(ReadJpeg *jpeg, VipsImage *out)
519
9.60k
{
520
9.60k
  struct jpeg_decompress_struct *cinfo = &jpeg->cinfo;
521
522
9.60k
  jpeg_saved_marker_ptr p;
523
9.60k
  VipsInterpretation interpretation;
524
9.60k
  double xres, yres;
525
526
  /* Capture app2 sections here for assembly.
527
   */
528
9.60k
  void *app2_data[MAX_APP2_SECTIONS] = { 0 };
529
9.60k
  size_t app2_data_length[MAX_APP2_SECTIONS] = { 0 };
530
9.60k
  size_t data_length;
531
9.60k
  int i;
532
533
  /* Read JPEG header. libjpeg will set out_color_space sanely for us
534
   * for YUV YCCK etc.
535
   */
536
9.60k
  jpeg_read_header(cinfo, TRUE);
537
9.60k
  cinfo->scale_denom = jpeg->shrink;
538
9.60k
  cinfo->scale_num = 1;
539
9.60k
  jpeg_calc_output_dimensions(cinfo);
540
541
9.60k
  jpeg->invert_pels = FALSE;
542
9.60k
  switch (cinfo->out_color_space) {
543
3.33k
  case JCS_GRAYSCALE:
544
3.33k
    interpretation = VIPS_INTERPRETATION_B_W;
545
3.33k
    break;
546
547
1.15k
  case JCS_CMYK:
548
1.15k
    interpretation = VIPS_INTERPRETATION_CMYK;
549
550
    /* CMYKs are almost always returned inverted, but see below.
551
     */
552
1.15k
    jpeg->invert_pels = TRUE;
553
1.15k
    break;
554
555
4.01k
  case JCS_RGB:
556
4.49k
  default:
557
4.49k
    interpretation = VIPS_INTERPRETATION_sRGB;
558
4.49k
    break;
559
9.60k
  }
560
561
#ifdef DEBUG
562
  if (cinfo->saw_JFIF_marker)
563
    printf("read_jpeg_header: jfif _density %d, %d, unit %d\n",
564
      cinfo->X_density, cinfo->Y_density,
565
      cinfo->density_unit);
566
#endif /*DEBUG*/
567
568
  /* Get the jfif resolution. exif may overwrite this later. Default to
569
   * 72dpi (as EXIF does).
570
   */
571
8.98k
  xres = 72.0 / 25.4;
572
8.98k
  yres = 72.0 / 25.4;
573
8.98k
  if (cinfo->saw_JFIF_marker &&
574
418
    cinfo->X_density != 1U &&
575
391
    cinfo->Y_density != 1U) {
576
386
    switch (cinfo->density_unit) {
577
46
    case 0:
578
      /* X_density / Y_density gives the pixel aspect ratio.
579
       * Leave xres, but adjust yres.
580
       */
581
46
      if (cinfo->Y_density > 0)
582
23
        yres = xres * cinfo->X_density /
583
23
          cinfo->Y_density;
584
46
      break;
585
586
30
    case 1:
587
      /* Pixels per inch.
588
       */
589
30
      xres = cinfo->X_density / 25.4;
590
30
      yres = cinfo->Y_density / 25.4;
591
30
      vips_image_set_string(out,
592
30
        VIPS_META_RESOLUTION_UNIT, "in");
593
30
      break;
594
595
224
    case 2:
596
      /* Pixels per cm.
597
       */
598
224
      xres = cinfo->X_density / 10.0;
599
224
      yres = cinfo->Y_density / 10.0;
600
224
      vips_image_set_string(out,
601
224
        VIPS_META_RESOLUTION_UNIT, "cm");
602
224
      break;
603
604
86
    default:
605
86
      g_warning("unknown JFIF resolution unit");
606
86
      break;
607
386
    }
608
609
#ifdef DEBUG
610
    printf("read_jpeg_header: seen jfif resolution %g, %g p/mm\n",
611
      xres, yres);
612
#endif /*DEBUG*/
613
386
  }
614
615
  /* Set VIPS header.
616
   */
617
8.98k
  vips_image_init_fields(out,
618
8.98k
    cinfo->output_width, cinfo->output_height,
619
8.98k
    cinfo->output_components,
620
8.98k
    VIPS_FORMAT_UCHAR, VIPS_CODING_NONE,
621
8.98k
    interpretation,
622
8.98k
    xres, yres);
623
624
8.98k
  VIPS_SETSTR(out->filename,
625
8.98k
    vips_connection_filename(VIPS_CONNECTION(jpeg->source)));
626
627
8.98k
  if (vips_image_pipelinev(out, VIPS_DEMAND_STYLE_FATSTRIP, NULL))
628
0
    return -1;
629
630
  /* cinfo->output_width and cinfo->output_height round up with
631
   * shrink-on-load. For example, if the image is 1801 pixels across and
632
   * we shrink by 4, the output will be 450.25 pixels across,
633
   * cinfo->output_width with be 451, and libjpeg will write a black
634
   * column of pixels down the right.
635
   *
636
   * We must strictly round down, since we don't want fractional pixels
637
   * along the bottom and right.
638
   */
639
8.98k
  jpeg->output_width = cinfo->image_width / jpeg->shrink;
640
8.98k
  jpeg->output_height = cinfo->image_height / jpeg->shrink;
641
642
  /* Interlaced jpegs need lots of memory to read, so our caller needs
643
   * to know.
644
   */
645
8.98k
  (void) vips_image_set_int(out, "jpeg-multiscan",
646
8.98k
    jpeg_has_multiple_scans(cinfo));
647
648
  /* 8.7 adds this for PNG as well, so we have a new format-neutral name.
649
   */
650
8.98k
  if (jpeg_has_multiple_scans(cinfo))
651
7.28k
    vips_image_set_int(out, "interlaced", 1);
652
653
8.98k
  (void) vips_image_set_string(out, "jpeg-chroma-subsample",
654
8.98k
    find_chroma_subsample(cinfo));
655
656
  /* Look for EXIF and ICC profile.
657
   */
658
20.3k
  for (p = cinfo->marker_list; p; p = p->next) {
659
#ifdef DEBUG
660
    {
661
      printf("read_jpeg_header: seen %u bytes of APP%d\n",
662
        p->data_length,
663
        p->marker - JPEG_APP0);
664
665
      i = 0;
666
      for (int row = 0; i < VIPS_MIN(100, p->data_length); row++) {
667
        printf(" 0x%02x)", i);
668
669
        for (int col = 0; col < 8 &&
670
            i < VIPS_MIN(100, p->data_length); col++, i++) {
671
          printf(" %02x", p->data[i]);
672
          if (p->data[i] > 32 && p->data[i] < 127)
673
            printf(" '%c'", p->data[i]);
674
          else
675
            printf("    ");
676
        }
677
678
        printf("\n");
679
      }
680
    }
681
#endif /*DEBUG*/
682
683
11.3k
    switch (p->marker) {
684
7.24k
    case JPEG_APP0 + 1:
685
      /* Possible EXIF or XMP data.
686
       */
687
7.24k
      if (p->data_length > 4 &&
688
7.03k
        vips_isprefix("Exif", (char *) p->data))
689
2.89k
        attach_blob(out, VIPS_META_EXIF_NAME,
690
2.89k
          p->data, p->data_length);
691
692
7.24k
      if (p->data_length > 4 &&
693
7.03k
        vips_isprefix("http", (char *) p->data))
694
3.50k
        attach_xmp_blob(out,
695
3.50k
          (char *) p->data, p->data_length);
696
697
7.24k
      break;
698
699
3.40k
    case JPEG_APP0 + 2:
700
      /* Possible ICC profile.
701
       */
702
3.40k
      if (p->data_length > 14 &&
703
3.09k
        vips_isprefix("ICC_PROFILE",
704
3.09k
          (char *) p->data)) {
705
        /* cur_marker numbers from 1, according to
706
         * spec.
707
         */
708
1.60k
        int cur_marker = p->data[12] - 1;
709
710
1.60k
        if (cur_marker >= 0 &&
711
1.44k
          cur_marker < MAX_APP2_SECTIONS) {
712
1.00k
          app2_data[cur_marker] = p->data + 14;
713
1.00k
          app2_data_length[cur_marker] =
714
1.00k
            p->data_length - 14;
715
1.00k
        }
716
1.60k
      }
717
3.40k
      break;
718
719
723
    case JPEG_APP0 + 13:
720
      /* Possible IPTC data block.
721
       */
722
723
      if (p->data_length > 5 &&
723
457
        vips_isprefix("Photo", (char *) p->data)) {
724
372
        attach_blob(out, VIPS_META_IPTC_NAME,
725
372
          p->data, p->data_length);
726
727
        /* Older versions of libvips used this misspelt
728
         * name :-( attach under this name too for
729
         * compatibility.
730
         */
731
372
        attach_blob(out, "ipct-data",
732
372
          p->data, p->data_length);
733
372
      }
734
723
      break;
735
736
0
    case JPEG_APP0 + 14:
737
      /* Adobe block. There's a lot of confusion about
738
       * whether or not CMYK jpg images are inverted. For
739
       * the images we have, it seems they should always
740
       * invert.
741
       *
742
       * See: https://sno.phy.queensu.ca/~phil/exiftool/\
743
       *  TagNames/JPEG.html#Adobe
744
       *
745
       * data[11] == 0 - unknown
746
       * data[11] == 1 - YCbCr
747
       * data[11] == 2 - YCCK
748
       *
749
       * Leave this code here in case we come up with a
750
       * better rule. Make sure to also uncomment
751
       * jpeg_save_markers() for the APP14 marker.
752
       */
753
0
      if (p->data_length >= 12 &&
754
0
        vips_isprefix("Adobe", (char *) p->data)) {
755
0
        if (p->data[11] == 0) {
756
#ifdef DEBUG
757
          printf("complete Adobe block, not YCCK image\n");
758
#endif        /*DEBUG*/
759
          // jpeg->invert_pels = FALSE;
760
0
        }
761
0
      }
762
0
      break;
763
764
0
    default:
765
#ifdef DEBUG
766
      printf("read_jpeg_header: "
767
           "ignoring %u byte APP%d block\n",
768
        p->data_length, p->marker - JPEG_APP0);
769
#endif /*DEBUG*/
770
0
      break;
771
11.3k
    }
772
11.3k
  }
773
774
  /* Assemble ICC sections.
775
   */
776
8.98k
  data_length = 0;
777
9.17k
  for (i = 0; i < MAX_APP2_SECTIONS && app2_data[i]; i++)
778
190
    data_length += app2_data_length[i];
779
8.98k
  if (data_length) {
780
173
    unsigned char *data;
781
173
    int p;
782
783
#ifdef DEBUG
784
    printf("read_jpeg_header: assembled %zd byte ICC profile\n",
785
      data_length);
786
#endif /*DEBUG*/
787
788
173
    if (!(data = vips_malloc(NULL, data_length)))
789
0
      return -1;
790
791
173
    p = 0;
792
363
    for (i = 0; i < MAX_APP2_SECTIONS && app2_data[i]; i++) {
793
190
      memcpy(data + p, app2_data[i], app2_data_length[i]);
794
190
      p += app2_data_length[i];
795
190
    }
796
797
173
    vips_image_set_blob(out, VIPS_META_ICC_NAME,
798
173
      (VipsCallbackFn) vips_area_free_cb, data, data_length);
799
173
  }
800
801
8.98k
  return 0;
802
8.98k
}
803
804
static int
805
read_jpeg_generate(VipsRegion *out_region,
806
  void *seq, void *a, void *b, gboolean *stop)
807
13.4k
{
808
13.4k
  VipsRect *r = &out_region->valid;
809
13.4k
  ReadJpeg *jpeg = (ReadJpeg *) a;
810
13.4k
  struct jpeg_decompress_struct *cinfo = &jpeg->cinfo;
811
13.4k
  int sz = cinfo->output_width * cinfo->output_components;
812
813
13.4k
  int y;
814
815
#ifdef DEBUG_VERBOSE
816
  printf("read_jpeg_generate: %p line %d, %d rows\n",
817
    g_thread_self(), r->top, r->height);
818
#endif /*DEBUG_VERBOSE*/
819
820
13.4k
  VIPS_GATE_START("read_jpeg_generate: work");
821
822
  /* We're inside a tilecache where tiles are the full image width, so
823
   * this should always be true.
824
   */
825
13.4k
  g_assert(r->left == 0);
826
13.4k
  g_assert(r->width == out_region->im->Xsize);
827
13.4k
  g_assert(VIPS_RECT_BOTTOM(r) <= out_region->im->Ysize);
828
829
  /* Tiles should always be on a 8-pixel boundary.
830
   */
831
13.4k
  g_assert(r->top % 8 == 0);
832
833
  /* Tiles should always be a strip in height, unless it's the final
834
   * strip.
835
   */
836
13.4k
  g_assert(r->height == VIPS_MIN(8, out_region->im->Ysize - r->top));
837
838
  /* And check that the y position is correct. It should be, since we are
839
   * inside a vips_sequential().
840
   */
841
13.4k
  if (r->top != cinfo->output_scanline) {
842
0
    VIPS_GATE_STOP("read_jpeg_generate: work");
843
0
    vips_error("VipsJpeg", _("out of order read at line %d"),
844
0
      cinfo->output_scanline);
845
846
0
    return -1;
847
0
  }
848
849
  /* Here for longjmp() from vips__new_error_exit() during
850
   * jpeg_read_scanlines().
851
   */
852
13.4k
  if (setjmp(jpeg->eman.jmp)) {
853
765
    VIPS_GATE_STOP("read_jpeg_generate: work");
854
855
#ifdef DEBUG
856
    printf("read_jpeg_generate() exit\n");
857
#endif /*DEBUG*/
858
859
765
    return -1;
860
765
  }
861
862
12.6k
  if (jpeg->eman.pub.num_warnings > 0 &&
863
13.2k
    jpeg->fail_on >= VIPS_FAIL_ON_WARNING) {
864
0
    VIPS_GATE_STOP("read_jpeg_generate: work");
865
866
    /* Only fail once.
867
     */
868
0
    jpeg->eman.pub.num_warnings = 0;
869
870
0
    return -1;
871
0
  }
872
873
109k
  for (y = 0; y < r->height; y++) {
874
96.5k
    JSAMPROW row_pointer[1];
875
876
96.5k
    row_pointer[0] = (JSAMPLE *)
877
96.5k
      VIPS_REGION_ADDR(out_region, 0, r->top + y);
878
879
96.5k
    jpeg_read_scanlines(cinfo, &row_pointer[0], 1);
880
881
96.5k
    if (jpeg->invert_pels) {
882
25.7k
      int x;
883
884
8.64M
      for (x = 0; x < sz; x++)
885
8.61M
        row_pointer[0][x] = 255 - row_pointer[0][x];
886
25.7k
    }
887
96.5k
  }
888
889
12.6k
  VIPS_GATE_STOP("read_jpeg_generate: work");
890
891
12.6k
  return 0;
892
12.6k
}
893
894
/* Read a cinfo to a VIPS image.
895
 */
896
static int
897
read_jpeg_image(ReadJpeg *jpeg, VipsImage *out)
898
4.05k
{
899
4.05k
  struct jpeg_decompress_struct *cinfo = &jpeg->cinfo;
900
4.05k
  VipsImage **t = (VipsImage **)
901
4.05k
    vips_object_local_array(VIPS_OBJECT(out), 5);
902
903
4.05k
  VipsImage *im;
904
905
  /* Here for longjmp() from vips__new_error_exit() during
906
   * jpeg_read_header() or jpeg_start_decompress().
907
   */
908
4.05k
  if (setjmp(jpeg->eman.jmp))
909
1.76k
    return -1;
910
911
2.29k
  t[0] = vips_image_new();
912
2.29k
  if (read_jpeg_header(jpeg, t[0]))
913
0
    return -1;
914
915
  /* Switch to pixel decode.
916
   */
917
2.29k
  if (vips_source_decode(jpeg->source))
918
0
    return -1;
919
920
2.29k
  jpeg_start_decompress(cinfo);
921
922
#ifdef DEBUG
923
  printf("read_jpeg_image: starting decompress\n");
924
#endif /*DEBUG*/
925
926
  /* We must crop after the seq, or our generate may not be asked for
927
   * full lines of pixels and will attempt to write beyond the buffer.
928
   */
929
2.29k
  if (vips_image_generate(t[0],
930
2.29k
      NULL, read_jpeg_generate, NULL,
931
2.29k
      jpeg, NULL) ||
932
2.29k
    vips_sequential(t[0], &t[1],
933
2.29k
      "tile_height", 8,
934
2.29k
      NULL) ||
935
2.29k
    vips_extract_area(t[1], &t[2],
936
2.29k
      0, 0, jpeg->output_width, jpeg->output_height, NULL))
937
0
    return -1;
938
2.29k
  im = t[2];
939
940
2.29k
  if (jpeg->autorotate &&
941
0
    vips_image_get_orientation(im) != 1) {
942
    /* We have to copy to memory before calling autorot, since it
943
     * needs random access.
944
     */
945
0
    if (!(t[3] = vips_image_copy_memory(im)) ||
946
0
      vips_autorot(t[3], &t[4], NULL))
947
0
      return -1;
948
0
    im = t[4];
949
0
  }
950
951
2.29k
  if (vips_image_write(im, out))
952
765
    return -1;
953
954
1.52k
  return 0;
955
2.29k
}
956
957
static int
958
jpeg_read(ReadJpeg *jpeg, VipsImage *out, gboolean header_only)
959
9.60k
{
960
  /* Need to read in APP1 (EXIF/XMP metadata), APP2 (ICC profile) and APP13
961
   * (photoshop IPTC).
962
   */
963
9.60k
  jpeg_save_markers(&jpeg->cinfo, JPEG_APP0 + 1, 0xffff);
964
9.60k
  jpeg_save_markers(&jpeg->cinfo, JPEG_APP0 + 2, 0xffff);
965
9.60k
  jpeg_save_markers(&jpeg->cinfo, JPEG_APP0 + 13, 0xffff);
966
967
  /* APP14 (Adobe flags), deliberately ignored, see above.
968
   */
969
  // jpeg_save_markers(&jpeg->cinfo, JPEG_APP0 + 14, 0xffff);
970
971
#ifdef DEBUG
972
  {
973
    int i;
974
975
    /* Handy for debugging ... spot any extra  markers.
976
     */
977
    for (i = 0; i < 16; i++)
978
      jpeg_save_markers(&jpeg->cinfo, JPEG_APP0 + i, 0xffff);
979
  }
980
#endif /*DEBUG*/
981
982
  /* Convert!
983
   */
984
9.60k
  if (header_only) {
985
5.55k
    if (read_jpeg_header(jpeg, out))
986
0
      return -1;
987
988
    /* Patch in the correct size.
989
     */
990
5.55k
    out->Xsize = jpeg->output_width;
991
5.55k
    out->Ysize = jpeg->output_height;
992
993
    /* Swap width and height if we're going to rotate this image.
994
     */
995
5.55k
    if (jpeg->autorotate) {
996
0
      if (vips_image_get_orientation_swap(out))
997
0
        VIPS_SWAP(int, out->Xsize, out->Ysize);
998
999
0
      vips_autorot_remove_angle(out);
1000
0
    }
1001
5.55k
  }
1002
4.05k
  else {
1003
4.05k
    if (read_jpeg_image(jpeg, out))
1004
2.52k
      return -1;
1005
4.05k
  }
1006
1007
7.08k
  return 0;
1008
9.60k
}
1009
1010
int
1011
vips__jpeg_read_source(VipsSource *source, VipsImage *out,
1012
  gboolean header_only, int shrink, VipsFailOn fail_on,
1013
  gboolean autorotate, gboolean unlimited)
1014
9.60k
{
1015
9.60k
  ReadJpeg *jpeg;
1016
1017
9.60k
  if (!(jpeg = vips__readjpeg_new(source, out, shrink, fail_on,
1018
9.60k
        autorotate, unlimited)))
1019
0
    return -1;
1020
1021
  /* Here for longjmp() from vips__new_error_exit() during
1022
   * cinfo->mem->alloc_small() or jpeg_read_header().
1023
   */
1024
9.60k
  if (setjmp(jpeg->eman.jmp))
1025
622
    return -1;
1026
1027
8.98k
  if (vips__readjpeg_open_input(jpeg) ||
1028
9.60k
    jpeg_read(jpeg, out, header_only))
1029
2.52k
    return -1;
1030
1031
6.45k
  if (header_only)
1032
4.93k
    vips_source_minimise(source);
1033
1034
6.45k
  return 0;
1035
8.98k
}
1036
1037
int
1038
vips__isjpeg_source(VipsSource *source)
1039
73.1k
{
1040
73.1k
  const unsigned char *p;
1041
1042
73.1k
  if ((p = vips_source_sniff(source, 2)) &&
1043
73.1k
    p[0] == 0xff &&
1044
29.4k
    p[1] == 0xd8)
1045
11.1k
    return 1;
1046
1047
62.0k
  return 0;
1048
73.1k
}
1049
1050
#endif /*HAVE_JPEG*/