1#include "mupdf/fitz.h"
2
3#include <limits.h>
4#include <assert.h>
5#include <string.h>
6
7/*
8 * TIFF image loader. Should be enough to support TIFF files in XPS.
9 * Baseline TIFF 6.0 plus CMYK, LZW, Flate and JPEG support.
10 * Limited bit depths (1,2,4,8).
11 * Limited planar configurations (1=chunky).
12 * TODO: RGBPal images
13 */
14
15struct tiff
16{
17 /* "file" */
18 const unsigned char *bp, *rp, *ep;
19
20 /* byte order */
21 unsigned order;
22
23 /* offset of first ifd */
24 unsigned *ifd_offsets;
25 int ifds;
26
27 /* where we can find the strips of image data */
28 unsigned rowsperstrip;
29 unsigned *stripoffsets;
30 unsigned *stripbytecounts;
31 unsigned stripoffsetslen;
32 unsigned stripbytecountslen;
33
34 /* where we can find the tiles of image data */
35 unsigned tilelength;
36 unsigned tilewidth;
37 unsigned *tileoffsets;
38 unsigned *tilebytecounts;
39 unsigned tileoffsetslen;
40 unsigned tilebytecountslen;
41
42 /* colormap */
43 unsigned *colormap;
44 unsigned colormaplen;
45
46 /* assorted tags */
47 unsigned subfiletype;
48 unsigned photometric;
49 unsigned compression;
50 unsigned imagewidth;
51 unsigned imagelength;
52 unsigned samplesperpixel;
53 unsigned bitspersample;
54 unsigned planar;
55 unsigned extrasamples;
56 unsigned xresolution;
57 unsigned yresolution;
58 unsigned resolutionunit;
59 unsigned fillorder;
60 unsigned g3opts;
61 unsigned g4opts;
62 unsigned predictor;
63
64 unsigned ycbcrsubsamp[2];
65
66 const unsigned char *jpegtables; /* point into "file" buffer */
67 unsigned jpegtableslen;
68
69 unsigned char *profile;
70 int profilesize;
71
72 /* decoded data */
73 fz_colorspace *colorspace;
74 unsigned char *samples;
75 unsigned char *data;
76 int tilestride;
77 int stride;
78};
79
80enum
81{
82 TII = 0x4949, /* 'II' */
83 TMM = 0x4d4d, /* 'MM' */
84 TBYTE = 1,
85 TASCII = 2,
86 TSHORT = 3,
87 TLONG = 4,
88 TRATIONAL = 5
89};
90
91#define NewSubfileType 254
92#define ImageWidth 256
93#define ImageLength 257
94#define BitsPerSample 258
95#define Compression 259
96#define PhotometricInterpretation 262
97#define FillOrder 266
98#define StripOffsets 273
99#define SamplesPerPixel 277
100#define RowsPerStrip 278
101#define StripByteCounts 279
102#define XResolution 282
103#define YResolution 283
104#define PlanarConfiguration 284
105#define T4Options 292
106#define T6Options 293
107#define ResolutionUnit 296
108#define Predictor 317
109#define ColorMap 320
110#define TileWidth 322
111#define TileLength 323
112#define TileOffsets 324
113#define TileByteCounts 325
114#define ExtraSamples 338
115#define JPEGTables 347
116#define YCbCrSubSampling 530
117#define ICCProfile 34675
118
119static const unsigned char bitrev[256] =
120{
121 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
122 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
123 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
124 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
125 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
126 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
127 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
128 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
129 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
130 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
131 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
132 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
133 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
134 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
135 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
136 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
137 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1,
138 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
139 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9,
140 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
141 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
142 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
143 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed,
144 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
145 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3,
146 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
147 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
148 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
149 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
150 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
151 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
152 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff
153};
154
155static inline int tiff_getcomp(unsigned char *line, int x, int bpc)
156{
157 switch (bpc)
158 {
159 case 1: return (line[x >> 3] >> ( 7 - (x & 7) ) ) & 1;
160 case 2: return (line[x >> 2] >> ( ( 3 - (x & 3) ) << 1 ) ) & 3;
161 case 4: return (line[x >> 1] >> ( ( 1 - (x & 1) ) << 2 ) ) & 15;
162 case 8: return line[x];
163 case 16: return line[x << 1] << 8 | line[(x << 1) + 1];
164 }
165 return 0;
166}
167
168static inline void tiff_putcomp(unsigned char *line, int x, int bpc, int value)
169{
170 int maxval = (1 << bpc) - 1;
171
172 switch (bpc)
173 {
174 case 1: line[x >> 3] &= ~(maxval << (7 - (x & 7))); break;
175 case 2: line[x >> 2] &= ~(maxval << ((3 - (x & 3)) << 1)); break;
176 case 4: line[x >> 1] &= ~(maxval << ((1 - (x & 1)) << 2)); break;
177 }
178
179 switch (bpc)
180 {
181 case 1: line[x >> 3] |= value << (7 - (x & 7)); break;
182 case 2: line[x >> 2] |= value << ((3 - (x & 3)) << 1); break;
183 case 4: line[x >> 1] |= value << ((1 - (x & 1)) << 2); break;
184 case 8: line[x] = value; break;
185 case 16: line[x << 1] = value >> 8; line[(x << 1) + 1] = value & 0xFF; break;
186 }
187}
188
189static void
190tiff_unpredict_line(unsigned char *line, int width, int comps, int bits)
191{
192 unsigned char left[FZ_MAX_COLORS];
193 int i, k, v;
194
195 for (k = 0; k < comps; k++)
196 left[k] = 0;
197
198 for (i = 0; i < width; i++)
199 {
200 for (k = 0; k < comps; k++)
201 {
202 v = tiff_getcomp(line, i * comps + k, bits);
203 v = v + left[k];
204 v = v % (1 << bits);
205 tiff_putcomp(line, i * comps + k, bits, v);
206 left[k] = v;
207 }
208 }
209}
210
211static void
212tiff_invert_line(unsigned char *line, int width, int comps, int bits, int alpha)
213{
214 int i, k, v;
215 int m = (1 << bits) - 1;
216
217 for (i = 0; i < width; i++)
218 {
219 for (k = 0; k < comps; k++)
220 {
221 v = tiff_getcomp(line, i * comps + k, bits);
222 if (!alpha || k < comps - 1)
223 v = m - v;
224 tiff_putcomp(line, i * comps + k, bits, v);
225 }
226 }
227}
228
229static void
230tiff_expand_colormap(fz_context *ctx, struct tiff *tiff)
231{
232 int maxval = 1 << tiff->bitspersample;
233 unsigned char *samples;
234 unsigned char *src, *dst;
235 unsigned int x, y;
236 unsigned int stride;
237
238 /* colormap has first all red, then all green, then all blue values */
239 /* colormap values are 0..65535, bits is 4 or 8 */
240 /* image can be with or without extrasamples: comps is 1 or 2 */
241
242 if (tiff->samplesperpixel != 1 && tiff->samplesperpixel != 2)
243 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid number of samples for RGBPal");
244
245 if (tiff->bitspersample != 1 && tiff->bitspersample != 2 && tiff->bitspersample != 4 && tiff->bitspersample != 8 && tiff->bitspersample != 16)
246 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid number of bits for RGBPal");
247
248 if (tiff->colormaplen < (unsigned)maxval * 3)
249 fz_throw(ctx, FZ_ERROR_GENERIC, "insufficient colormap data");
250
251 if (tiff->imagelength > UINT_MAX / tiff->imagewidth / (tiff->samplesperpixel + 2))
252 fz_throw(ctx, FZ_ERROR_GENERIC, "image too large");
253
254 stride = tiff->imagewidth * (tiff->samplesperpixel + 2);
255
256 samples = fz_malloc(ctx, stride * tiff->imagelength);
257
258 for (y = 0; y < tiff->imagelength; y++)
259 {
260 src = tiff->samples + (unsigned int)(tiff->stride * y);
261 dst = samples + (unsigned int)(stride * y);
262
263 for (x = 0; x < tiff->imagewidth; x++)
264 {
265 if (tiff->extrasamples)
266 {
267 int c = tiff_getcomp(src, x * 2, tiff->bitspersample);
268 int a = tiff_getcomp(src, x * 2 + 1, tiff->bitspersample);
269 *dst++ = tiff->colormap[c + 0] >> 8;
270 *dst++ = tiff->colormap[c + maxval] >> 8;
271 *dst++ = tiff->colormap[c + maxval * 2] >> 8;
272 if (tiff->bitspersample <= 8)
273 *dst++ = a << (8 - tiff->bitspersample);
274 else
275 *dst++ = a >> (tiff->bitspersample - 8);
276 }
277 else
278 {
279 int c = tiff_getcomp(src, x, tiff->bitspersample);
280 *dst++ = tiff->colormap[c + 0] >> 8;
281 *dst++ = tiff->colormap[c + maxval] >> 8;
282 *dst++ = tiff->colormap[c + maxval * 2] >> 8;
283 }
284 }
285 }
286
287 tiff->samplesperpixel += 2;
288 tiff->bitspersample = 8;
289 tiff->stride = stride;
290 fz_free(ctx, tiff->samples);
291 tiff->samples = samples;
292}
293
294static unsigned
295tiff_decode_data(fz_context *ctx, struct tiff *tiff, const unsigned char *rp, unsigned int rlen, unsigned char *wp, unsigned int wlen)
296{
297 fz_stream *encstm = NULL;
298 fz_stream *stm = NULL;
299 unsigned i, size = 0;
300 unsigned char *reversed = NULL;
301 fz_stream *jpegtables = NULL;
302 int old_tiff;
303
304 if (rp + rlen > tiff->ep)
305 fz_throw(ctx, FZ_ERROR_GENERIC, "strip extends beyond the end of the file");
306
307 /* the bits are in un-natural order */
308 if (tiff->fillorder == 2)
309 {
310 reversed = fz_malloc(ctx, rlen);
311 for (i = 0; i < rlen; i++)
312 reversed[i] = bitrev[rp[i]];
313 rp = reversed;
314 }
315
316 fz_var(jpegtables);
317 fz_var(encstm);
318 fz_var(stm);
319
320 fz_try(ctx)
321 {
322 encstm = fz_open_memory(ctx, rp, rlen);
323
324 /* switch on compression to create a filter */
325 /* feed each chunk (strip or tile) to the filter */
326 /* read out the data into a buffer */
327 /* the level above packs the chunk's samples into a pixmap */
328
329 /* type 32773 / packbits -- nothing special (same row-padding as PDF) */
330 /* type 2 / ccitt rle -- no EOL, no RTC, rows are byte-aligned */
331 /* type 3 and 4 / g3 and g4 -- each strip starts new section */
332 /* type 5 / lzw -- each strip is handled separately */
333
334 switch (tiff->compression)
335 {
336 case 1:
337 /* stm already open and reading uncompressed data */
338 stm = fz_keep_stream(ctx, encstm);
339 break;
340 case 2:
341 case 3:
342 case 4:
343 stm = fz_open_faxd(ctx, encstm,
344 tiff->compression == 4 ? -1 :
345 tiff->compression == 2 ? 0 :
346 tiff->g3opts & 1,
347 0,
348 tiff->compression == 2,
349 tiff->imagewidth,
350 tiff->imagelength,
351 0,
352 1);
353 break;
354 case 5:
355 old_tiff = rp[0] == 0 && (rp[1] & 1);
356 stm = fz_open_lzwd(ctx, encstm, old_tiff ? 0 : 1, 9, old_tiff ? 1 : 0, old_tiff);
357 break;
358 case 6:
359 fz_warn(ctx, "deprecated JPEG in TIFF compression not fully supported");
360 /* fall through */
361 case 7:
362 if (tiff->jpegtables && (int)tiff->jpegtableslen > 0)
363 jpegtables = fz_open_memory(ctx, tiff->jpegtables, tiff->jpegtableslen);
364
365 stm = fz_open_dctd(ctx, encstm,
366 tiff->photometric == 2 || tiff->photometric == 3 ? 0 : -1,
367 0,
368 jpegtables);
369 break;
370 case 8:
371 case 32946:
372 stm = fz_open_flated(ctx, encstm, 15);
373 break;
374 case 32773:
375 stm = fz_open_rld(ctx, encstm);
376 break;
377 case 34676:
378 if (tiff->photometric == 32845)
379 stm = fz_open_sgilog32(ctx, encstm, tiff->imagewidth);
380 else
381 stm = fz_open_sgilog16(ctx, encstm, tiff->imagewidth);
382 break;
383 case 34677:
384 stm = fz_open_sgilog24(ctx, encstm, tiff->imagewidth);
385 break;
386 case 32809:
387 if (tiff->bitspersample != 4)
388 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid bits per pixel in thunder encoding");
389 stm = fz_open_thunder(ctx, encstm, tiff->imagewidth);
390 break;
391 default:
392 fz_throw(ctx, FZ_ERROR_GENERIC, "unknown TIFF compression: %d", tiff->compression);
393 }
394
395 size = (unsigned)fz_read(ctx, stm, wp, wlen);
396 }
397 fz_always(ctx)
398 {
399 fz_drop_stream(ctx, jpegtables);
400 fz_drop_stream(ctx, encstm);
401 fz_drop_stream(ctx, stm);
402 fz_free(ctx, reversed);
403 }
404 fz_catch(ctx)
405 fz_rethrow(ctx);
406
407 return size;
408}
409
410static void
411tiff_paste_tile(fz_context *ctx, struct tiff *tiff, unsigned char *tile, unsigned int row, unsigned int col)
412{
413 unsigned int x, y, k;
414
415 for (y = 0; y < tiff->tilelength && row + y < tiff->imagelength; y++)
416 {
417 for (x = 0; x < tiff->tilewidth && col + x < tiff->imagewidth; x++)
418 {
419 for (k = 0; k < tiff->samplesperpixel; k++)
420 {
421 unsigned char *dst, *src;
422
423 dst = tiff->samples;
424 dst += (row + y) * tiff->stride;
425 dst += (((col + x) * tiff->samplesperpixel + k) * tiff->bitspersample + 7) / 8;
426
427 src = tile;
428 src += y * tiff->tilestride;
429 src += ((x * tiff->samplesperpixel + k) * tiff->bitspersample + 7) / 8;
430
431 switch (tiff->bitspersample)
432 {
433 case 1: *dst |= (*src >> (7 - 1 * ((col + x) % 8))) & 0x1; break;
434 case 2: *dst |= (*src >> (6 - 2 * ((col + x) % 4))) & 0x3; break;
435 case 4: *dst |= (*src >> (4 - 4 * ((col + x) % 2))) & 0xf; break;
436 case 8: *dst = *src; break;
437 case 16: dst[0] = src[0]; dst[1] = src[1]; break;
438 case 24: dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; break;
439 case 32: dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; break;
440 }
441 }
442 }
443 }
444}
445
446static void
447tiff_paste_subsampled_tile(fz_context *ctx, struct tiff *tiff, unsigned char *tile, unsigned len, unsigned tw, unsigned th, unsigned col, unsigned row)
448{
449 /*
450 This explains how the samples are laid out in tiff data, the spec example is non-obvious.
451 The y, cb, cr indicies follow the spec, i.e. y17 is the y sample at row 1, column 7.
452 All indicies start at 0.
453
454 hexlookup = (horizontalsubsampling & 0xf) << 4 | (verticalsubsampling & 0xf)
455
456 0x11 y00 cb00 cr00 0x21 y00 y01 cb00 cr00 0x41 y00 y01 y02 y03 cb00 cr00
457 y01 cb01 cr01 y10 y11 cb01 cr01 y04 y05 y06 y07 cb01 cr01
458 .... ... ...
459 y10 cb10 cr10 y20 y21 cb10 cr10 y10 y11 y12 y13 cb10 cr10
460 y11 cb11 cr11 y30 y31 cb11 cr11 y14 y15 y16 y17 cb11 cr11
461
462 0x12 y00 0x22 y00 y01 0x42 y00 y01 y02 y03
463 y10 cb00 cr00 y10 y11 cb00 cr00 y10 y11 y12 y13 cb00 cr00
464 y01 y02 y03 y04 y05 y06 y07
465 y11 cb01 cr01 y12 y13 cb01 cr01 y14 y15 y16 y17 cb01 cr01
466 .... ... ...
467 y20 y20 y21 y20 y21 y22 y23
468 y30 cb10 cr10 y30 y31 cb10 cr10 y30 y31 y32 y33 cb10 cr10
469 y21 y22 y23 y24 y25 y26 y27
470 y31 cb11 cr11 y32 y33 cb11 cr11 y34 y35 y36 y37 cb11 cr11
471
472 0x14 y00 0x24 y00 y01 0x44 y00 y01 y02 y03
473 y10 y10 y11 y10 y11 y12 y13
474 y20 y20 y21 y20 y21 y22 y23
475 y30 cb00 cr00 y30 y31 cb00 cr00 y30 y31 y32 y33 cb00 cr00
476 y01 y02 y03 y04 y05 y06 y07
477 y11 y12 y13 y14 y15 y16 y17
478 y21 y22 y23 y24 y25 y26 y27
479 y31 cb01 cr01 y32 y33 cb01 cr01 y34 y35 y36 y37 cb01 cr01
480 .... ... ...
481 y40 y40 y41 y40 y41 y42 y43
482 y50 y50 y51 y50 y51 y52 y53
483 y60 y60 y61 y60 y61 y62 y63
484 y70 cb10 cr10 y70 y71 cb10 cr10 y70 y71 y72 y73 cb10 cr10
485 y41 y42 y43 y44 y45 y46 y47
486 y51 y52 y53 y54 y55 y56 y57
487 y61 y62 y63 y64 y65 y66 y67
488 y71 cb11 cr11 y72 y73 cb11 cr11 y74 y75 y76 y77 cb11 cr11
489 */
490
491 unsigned char *src = tile;
492 unsigned char *dst;
493 unsigned x, y, w, h; /* coordinates and dimensions of entire image */
494 unsigned sx, sy, sw, sh; /* coordinates and dimensions of a single subsample region, i.e. max 4 x 4 samples */
495 int k;
496 int offsets[4 * 4 * 3]; /* for a pixel position, these point to all pixel components in a subsample region */
497 int *offset = offsets;
498
499 assert(tiff->samplesperpixel == 3);
500 assert(tiff->bitspersample == 8);
501
502 w = tiff->imagewidth;
503 h = tiff->imagelength;
504
505 sx = 0;
506 sy = 0;
507 sw = tiff->ycbcrsubsamp[0];
508 sh = tiff->ycbcrsubsamp[1];
509 if (sw > 4 || sh > 4 || !fz_is_pow2(sw) || !fz_is_pow2(sh))
510 fz_throw(ctx, FZ_ERROR_GENERIC, "Illegal TIFF Subsample values %d %d", sw, sh);
511
512 for (k = 0; k < 3; k++)
513 for (y = 0; y < sh; y++)
514 for (x = 0; x < sw; x++)
515 *offset++ = k + y * tiff->stride + x * 3;
516
517 offset = offsets;
518 x = col;
519 y = row;
520 k = 0;
521
522 dst = &tiff->samples[row * tiff->stride + col * 3];
523
524 while (src < tile + len)
525 {
526 if (k == 0)
527 { /* put all Y samples for a subsample region at the correct image pixel */
528 if (y + sy < h && y + sy < row + th && x + sx < w && x + sx < col + tw)
529 dst[*offset] = *src;
530 offset++;
531
532 if (++sx >= sw)
533 {
534 sx = 0;
535 if (++sy >= sh)
536 {
537 sy = 0;
538 k++;
539 }
540 }
541 }
542 else
543 { /* put all Cb/Cr samples for a subsample region at the correct image pixel */
544 for (sy = 0; sy < sh; sy++)
545 for (sx = 0; sx < sw; sx++)
546 {
547 if (y + sy < h && y + sy < row + th && x + sx < w && x + sx < col + tw)
548 dst[*offset] = *src;
549 offset++;
550 }
551
552 if (++k >= 3)
553 { /* we're done with this subsample region, on to the next one */
554 k = sx = sy = 0;
555 offset = offsets;
556
557 dst += sw * 3;
558
559 x += sw;
560 if (x >= col + tw)
561 {
562 dst -= (x - (col + tw)) * 3;
563 dst += (sh - 1) * w * 3;
564 dst += col * 3;
565 x = col;
566 y += sh;
567 }
568 }
569 }
570
571 src++;
572 }
573}
574
575static void
576tiff_decode_tiles(fz_context *ctx, struct tiff *tiff)
577{
578 unsigned char *data;
579 unsigned x, y, wlen, tile;
580 unsigned tiles, tilesacross, tilesdown;
581
582 tilesdown = (tiff->imagelength + tiff->tilelength - 1) / tiff->tilelength;
583 tilesacross = (tiff->imagewidth + tiff->tilewidth - 1) / tiff->tilewidth;
584 tiles = tilesacross * tilesdown;
585 if (tiff->tileoffsetslen < tiles || tiff->tilebytecountslen < tiles)
586 fz_throw(ctx, FZ_ERROR_GENERIC, "insufficient tile metadata");
587
588 /* JPEG can handle subsampling on its own */
589 if (tiff->photometric == 6 && tiff->compression != 6 && tiff->compression != 7)
590 {
591 /* regardless of how this is subsampled, a tile is never larger */
592 if (tiff->tilelength >= tiff->ycbcrsubsamp[1])
593 wlen = tiff->tilestride * tiff->tilelength;
594 else
595 wlen = tiff->tilestride * tiff->ycbcrsubsamp[1];
596
597 data = tiff->data = fz_malloc(ctx, wlen);
598
599 tile = 0;
600 for (x = 0; x < tiff->imagelength; x += tiff->tilelength)
601 {
602 for (y = 0; y < tiff->imagewidth; y += tiff->tilewidth)
603 {
604 unsigned int offset = tiff->tileoffsets[tile];
605 unsigned int rlen = tiff->tilebytecounts[tile];
606 const unsigned char *rp = tiff->bp + offset;
607 unsigned decoded;
608
609 if (offset > (unsigned)(tiff->ep - tiff->bp))
610 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid tile offset %u", offset);
611 if (rlen > (unsigned)(tiff->ep - rp))
612 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid tile byte count %u", rlen);
613
614 decoded = tiff_decode_data(ctx, tiff, rp, rlen, data, wlen);
615 tiff_paste_subsampled_tile(ctx, tiff, data, decoded, tiff->tilewidth, tiff->tilelength, x, y);
616 tile++;
617 }
618 }
619 }
620 else
621 {
622 wlen = tiff->tilelength * tiff->tilestride;
623 data = tiff->data = fz_malloc(ctx, wlen);
624
625 tile = 0;
626 for (x = 0; x < tiff->imagelength; x += tiff->tilelength)
627 {
628 for (y = 0; y < tiff->imagewidth; y += tiff->tilewidth)
629 {
630 unsigned int offset = tiff->tileoffsets[tile];
631 unsigned int rlen = tiff->tilebytecounts[tile];
632 const unsigned char *rp = tiff->bp + offset;
633
634 if (offset > (unsigned)(tiff->ep - tiff->bp))
635 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid tile offset %u", offset);
636 if (rlen > (unsigned)(tiff->ep - rp))
637 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid tile byte count %u", rlen);
638
639 if (tiff_decode_data(ctx, tiff, rp, rlen, data, wlen) != wlen)
640 fz_throw(ctx, FZ_ERROR_GENERIC, "decoded tile is the wrong size");
641
642 tiff_paste_tile(ctx, tiff, data, x, y);
643 tile++;
644 }
645 }
646 }
647}
648
649static void
650tiff_decode_strips(fz_context *ctx, struct tiff *tiff)
651{
652 unsigned char *data;
653 unsigned strips;
654 unsigned strip;
655 unsigned y;
656
657 strips = (tiff->imagelength + tiff->rowsperstrip - 1) / tiff->rowsperstrip;
658 if (tiff->stripoffsetslen < strips || tiff->stripbytecountslen < strips)
659 fz_throw(ctx, FZ_ERROR_GENERIC, "insufficient strip metadata");
660
661 data = tiff->samples;
662
663 /* JPEG can handle subsampling on its own */
664 if (tiff->photometric == 6 && tiff->compression != 6 && tiff->compression != 7)
665 {
666 unsigned wlen;
667 unsigned rowsperstrip;
668
669 /* regardless of how this is subsampled, a strip is never taller */
670 if (tiff->rowsperstrip >= tiff->ycbcrsubsamp[1])
671 rowsperstrip = tiff->rowsperstrip;
672 else
673 rowsperstrip = tiff->ycbcrsubsamp[1];
674
675 wlen = rowsperstrip * tiff->stride;
676 data = tiff->data = fz_malloc(ctx, wlen);
677
678 strip = 0;
679 for (y = 0; y < tiff->imagelength; y += rowsperstrip)
680 {
681 unsigned offset = tiff->stripoffsets[strip];
682 unsigned rlen = tiff->stripbytecounts[strip];
683 const unsigned char *rp = tiff->bp + offset;
684 int decoded;
685
686 if (offset > (unsigned)(tiff->ep - tiff->bp))
687 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid strip offset %u", offset);
688 if (rlen > (unsigned)(tiff->ep - rp))
689 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid strip byte count %u", rlen);
690
691 decoded = tiff_decode_data(ctx, tiff, rp, rlen, data, wlen);
692 tiff_paste_subsampled_tile(ctx, tiff, data, decoded, tiff->imagewidth, tiff->rowsperstrip, 0, y);
693 strip++;
694 }
695 }
696 else
697 {
698 strip = 0;
699 for (y = 0; y < tiff->imagelength; y += tiff->rowsperstrip)
700 {
701 unsigned offset = tiff->stripoffsets[strip];
702 unsigned rlen = tiff->stripbytecounts[strip];
703 unsigned wlen = tiff->stride * tiff->rowsperstrip;
704 const unsigned char *rp = tiff->bp + offset;
705
706 if (offset > (unsigned)(tiff->ep - tiff->bp))
707 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid strip offset %u", offset);
708 if (rlen > (unsigned)(tiff->ep - rp))
709 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid strip byte count %u", rlen);
710
711 /* if imagelength is not a multiple of rowsperstrip, adjust the expectation of the size of the decoded data */
712 if (y + tiff->rowsperstrip >= tiff->imagelength)
713 wlen = tiff->stride * (tiff->imagelength - y);
714
715 if (tiff_decode_data(ctx, tiff, rp, rlen, data, wlen) < wlen)
716 {
717 fz_warn(ctx, "premature end of data in decoded strip");
718 break;
719 }
720
721 data += wlen;
722 strip ++;
723 }
724 }
725}
726
727static inline int tiff_readbyte(struct tiff *tiff)
728{
729 if (tiff->rp < tiff->ep)
730 return *tiff->rp++;
731 return EOF;
732}
733
734static inline unsigned readshort(struct tiff *tiff)
735{
736 unsigned a = tiff_readbyte(tiff);
737 unsigned b = tiff_readbyte(tiff);
738 if (tiff->order == TII)
739 return (b << 8) | a;
740 return (a << 8) | b;
741}
742
743static inline unsigned tiff_readlong(struct tiff *tiff)
744{
745 unsigned a = tiff_readbyte(tiff);
746 unsigned b = tiff_readbyte(tiff);
747 unsigned c = tiff_readbyte(tiff);
748 unsigned d = tiff_readbyte(tiff);
749 if (tiff->order == TII)
750 return (d << 24) | (c << 16) | (b << 8) | a;
751 return (a << 24) | (b << 16) | (c << 8) | d;
752}
753
754static void
755tiff_read_bytes(unsigned char *p, struct tiff *tiff, unsigned ofs, unsigned n)
756{
757 if (ofs > (unsigned)(tiff->ep - tiff->bp))
758 ofs = (unsigned)(tiff->ep - tiff->bp);
759 tiff->rp = tiff->bp + ofs;
760
761 while (n--)
762 *p++ = tiff_readbyte(tiff);
763}
764
765static void
766tiff_read_tag_value(unsigned *p, struct tiff *tiff, unsigned type, unsigned ofs, unsigned n)
767{
768 unsigned den;
769
770 if (ofs > (unsigned)(tiff->ep - tiff->bp))
771 ofs = (unsigned)(tiff->ep - tiff->bp);
772 tiff->rp = tiff->bp + ofs;
773
774 while (n--)
775 {
776 switch (type)
777 {
778 case TRATIONAL:
779 *p = tiff_readlong(tiff);
780 den = tiff_readlong(tiff);
781 if (den)
782 *p = *p / den;
783 else
784 *p = UINT_MAX;
785 p ++;
786 break;
787 case TBYTE: *p++ = tiff_readbyte(tiff); break;
788 case TSHORT: *p++ = readshort(tiff); break;
789 case TLONG: *p++ = tiff_readlong(tiff); break;
790 default: *p++ = 0; break;
791 }
792 }
793}
794
795static void
796tiff_read_tag(fz_context *ctx, struct tiff *tiff, unsigned offset)
797{
798 unsigned tag;
799 unsigned type;
800 unsigned count;
801 unsigned value;
802
803 tiff->rp = tiff->bp + offset;
804
805 tag = readshort(tiff);
806 type = readshort(tiff);
807 count = tiff_readlong(tiff);
808
809 if ((type == TBYTE && count <= 4) ||
810 (type == TSHORT && count <= 2) ||
811 (type == TLONG && count <= 1))
812 value = tiff->rp - tiff->bp;
813 else
814 value = tiff_readlong(tiff);
815
816 switch (tag)
817 {
818 case NewSubfileType:
819 tiff_read_tag_value(&tiff->subfiletype, tiff, type, value, 1);
820 break;
821 case ImageWidth:
822 tiff_read_tag_value(&tiff->imagewidth, tiff, type, value, 1);
823 break;
824 case ImageLength:
825 tiff_read_tag_value(&tiff->imagelength, tiff, type, value, 1);
826 break;
827 case BitsPerSample:
828 tiff_read_tag_value(&tiff->bitspersample, tiff, type, value, 1);
829 break;
830 case Compression:
831 tiff_read_tag_value(&tiff->compression, tiff, type, value, 1);
832 break;
833 case PhotometricInterpretation:
834 tiff_read_tag_value(&tiff->photometric, tiff, type, value, 1);
835 break;
836 case FillOrder:
837 tiff_read_tag_value(&tiff->fillorder, tiff, type, value, 1);
838 break;
839 case SamplesPerPixel:
840 tiff_read_tag_value(&tiff->samplesperpixel, tiff, type, value, 1);
841 break;
842 case RowsPerStrip:
843 tiff_read_tag_value(&tiff->rowsperstrip, tiff, type, value, 1);
844 break;
845 case XResolution:
846 tiff_read_tag_value(&tiff->xresolution, tiff, type, value, 1);
847 break;
848 case YResolution:
849 tiff_read_tag_value(&tiff->yresolution, tiff, type, value, 1);
850 break;
851 case PlanarConfiguration:
852 tiff_read_tag_value(&tiff->planar, tiff, type, value, 1);
853 break;
854 case T4Options:
855 tiff_read_tag_value(&tiff->g3opts, tiff, type, value, 1);
856 break;
857 case T6Options:
858 tiff_read_tag_value(&tiff->g4opts, tiff, type, value, 1);
859 break;
860 case Predictor:
861 tiff_read_tag_value(&tiff->predictor, tiff, type, value, 1);
862 break;
863 case ResolutionUnit:
864 tiff_read_tag_value(&tiff->resolutionunit, tiff, type, value, 1);
865 break;
866 case YCbCrSubSampling:
867 tiff_read_tag_value(tiff->ycbcrsubsamp, tiff, type, value, 2);
868 break;
869 case ExtraSamples:
870 tiff_read_tag_value(&tiff->extrasamples, tiff, type, value, 1);
871 break;
872
873 case ICCProfile:
874 if (tiff->profile)
875 fz_throw(ctx, FZ_ERROR_GENERIC, "at most one ICC profile tag allowed");
876 tiff->profile = fz_malloc(ctx, count);
877 /* ICC profile data type is set to UNDEFINED.
878 * TBYTE reading not correct in tiff_read_tag_value */
879 tiff_read_bytes(tiff->profile, tiff, value, count);
880 tiff->profilesize = count;
881 break;
882
883 case JPEGTables:
884 /* Check both value and value + count to allow for overflow */
885 if (value > tiff->ep - tiff->bp || value + count > tiff->ep - tiff->bp)
886 fz_throw(ctx, FZ_ERROR_GENERIC, "TIFF JPEG tables out of range");
887 tiff->jpegtables = tiff->bp + value;
888 tiff->jpegtableslen = count;
889 break;
890
891 case StripOffsets:
892 if (tiff->stripoffsets)
893 fz_throw(ctx, FZ_ERROR_GENERIC, "at most one strip offsets tag allowed");
894 tiff->stripoffsets = fz_malloc_array(ctx, count, unsigned);
895 tiff_read_tag_value(tiff->stripoffsets, tiff, type, value, count);
896 tiff->stripoffsetslen = count;
897 break;
898
899 case StripByteCounts:
900 if (tiff->stripbytecounts)
901 fz_throw(ctx, FZ_ERROR_GENERIC, "at most one strip byte counts tag allowed");
902 tiff->stripbytecounts = fz_malloc_array(ctx, count, unsigned);
903 tiff_read_tag_value(tiff->stripbytecounts, tiff, type, value, count);
904 tiff->stripbytecountslen = count;
905 break;
906
907 case ColorMap:
908 if (tiff->colormap)
909 fz_throw(ctx, FZ_ERROR_GENERIC, "at most one color map allowed");
910 tiff->colormap = fz_malloc_array(ctx, count, unsigned);
911 tiff_read_tag_value(tiff->colormap, tiff, type, value, count);
912 tiff->colormaplen = count;
913 break;
914
915 case TileWidth:
916 tiff_read_tag_value(&tiff->tilewidth, tiff, type, value, 1);
917 break;
918
919 case TileLength:
920 tiff_read_tag_value(&tiff->tilelength, tiff, type, value, 1);
921 break;
922
923 case TileOffsets:
924 if (tiff->tileoffsets)
925 fz_throw(ctx, FZ_ERROR_GENERIC, "at most one tile offsets tag allowed");
926 tiff->tileoffsets = fz_malloc_array(ctx, count, unsigned);
927 tiff_read_tag_value(tiff->tileoffsets, tiff, type, value, count);
928 tiff->tileoffsetslen = count;
929 break;
930
931 case TileByteCounts:
932 if (tiff->tilebytecounts)
933 fz_throw(ctx, FZ_ERROR_GENERIC, "at most one tile byte counts tag allowed");
934 tiff->tilebytecounts = fz_malloc_array(ctx, count, unsigned);
935 tiff_read_tag_value(tiff->tilebytecounts, tiff, type, value, count);
936 tiff->tilebytecountslen = count;
937 break;
938
939 default:
940 /* fz_warn(ctx, "unknown tag: %d t=%d n=%d", tag, type, count); */
941 break;
942 }
943}
944
945static void
946tiff_swap_byte_order(unsigned char *buf, int n)
947{
948 int i, t;
949 for (i = 0; i < n; i++)
950 {
951 t = buf[i * 2 + 0];
952 buf[i * 2 + 0] = buf[i * 2 + 1];
953 buf[i * 2 + 1] = t;
954 }
955}
956
957static void
958tiff_scale_lab_samples(fz_context *ctx, unsigned char *buf, int bps, int n)
959{
960 int i;
961 if (bps == 8)
962 for (i = 0; i < n; i++, buf += 3)
963 {
964 buf[1] ^= 128;
965 buf[2] ^= 128;
966 }
967 else if (bps == 16)
968 for (i = 0; i < n; i++, buf += 6)
969 {
970 buf[2] ^= 128;
971 buf[4] ^= 128;
972 }
973}
974
975static void
976tiff_read_header(fz_context *ctx, struct tiff *tiff, const unsigned char *buf, size_t len)
977{
978 unsigned version;
979
980 memset(tiff, 0, sizeof(struct tiff));
981 tiff->bp = buf;
982 tiff->rp = buf;
983 tiff->ep = buf + len;
984
985 /* tag defaults, where applicable */
986 tiff->bitspersample = 1;
987 tiff->compression = 1;
988 tiff->samplesperpixel = 1;
989 tiff->resolutionunit = 2;
990 tiff->rowsperstrip = 0xFFFFFFFF;
991 tiff->fillorder = 1;
992 tiff->planar = 1;
993 tiff->subfiletype = 0;
994 tiff->predictor = 1;
995 tiff->ycbcrsubsamp[0] = 2;
996 tiff->ycbcrsubsamp[1] = 2;
997
998 /*
999 * Read IFH
1000 */
1001
1002 /* get byte order marker */
1003 tiff->order = readshort(tiff);
1004 if (tiff->order != TII && tiff->order != TMM)
1005 fz_throw(ctx, FZ_ERROR_GENERIC, "not a TIFF file, wrong magic marker");
1006
1007 /* check version */
1008 version = readshort(tiff);
1009 if (version != 42)
1010 fz_throw(ctx, FZ_ERROR_GENERIC, "not a TIFF file, wrong version marker");
1011
1012 /* get offset of IFD */
1013 tiff->ifd_offsets = fz_malloc_array(ctx, 1, unsigned);
1014 tiff->ifd_offsets[0] = tiff_readlong(tiff);
1015 tiff->ifds = 1;
1016}
1017
1018static unsigned
1019tiff_next_ifd(fz_context *ctx, struct tiff *tiff, unsigned offset)
1020{
1021 unsigned count;
1022 int i;
1023
1024 if (offset > (unsigned)(tiff->ep - tiff->bp))
1025 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid IFD offset %u", offset);
1026
1027 tiff->rp = tiff->bp + offset;
1028 count = readshort(tiff);
1029
1030 if (count * 12 > (unsigned)(tiff->ep - tiff->rp))
1031 fz_throw(ctx, FZ_ERROR_GENERIC, "overlarge IFD entry count %u", count);
1032
1033 tiff->rp += count * 12;
1034 offset = tiff_readlong(tiff);
1035
1036 for (i = 0; i < tiff->ifds; i++)
1037 if (tiff->ifd_offsets[i] == offset)
1038 fz_throw(ctx, FZ_ERROR_GENERIC, "cycle in IFDs detected");
1039
1040 tiff->ifd_offsets = fz_realloc_array(ctx, tiff->ifd_offsets, tiff->ifds + 1, unsigned);
1041 tiff->ifd_offsets[tiff->ifds] = offset;
1042 tiff->ifds++;
1043
1044 return offset;
1045}
1046
1047static void
1048tiff_seek_ifd(fz_context *ctx, struct tiff *tiff, int subimage)
1049{
1050 unsigned offset = tiff->ifd_offsets[0];
1051
1052 while (subimage--)
1053 {
1054 offset = tiff_next_ifd(ctx, tiff, offset);
1055
1056 if (offset == 0)
1057 fz_throw(ctx, FZ_ERROR_GENERIC, "subimage index %i out of range", subimage);
1058 }
1059
1060 tiff->rp = tiff->bp + offset;
1061
1062 if (tiff->rp < tiff->bp || tiff->rp > tiff->ep)
1063 fz_throw(ctx, FZ_ERROR_GENERIC, "invalid IFD offset %u", offset);
1064}
1065
1066static void
1067tiff_read_ifd(fz_context *ctx, struct tiff *tiff)
1068{
1069 unsigned offset;
1070 unsigned count;
1071 unsigned i;
1072
1073 offset = tiff->rp - tiff->bp;
1074
1075 count = readshort(tiff);
1076
1077 if (count * 12 > (unsigned)(tiff->ep - tiff->rp))
1078 fz_throw(ctx, FZ_ERROR_GENERIC, "overlarge IFD entry count %u", count);
1079
1080 offset += 2;
1081 for (i = 0; i < count; i++)
1082 {
1083 tiff_read_tag(ctx, tiff, offset);
1084 offset += 12;
1085 }
1086}
1087
1088static void
1089tiff_ycc_to_rgb(fz_context *ctx, struct tiff *tiff)
1090{
1091 unsigned x, y;
1092 int offset = tiff->samplesperpixel;
1093
1094 for (y = 0; y < tiff->imagelength; y++)
1095 {
1096 unsigned char * row = &tiff->samples[tiff->stride * y];
1097 for (x = 0; x < tiff->imagewidth; x++)
1098 {
1099 int ycc[3];
1100 ycc[0] = row[x * offset + 0];
1101 ycc[1] = row[x * offset + 1] - 128;
1102 ycc[2] = row[x * offset + 2] - 128;
1103
1104 row[x * offset + 0] = fz_clampi(ycc[0] + 1.402f * ycc[2], 0, 255);
1105 row[x * offset + 1] = fz_clampi(ycc[0] - 0.34413f * ycc[1] - 0.71414f * ycc[2], 0, 255);
1106 row[x * offset + 2] = fz_clampi(ycc[0] + 1.772f * ycc[1], 0, 255);
1107 }
1108 }
1109}
1110
1111static void
1112tiff_decode_ifd(fz_context *ctx, struct tiff *tiff)
1113{
1114 unsigned i;
1115
1116 if (tiff->imagelength <= 0)
1117 fz_throw(ctx, FZ_ERROR_GENERIC, "image height must be > 0");
1118 if (tiff->imagewidth <= 0)
1119 fz_throw(ctx, FZ_ERROR_GENERIC, "image width must be > 0");
1120 if (tiff->bitspersample > 16 || !fz_is_pow2(tiff->bitspersample))
1121 fz_throw(ctx, FZ_ERROR_GENERIC, "bits per sample illegal %d", tiff->bitspersample);
1122 if (tiff->samplesperpixel == 0 || tiff->samplesperpixel >= FZ_MAX_COLORS)
1123 fz_throw(ctx, FZ_ERROR_GENERIC, "components per pixel out of range");
1124 if (tiff->imagelength > UINT_MAX / tiff->imagewidth / (tiff->samplesperpixel + 2) / (tiff->bitspersample / 8 + 1))
1125 fz_throw(ctx, FZ_ERROR_GENERIC, "image too large");
1126
1127 if (tiff->planar != 1)
1128 fz_throw(ctx, FZ_ERROR_GENERIC, "image data is not in chunky format");
1129
1130 if (tiff->photometric == 6)
1131 {
1132 if (tiff->samplesperpixel != 3)
1133 fz_throw(ctx, FZ_ERROR_GENERIC, "unsupported samples per pixel when subsampling");
1134 if (tiff->bitspersample != 8)
1135 fz_throw(ctx, FZ_ERROR_GENERIC, "unsupported bits per sample when subsampling");
1136 if (tiff->ycbcrsubsamp[0] == 0 || tiff->ycbcrsubsamp[1] == 0)
1137 fz_throw(ctx, FZ_ERROR_GENERIC, "unsupported subsampling factor");
1138 }
1139
1140 tiff->stride = (tiff->imagewidth * tiff->samplesperpixel * tiff->bitspersample + 7) / 8;
1141 tiff->tilestride = (tiff->tilewidth * tiff->samplesperpixel * tiff->bitspersample + 7) / 8;
1142
1143 switch (tiff->photometric)
1144 {
1145 case 0: /* WhiteIsZero -- inverted */
1146 tiff->colorspace = fz_keep_colorspace(ctx, fz_device_gray(ctx));
1147 break;
1148 case 1: /* BlackIsZero */
1149 tiff->colorspace = fz_keep_colorspace(ctx, fz_device_gray(ctx));
1150 break;
1151 case 2: /* RGB */
1152 tiff->colorspace = fz_keep_colorspace(ctx, fz_device_rgb(ctx));
1153 break;
1154 case 3: /* RGBPal */
1155 tiff->colorspace = fz_keep_colorspace(ctx, fz_device_rgb(ctx));
1156 break;
1157 case 4: /* Transparency mask */
1158 tiff->colorspace = NULL;
1159 break;
1160 case 5: /* CMYK */
1161 tiff->colorspace = fz_keep_colorspace(ctx, fz_device_cmyk(ctx));
1162 break;
1163 case 6: /* YCbCr */
1164 /* it's probably a jpeg ... we let jpeg convert to rgb */
1165 tiff->colorspace = fz_keep_colorspace(ctx, fz_device_rgb(ctx));
1166 break;
1167 case 8: /* Direct L*a*b* encoding. a*, b* signed values */
1168 case 9: /* ICC Style L*a*b* encoding */
1169 tiff->colorspace = fz_keep_colorspace(ctx, fz_device_lab(ctx));
1170 break;
1171 case 32844: /* SGI CIE Log 2 L (16bpp Greyscale) */
1172 tiff->colorspace = fz_keep_colorspace(ctx, fz_device_gray(ctx));
1173 if (tiff->bitspersample != 8)
1174 tiff->bitspersample = 8;
1175 tiff->stride >>= 1;
1176 break;
1177 case 32845: /* SGI CIE Log 2 L, u, v (24bpp or 32bpp) */
1178 tiff->colorspace = fz_keep_colorspace(ctx, fz_device_rgb(ctx));
1179 if (tiff->bitspersample != 8)
1180 tiff->bitspersample = 8;
1181 tiff->stride >>= 1;
1182 break;
1183 default:
1184 fz_throw(ctx, FZ_ERROR_GENERIC, "unknown photometric: %d", tiff->photometric);
1185 }
1186
1187#if FZ_ENABLE_ICC
1188 if (tiff->profile)
1189 {
1190 fz_buffer *buff = NULL;
1191 fz_colorspace *icc = NULL;
1192 fz_var(buff);
1193 fz_try(ctx)
1194 {
1195 buff = fz_new_buffer_from_copied_data(ctx, tiff->profile, tiff->profilesize);
1196 icc = fz_new_icc_colorspace(ctx, fz_colorspace_type(ctx, tiff->colorspace), 0, NULL, buff);
1197 fz_drop_colorspace(ctx, tiff->colorspace);
1198 tiff->colorspace = icc;
1199 }
1200 fz_always(ctx)
1201 fz_drop_buffer(ctx, buff);
1202 fz_catch(ctx)
1203 fz_warn(ctx, "ignoring embedded ICC profile");
1204 }
1205#endif
1206
1207 if (!tiff->colorspace && tiff->samplesperpixel < 1)
1208 fz_throw(ctx, FZ_ERROR_GENERIC, "too few components for transparency mask");
1209 if (tiff->colorspace && tiff->colormap && tiff->samplesperpixel < 1)
1210 fz_throw(ctx, FZ_ERROR_GENERIC, "too few components for RGBPal");
1211 if (tiff->colorspace && !tiff->colormap && tiff->samplesperpixel < fz_colorspace_n(ctx, tiff->colorspace))
1212 fz_throw(ctx, FZ_ERROR_GENERIC, "fewer components per pixel than indicated by colorspace");
1213
1214 switch (tiff->resolutionunit)
1215 {
1216 case 2:
1217 /* no unit conversion needed */
1218 break;
1219 case 3:
1220 tiff->xresolution = tiff->xresolution * 254 / 100;
1221 tiff->yresolution = tiff->yresolution * 254 / 100;
1222 break;
1223 default:
1224 tiff->xresolution = 96;
1225 tiff->yresolution = 96;
1226 break;
1227 }
1228
1229 /* Note xres and yres could be 0 even if unit was set. If so default to 96dpi. */
1230 if (tiff->xresolution == 0 || tiff->yresolution == 0)
1231 {
1232 tiff->xresolution = 96;
1233 tiff->yresolution = 96;
1234 }
1235
1236 if (tiff->rowsperstrip > tiff->imagelength)
1237 tiff->rowsperstrip = tiff->imagelength;
1238
1239 /* some creators don't write byte counts for uncompressed images */
1240 if (tiff->compression == 1)
1241 {
1242 if (tiff->rowsperstrip == 0)
1243 fz_throw(ctx, FZ_ERROR_GENERIC, "rowsperstrip cannot be 0");
1244 if (!tiff->tilelength && !tiff->tilewidth && !tiff->stripbytecounts)
1245 {
1246 tiff->stripbytecountslen = (tiff->imagelength + tiff->rowsperstrip - 1) / tiff->rowsperstrip;
1247 tiff->stripbytecounts = fz_malloc_array(ctx, tiff->stripbytecountslen, unsigned);
1248 for (i = 0; i < tiff->stripbytecountslen; i++)
1249 tiff->stripbytecounts[i] = tiff->rowsperstrip * tiff->stride;
1250 }
1251 if (tiff->tilelength && tiff->tilewidth && !tiff->tilebytecounts)
1252 {
1253 unsigned tilesdown = (tiff->imagelength + tiff->tilelength - 1) / tiff->tilelength;
1254 unsigned tilesacross = (tiff->imagewidth + tiff->tilewidth - 1) / tiff->tilewidth;
1255 tiff->tilebytecountslen = tilesacross * tilesdown;
1256 tiff->tilebytecounts = fz_malloc_array(ctx, tiff->tilebytecountslen, unsigned);
1257 for (i = 0; i < tiff->tilebytecountslen; i++)
1258 tiff->tilebytecounts[i] = tiff->tilelength * tiff->tilestride;
1259 }
1260 }
1261
1262 /* some creators write strip tags when they meant to write tile tags... */
1263 if (tiff->tilelength && tiff->tilewidth)
1264 {
1265 if (!tiff->tileoffsets && !tiff->tileoffsetslen &&
1266 tiff->stripoffsets && tiff->stripoffsetslen)
1267 {
1268 tiff->tileoffsets = tiff->stripoffsets;
1269 tiff->tileoffsetslen = tiff->stripoffsetslen;
1270 tiff->stripoffsets = NULL;
1271 tiff->stripoffsetslen = 0;
1272 }
1273 if (!tiff->tilebytecounts && !tiff->tilebytecountslen &&
1274 tiff->stripbytecounts && tiff->stripbytecountslen)
1275 {
1276 tiff->tilebytecounts = tiff->stripbytecounts;
1277 tiff->tilebytecountslen = tiff->stripbytecountslen;
1278 tiff->stripbytecounts = NULL;
1279 tiff->stripbytecountslen = 0;
1280 }
1281 }
1282}
1283
1284static void
1285tiff_decode_samples(fz_context *ctx, struct tiff *tiff)
1286{
1287 unsigned i;
1288
1289 if (tiff->imagelength > UINT_MAX / tiff->stride)
1290 fz_throw(ctx, FZ_ERROR_MEMORY, "image too large");
1291 tiff->samples = fz_malloc(ctx, tiff->imagelength * tiff->stride);
1292 memset(tiff->samples, 0x55, tiff->imagelength * tiff->stride);
1293
1294 if (tiff->tilelength && tiff->tilewidth && tiff->tileoffsets && tiff->tilebytecounts)
1295 tiff_decode_tiles(ctx, tiff);
1296 else if (tiff->rowsperstrip && tiff->stripoffsets && tiff->stripbytecounts)
1297 tiff_decode_strips(ctx, tiff);
1298 else
1299 fz_throw(ctx, FZ_ERROR_GENERIC, "image is missing both strip and tile data");
1300
1301 /* Predictor (only for LZW and Flate) */
1302 if ((tiff->compression == 5 || tiff->compression == 8 || tiff->compression == 32946) && tiff->predictor == 2)
1303 {
1304 unsigned char *p = tiff->samples;
1305 for (i = 0; i < tiff->imagelength; i++)
1306 {
1307 tiff_unpredict_line(p, tiff->imagewidth, tiff->samplesperpixel, tiff->bitspersample);
1308 p += tiff->stride;
1309 }
1310 }
1311
1312 /* YCbCr -> RGB, but JPEG already has done this conversion */
1313 if (tiff->photometric == 6 && tiff->compression != 6 && tiff->compression != 7)
1314 tiff_ycc_to_rgb(ctx, tiff);
1315
1316 /* RGBPal */
1317 if (tiff->photometric == 3 && tiff->colormap)
1318 tiff_expand_colormap(ctx, tiff);
1319
1320 /* WhiteIsZero .. invert */
1321 if (tiff->photometric == 0)
1322 {
1323 unsigned char *p = tiff->samples;
1324 for (i = 0; i < tiff->imagelength; i++)
1325 {
1326 tiff_invert_line(p, tiff->imagewidth, tiff->samplesperpixel, tiff->bitspersample, tiff->extrasamples);
1327 p += tiff->stride;
1328 }
1329 }
1330
1331 /* Premultiplied transparency */
1332 if (tiff->extrasamples == 1)
1333 {
1334 /* In GhostXPS we undo the premultiplication here; muxps holds
1335 * all our images premultiplied by default, so nothing to do.
1336 */
1337 }
1338
1339 /* Non-premultiplied transparency */
1340 if (tiff->extrasamples == 2)
1341 {
1342 /* Premultiplied files are corrected for elsewhere */
1343 }
1344
1345 /* Byte swap 16-bit images to big endian if necessary */
1346 if (tiff->bitspersample == 16 && tiff->order == TII)
1347 tiff_swap_byte_order(tiff->samples, tiff->imagewidth * tiff->imagelength * tiff->samplesperpixel);
1348
1349 /* Lab colorspace expects all sample components 0..255.
1350 TIFF supplies them as L = 0..255, a/b = -128..127 (for
1351 8 bits per sample, -32768..32767 for 16 bits per sample)
1352 Scale them to the colorspace's expectations. */
1353 if (tiff->photometric == 8 && tiff->samplesperpixel == 3)
1354 tiff_scale_lab_samples(ctx, tiff->samples, tiff->bitspersample, tiff->imagewidth * tiff->imagelength);
1355}
1356
1357fz_pixmap *
1358fz_load_tiff_subimage(fz_context *ctx, const unsigned char *buf, size_t len, int subimage)
1359{
1360 fz_pixmap *image = NULL;
1361 struct tiff tiff = { 0 };
1362 int alpha;
1363
1364 fz_var(image);
1365
1366 fz_try(ctx)
1367 {
1368 tiff_read_header(ctx, &tiff, buf, len);
1369 tiff_seek_ifd(ctx, &tiff, subimage);
1370 tiff_read_ifd(ctx, &tiff);
1371
1372 /* Decode the image data */
1373 tiff_decode_ifd(ctx, &tiff);
1374 tiff_decode_samples(ctx, &tiff);
1375
1376 /* Expand into fz_pixmap struct */
1377 alpha = tiff.extrasamples != 0 || tiff.colorspace == NULL;
1378 image = fz_new_pixmap(ctx, tiff.colorspace, tiff.imagewidth, tiff.imagelength, NULL, alpha);
1379 image->xres = tiff.xresolution;
1380 image->yres = tiff.yresolution;
1381
1382 fz_unpack_tile(ctx, image, tiff.samples, tiff.samplesperpixel, tiff.bitspersample, tiff.stride, 0);
1383
1384 /* We should only do this on non-pre-multiplied images, but files in the wild are bad */
1385 /* TODO: check if any samples are non-premul to detect bad files */
1386 if (tiff.extrasamples /* == 2 */)
1387 fz_premultiply_pixmap(ctx, image);
1388 }
1389 fz_always(ctx)
1390 {
1391 /* Clean up scratch memory */
1392 fz_drop_colorspace(ctx, tiff.colorspace);
1393 fz_free(ctx, tiff.colormap);
1394 fz_free(ctx, tiff.stripoffsets);
1395 fz_free(ctx, tiff.stripbytecounts);
1396 fz_free(ctx, tiff.tileoffsets);
1397 fz_free(ctx, tiff.tilebytecounts);
1398 fz_free(ctx, tiff.data);
1399 fz_free(ctx, tiff.samples);
1400 fz_free(ctx, tiff.profile);
1401 fz_free(ctx, tiff.ifd_offsets);
1402 }
1403 fz_catch(ctx)
1404 {
1405 fz_drop_pixmap(ctx, image);
1406 fz_rethrow(ctx);
1407 }
1408
1409 return image;
1410}
1411
1412fz_pixmap *
1413fz_load_tiff(fz_context *ctx, const unsigned char *buf, size_t len)
1414{
1415 return fz_load_tiff_subimage(ctx, buf, len, 0);
1416}
1417
1418void
1419fz_load_tiff_info_subimage(fz_context *ctx, const unsigned char *buf, size_t len, int *wp, int *hp, int *xresp, int *yresp, fz_colorspace **cspacep, int subimage)
1420{
1421 struct tiff tiff = { 0 };
1422
1423 fz_try(ctx)
1424 {
1425 tiff_read_header(ctx, &tiff, buf, len);
1426 tiff_seek_ifd(ctx, &tiff, subimage);
1427 tiff_read_ifd(ctx, &tiff);
1428
1429 tiff_decode_ifd(ctx, &tiff);
1430
1431 *wp = tiff.imagewidth;
1432 *hp = tiff.imagelength;
1433 *xresp = (tiff.xresolution ? tiff.xresolution : 96);
1434 *yresp = (tiff.yresolution ? tiff.yresolution : 96);
1435 if (tiff.extrasamples /* == 2 */)
1436 {
1437 fz_drop_colorspace(ctx, tiff.colorspace);
1438 tiff.colorspace = fz_keep_colorspace(ctx, fz_device_rgb(ctx));
1439 }
1440 *cspacep = fz_keep_colorspace(ctx, tiff.colorspace);
1441 }
1442 fz_always(ctx)
1443 {
1444 /* Clean up scratch memory */
1445 fz_drop_colorspace(ctx, tiff.colorspace);
1446 fz_free(ctx, tiff.colormap);
1447 fz_free(ctx, tiff.stripoffsets);
1448 fz_free(ctx, tiff.stripbytecounts);
1449 fz_free(ctx, tiff.tileoffsets);
1450 fz_free(ctx, tiff.tilebytecounts);
1451 fz_free(ctx, tiff.data);
1452 fz_free(ctx, tiff.samples);
1453 fz_free(ctx, tiff.profile);
1454 fz_free(ctx, tiff.ifd_offsets);
1455 }
1456 fz_catch(ctx)
1457 {
1458 fz_rethrow(ctx);
1459 }
1460}
1461
1462void
1463fz_load_tiff_info(fz_context *ctx, const unsigned char *buf, size_t len, int *wp, int *hp, int *xresp, int *yresp, fz_colorspace **cspacep)
1464{
1465 fz_load_tiff_info_subimage(ctx, buf, len, wp, hp, xresp, yresp, cspacep, 0);
1466}
1467
1468int
1469fz_load_tiff_subimage_count(fz_context *ctx, const unsigned char *buf, size_t len)
1470{
1471 unsigned offset;
1472 unsigned subimage_count = 0;
1473 struct tiff tiff = { 0 };
1474
1475 fz_try(ctx)
1476 {
1477 tiff_read_header(ctx, &tiff, buf, len);
1478
1479 offset = tiff.ifd_offsets[0];
1480
1481 do {
1482 subimage_count++;
1483 offset = tiff_next_ifd(ctx, &tiff, offset);
1484 } while (offset != 0);
1485 }
1486 fz_always(ctx)
1487 fz_free(ctx, tiff.ifd_offsets);
1488 fz_catch(ctx)
1489 fz_rethrow(ctx);
1490
1491 return subimage_count;
1492}
1493