Coverage Report

Created: 2026-12-01 06:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libwebp/imageio/tiffdec.c
Line
Count
Source
1
// Copyright 2012 Google Inc. All Rights Reserved.
2
//
3
// Use of this source code is governed by a BSD-style license
4
// that can be found in the COPYING file in the root of the source
5
// tree. An additional intellectual property rights grant can be found
6
// in the file PATENTS. All contributing project authors may
7
// be found in the AUTHORS file in the root of the source tree.
8
// -----------------------------------------------------------------------------
9
//
10
// TIFF decode.
11
12
#include "./tiffdec.h"
13
14
#ifdef HAVE_CONFIG_H
15
#include "webp/config.h"
16
#endif
17
18
#include <limits.h>
19
#include <stdio.h>
20
#include <string.h>
21
22
#ifdef WEBP_HAVE_TIFF
23
#include <tiff.h>
24
#include <tiffio.h>
25
26
#include "./imageio_util.h"
27
#include "./metadata.h"
28
#include "webp/encode.h"
29
#include "webp/types.h"
30
31
static const struct {
32
  ttag_t tag;
33
  size_t storage_offset;
34
} kTIFFMetadataMap[] = {
35
    {TIFFTAG_ICCPROFILE, METADATA_OFFSET(iccp)},
36
    {TIFFTAG_XMLPACKET, METADATA_OFFSET(xmp)},
37
    {0, 0},
38
};
39
40
// Returns true on success. The caller must use MetadataFree() on 'metadata' in
41
// all cases.
42
static int ExtractMetadataFromTIFF(TIFF* const tif, Metadata* const metadata) {
43
  int i;
44
  toff_t exif_ifd_offset;
45
46
  for (i = 0; kTIFFMetadataMap[i].tag != 0; ++i) {
47
    MetadataPayload* const payload =
48
        (MetadataPayload*)((uint8_t*)metadata +
49
                           kTIFFMetadataMap[i].storage_offset);
50
    void* tag_data;
51
    uint32_t tag_data_len;
52
53
    if (TIFFGetField(tif, kTIFFMetadataMap[i].tag, &tag_data_len, &tag_data) &&
54
        !MetadataCopy((const char*)tag_data, tag_data_len, payload)) {
55
      return 0;
56
    }
57
  }
58
59
  // TODO(jzern): To extract the raw EXIF directory some parsing of it would be
60
  // necessary to determine the overall size. In addition, value offsets in
61
  // individual directory entries may need to be updated as, depending on the
62
  // type, they are file based.
63
  // Exif 2.2 Section 4.6.2 Tag Structure
64
  // TIFF Revision 6.0 Part 1 Section 2 TIFF Structure #Image File Directory
65
  if (TIFFGetField(tif, TIFFTAG_EXIFIFD, &exif_ifd_offset)) {
66
    fprintf(stderr, "Warning: EXIF extraction from TIFF is unsupported.\n");
67
  }
68
  return 1;
69
}
70
71
// Ad-hoc structure to supply read-from-memory functionalities.
72
typedef struct {
73
  const uint8_t* data;
74
  toff_t size;
75
  toff_t pos;
76
} MyData;
77
78
static int MyClose(thandle_t opaque) {
79
  (void)opaque;
80
  return 0;
81
}
82
83
static toff_t MySize(thandle_t opaque) {
84
  const MyData* const my_data = (MyData*)opaque;
85
  return my_data->size;
86
}
87
88
static toff_t MySeek(thandle_t opaque, toff_t offset, int whence) {
89
  MyData* const my_data = (MyData*)opaque;
90
  offset += (whence == SEEK_CUR)   ? my_data->pos
91
            : (whence == SEEK_SET) ? 0
92
                                   : my_data->size;
93
  if (offset > my_data->size) return (toff_t)-1;
94
  my_data->pos = offset;
95
  return offset;
96
}
97
98
static int MyMapFile(thandle_t opaque, void** base, toff_t* size) {
99
  (void)opaque;
100
  (void)base;
101
  (void)size;
102
  return 0;
103
}
104
static void MyUnmapFile(thandle_t opaque, void* base, toff_t size) {
105
  (void)opaque;
106
  (void)base;
107
  (void)size;
108
}
109
110
static tsize_t MyRead(thandle_t opaque, void* dst, tsize_t size) {
111
  MyData* const my_data = (MyData*)opaque;
112
  if (my_data->pos + size > my_data->size) {
113
    size = (tsize_t)(my_data->size - my_data->pos);
114
  }
115
  if (size > 0) {
116
    memcpy(dst, my_data->data + my_data->pos, size);
117
    my_data->pos += size;
118
  }
119
  return size;
120
}
121
122
// Unmultiply Argb data. Taken from dsp/alpha_processing
123
// (we don't want to force a dependency to a libdspdec library).
124
#define MFIX 24  // 24bit fixed-point arithmetic
125
#define HALF ((1u << MFIX) >> 1)
126
127
static uint32_t Unmult(uint8_t x, uint32_t mult) {
128
  const uint32_t v = (x * mult + HALF) >> MFIX;
129
  return (v > 255u) ? 255u : v;
130
}
131
132
static WEBP_INLINE uint32_t GetScale(uint32_t a) { return (255u << MFIX) / a; }
133
134
#undef MFIX
135
#undef HALF
136
137
static void MultARGBRow(uint8_t* ptr, int width) {
138
  int x;
139
  for (x = 0; x < width; ++x, ptr += 4) {
140
    const uint32_t alpha = ptr[3];
141
    if (alpha < 255) {
142
      if (alpha == 0) {  // alpha == 0
143
        ptr[0] = ptr[1] = ptr[2] = 0;
144
      } else {
145
        const uint32_t scale = GetScale(alpha);
146
        ptr[0] = Unmult(ptr[0], scale);
147
        ptr[1] = Unmult(ptr[1], scale);
148
        ptr[2] = Unmult(ptr[2], scale);
149
      }
150
    }
151
  }
152
}
153
154
static int ReadTIFFInternal(const uint8_t* const data, size_t data_size,
155
                            WebPPicture* const pic, int keep_alpha,
156
                            Metadata* const metadata, int* const width_out,
157
                            int* const height_out) {
158
  MyData my_data = {data, (toff_t)data_size, 0};
159
  TIFF* tif;
160
  uint32_t image_width, image_height, tile_width, tile_height;
161
  uint64_t stride;
162
  uint16_t samples_per_px = 0;
163
  uint16_t extra_samples = 0;
164
  uint16_t* extra_samples_ptr = NULL;
165
  uint32_t* raster;
166
  int64_t alloc_size;
167
  int ok = 0;
168
  tdir_t dircount;
169
  TIFFErrorHandler prev_error_handler = NULL;
170
  TIFFErrorHandler prev_warning_handler = NULL;
171
172
  if (data == NULL || data_size < 4 || data_size > INT_MAX ||
173
      (data[0] != 'I' && data[0] != 'M') || data[0] != data[1]) {
174
    return 0;
175
  }
176
  if (pic == NULL && (width_out == NULL || height_out == NULL)) return 0;
177
178
  if (pic == NULL) {
179
    prev_error_handler = TIFFSetErrorHandler(NULL);
180
    prev_warning_handler = TIFFSetWarningHandler(NULL);
181
  }
182
183
  tif = TIFFClientOpen("Memory", "r", &my_data, MyRead, MyRead, MySeek, MyClose,
184
                       MySize, MyMapFile, MyUnmapFile);
185
  if (tif == NULL) {
186
    if (pic != NULL) fprintf(stderr, "Error! Cannot parse TIFF file\n");
187
    if (pic == NULL) {
188
      TIFFSetErrorHandler(prev_error_handler);
189
      TIFFSetWarningHandler(prev_warning_handler);
190
    }
191
    return 0;
192
  }
193
194
  if (!(TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &image_width) &&
195
        TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &image_height) &&
196
        image_width > 0 && image_height > 0 && image_width <= INT_MAX &&
197
        image_height <= INT_MAX)) {
198
    if (pic != NULL) {
199
      fprintf(stderr, "Error! Cannot retrieve TIFF image dimensions.\n");
200
    }
201
    goto End;
202
  }
203
  stride = (uint64_t)image_width * sizeof(*raster);
204
  if (!ImgIoUtilCheckSizeArgumentsOverflow(stride, image_height)) {
205
    if (pic != NULL) {
206
      fprintf(stderr, "Error! TIFF image dimension (%d x %d) is too large.\n",
207
              image_width, image_height);
208
    }
209
    goto End;
210
  }
211
212
  // According to spec, a tile can be bigger than the image. However it should
213
  // be a multiple of 16 and not way too large, so check that it's not more
214
  // than twice the image size, for dimensions above some arbitrary minimum
215
  // 32. We also check that they respect WebP's dimension and memory limit.
216
  // Note that a tile can be 6byte/px in some cases. Here we assume
217
  // 4byte/px with sizeof(*raster), to be conservative.
218
  if (TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width) &&
219
      TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height)) {
220
    if ((tile_width > 32 && tile_width / 2 > image_width) ||
221
        (tile_height > 32 && tile_height / 2 > image_height) ||
222
        !ImgIoUtilCheckSizeArgumentsOverflow(
223
            (uint64_t)tile_width * sizeof(*raster), tile_height)) {
224
      if (pic != NULL) {
225
        fprintf(stderr, "Error! TIFF tile dimension (%d x %d) is too large.\n",
226
                tile_width, tile_height);
227
      }
228
      goto End;
229
    }
230
  }
231
232
  if (width_out != NULL) *width_out = (int)image_width;
233
  if (height_out != NULL) *height_out = (int)image_height;
234
  if (pic == NULL) {
235
    ok = 1;
236
    goto End;
237
  }
238
239
  dircount = TIFFNumberOfDirectories(tif);
240
  if (dircount > 1) {
241
    fprintf(stderr,
242
            "Warning: multi-directory TIFF files are not supported.\n"
243
            "Only the first will be used, %d will be ignored.\n",
244
            dircount - 1);
245
  }
246
  if (!TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &samples_per_px)) {
247
    fprintf(stderr, "Error! Cannot retrieve TIFF samples-per-pixel info.\n");
248
    goto End;
249
  }
250
  if (!(samples_per_px == 1 || samples_per_px == 3 || samples_per_px == 4)) {
251
    goto End;  // not supported
252
  }
253
254
  if (samples_per_px > 3 && !TIFFGetField(tif, TIFFTAG_EXTRASAMPLES,
255
                                          &extra_samples, &extra_samples_ptr)) {
256
    fprintf(stderr, "Error! Cannot retrieve TIFF ExtraSamples info.\n");
257
    goto End;
258
  }
259
260
  // _Tiffmalloc uses a signed type for size.
261
  alloc_size = (int64_t)(stride * image_height);
262
  if (alloc_size < 0 || alloc_size != (tsize_t)alloc_size) goto End;
263
264
  raster = (uint32_t*)_TIFFmalloc((tsize_t)alloc_size);
265
  if (raster != NULL) {
266
    if (TIFFReadRGBAImageOriented(tif, image_width, image_height, raster,
267
                                  ORIENTATION_TOPLEFT, 1)) {
268
      pic->width = image_width;
269
      pic->height = image_height;
270
      // TIFF data is ABGR
271
#ifdef WORDS_BIGENDIAN
272
      TIFFSwabArrayOfLong(raster, image_width * image_height);
273
#endif
274
      // if we have an alpha channel, we must un-multiply from rgbA to RGBA
275
      if (extra_samples == 1 && extra_samples_ptr != NULL &&
276
          extra_samples_ptr[0] == EXTRASAMPLE_ASSOCALPHA) {
277
        uint32_t y;
278
        uint8_t* tmp = (uint8_t*)raster;
279
        for (y = 0; y < image_height; ++y) {
280
          MultARGBRow(tmp, image_width);
281
          tmp += stride;
282
        }
283
      }
284
      ok =
285
          keep_alpha
286
              ? WebPPictureImportRGBA(pic, (const uint8_t*)raster, (int)stride)
287
              : WebPPictureImportRGBX(pic, (const uint8_t*)raster, (int)stride);
288
    }
289
    _TIFFfree(raster);
290
  } else {
291
    fprintf(stderr, "Error allocating TIFF RGBA memory!\n");
292
  }
293
294
  if (ok) {
295
    if (metadata != NULL) {
296
      ok = ExtractMetadataFromTIFF(tif, metadata);
297
      if (!ok) {
298
        fprintf(stderr, "Error extracting TIFF metadata!\n");
299
        MetadataFree(metadata);
300
        WebPPictureFree(pic);
301
      }
302
    }
303
  }
304
End:
305
  TIFFClose(tif);
306
  if (pic == NULL) {
307
    TIFFSetErrorHandler(prev_error_handler);
308
    TIFFSetWarningHandler(prev_warning_handler);
309
  }
310
  return ok;
311
}
312
313
int ReadTIFF(const uint8_t* const data, size_t data_size,
314
             WebPPicture* const pic, int keep_alpha, Metadata* const metadata) {
315
  if (pic == NULL) return 0;
316
  return ReadTIFFInternal(data, data_size, pic, keep_alpha, metadata, NULL,
317
                          NULL);
318
}
319
320
int ReadTiffDimensions(const uint8_t* const data, size_t data_size,
321
                       int* const width, int* const height) {
322
  return ReadTIFFInternal(data, data_size, NULL, 0, NULL, width, height);
323
}
324
#else   // !WEBP_HAVE_TIFF
325
int ReadTIFF(const uint8_t* const data, size_t data_size,
326
             struct WebPPicture* const pic, int keep_alpha,
327
372
             struct Metadata* const metadata) {
328
372
  (void)data;
329
372
  (void)data_size;
330
372
  (void)pic;
331
372
  (void)keep_alpha;
332
372
  (void)metadata;
333
372
  fprintf(stderr,
334
372
          "TIFF support not compiled. Please install the libtiff "
335
372
          "development package before building.\n");
336
372
  return 0;
337
372
}
338
339
int ReadTiffDimensions(const uint8_t* const data, size_t data_size,
340
8.05k
                       int* const width, int* const height) {
341
8.05k
  (void)data;
342
8.05k
  (void)data_size;
343
8.05k
  (void)width;
344
8.05k
  (void)height;
345
8.05k
  return 0;
346
8.05k
}
347
#endif  // WEBP_HAVE_TIFF
348
349
// -----------------------------------------------------------------------------