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