1 /* TIFF parts: Copyright (c) 1988, 1990 by Sam Leffler.
2  * All rights reserved.
3  *
4  * This file is provided for unrestricted use provided that this
5  * legend is included on all tape media and as a part of the
6  * software program in whole or part.  Users may copy, modify or
7  * distribute this file at will.
8  * -----------------------------
9  * Modifications for VIPS:  Kirk Martinez 1994
10  * 22/11/94 JC
11  *	- more general
12  *	- memory leaks fixed
13  * 20/3/95 JC
14  *	- TIFF error handler added
15  *	- read errors detected correctly
16  *
17  * Modified to handle LAB in tiff format.
18  * It convert LAB-tiff format to VIPS_INTERPRETATION_LABQ in vips format.
19  *  Copyright July-1995 Ahmed Abbood.
20  *
21  *
22  * 19/9/95 JC
23  *	- now calls TIFFClose ... stupid
24  * 25/1/96 JC
25  *	- typo on MINISBLACK ...
26  * 7/4/97 JC
27  *	- completely redone for TIFF 6
28  *	- now full baseline TIFF 6 reader, and does CIELAB as well
29  * 11/4/97 JC
30  *	- added partial read for tiled images
31  * 23/4/97 JC
32  *	- extra subsample parameter
33  *	- im_istiffpyramid() added
34  * 5/12/97 JC
35  *	- if loading YCbCr, convert to VIPS_CODING_LABQ
36  * 1/5/98 JC
37  *	- now reads 16-bit greyscale and RGB
38  * 26/10/98 JC
39  *	- now used "rb" mode on systems that need binary open
40  * 12/11/98 JC
41  *	- no sub-sampling if sub == 1
42  * 26/2/99 JC
43  *	- ooops, else missing for subsample stuff above
44  * 2/10/99 JC
45  *	- tiled 16-bit greyscale read was broken
46  *	- added mutex for TIFFReadTile() calls
47  * 11/5/00 JC
48  *	- removed TIFFmalloc/TIFFfree usage
49  * 23/4/01 JC
50  *	- HAVE_TIFF turns on TIFF goodness
51  * 24/5/01 JC
52  *	- im_tiff2vips_header() added
53  * 11/7/01 JC
54  *	- subsample now in input filename
55  *	- ... and it's a page number (from 0) instead
56  * 21/8/02 JC
57  *	- now reads CMYK
58  *	- hmm, dpi -> ppm conversion was wrong!
59  * 10/9/02 JC
60  *	- oops, handle TIFF errors better
61  * 2/12/02 JC
62  *	- reads 8-bit RGBA
63  * 12/12/02 JC
64  *	- reads 16-bit LAB
65  * 13/2/03 JC
66  *	- pixels/cm res read was wrong
67  * 17/11/03 Andrey Kiselev
68  *	- read 32-bit float greyscale and rgb
69  * 5/4/04
70  *	- better handling of edge tiles (thanks Ruven)
71  * 16/4/04
72  *	- cleanup
73  *	- added broken tile read mode
74  * 18/5/04 Andrey Kiselev
75  *	- better no resolution diagnostic
76  * 26/5/04
77  *	- reads 16 bit RGBA
78  * 28/7/04
79  *	- arrg, 16bit RGB was broken, thanks haida
80  * 26/11/04
81  *	- add a TIFF warning handler, stops occasional libMagick exceptions
82  * 9/3/05
83  *	- load 32-bit float LAB
84  * 8/4/05
85  *	- onebit read no longer reads one byte too many on multiple of 8 wide
86  *	  images
87  * 22/6/05
88  *	- 16 bit LAB read was broken
89  * 9/9/05
90  * 	- read any ICCPROFILE tag
91  * 8/5/06
92  * 	- set RGB16 and GREY16 Type
93  * 21/5/06
94  * 	- use external im_tile_cache() operation for great code shrinkage
95  * 	- less RAM usage too, esp. with >1 CPU
96  * 	- should be slightly faster
97  * 	- removed 'broken' read option
98  * 18/7/07 Andrey Kiselev
99  * 	- remove "b" option on TIFFOpen()
100  * 9/4/08
101  * 	- set VIPS_META_RESOLUTION_UNIT
102  * 17/4/08
103  * 	- allow CMYKA (thanks Doron)
104  * 17/7/08
105  * 	- convert YCbCr to RGB on read (thanks Ole)
106  * 15/8/08
107  * 	- reorganise for image format system
108  * 20/12/08
109  * 	- dont read with mmap: no performance advantage with libtiff, chews up
110  * 	  VM wastefully
111  * 13/1/09
112  * 	- read strip-wise, not scanline-wise ... works with more compression /
113  * 	  subsampling schemes (esp. subsampled YCbCr), and it's a bit quicker
114  * 4/2/10
115  * 	- gtkdoc
116  * 12/12/10
117  * 	- oops, we can just memcpy() now heh
118  * 	- avoid unpacking via buffers if we can: either read a tile directly
119  * 	  into the output region, or writeline directly from the tiff buffer
120  * 4/4/11
121  * 	- argh int/uint mixup for rows_per_strip, thanks Bubba
122  * 21/4/11
123  * 	- palette read can do 1,2,4,8 bits per sample
124  * 	- palette read can do mono images
125  * 5/12/11
126  * 	- make into a simple function call ready to be wrapped as a new-style
127  * 	  VipsForeign class
128  * 18/2/12
129  * 	- switch to sequential read
130  * 	- remove the lock ... tilecache does this for us
131  * 3/6/12
132  * 	- always offer THINSTRIP ... later stages can ask for something more
133  * 	  relaxed if they wish
134  * 7/6/12
135  * 	- clip rows_per_strip down to image height to avoid overflows for huge
136  * 	  values (thanks Nicolas)
137  * 	- better error msg for not PLANARCONFIG_CONTIG images
138  * 16/9/13
139  * 	- support alpha for 8, 16 and 32-bit greyscale images, thanks Robert
140  * 17/9/13
141  * 	- support separate planes for strip read
142  * 	- big cleanup
143  * 	- support for many more formats, eg. 32-bit int etc.
144  * 11/4/14
145  * 	- support 16 bits per sample palette images
146  * 	- palette images can have an alpha
147  * 22/4/14
148  * 	- add read from buffer
149  * 30/4/14
150  * 	- 1/2/4 bit palette images can have alpha
151  * 27/10/14 Lovell
152  * 	- better istiff detector spots bigtiff
153  * 3/12/14
154  * 	- read any XMP metadata
155  * 19/1/15
156  * 	- try to handle 8-bit colormaps
157  * 26/2/15
158  * 	- close the read down early for a header read ... this saves an
159  * 	  fd during file read, handy for large numbers of input images
160  * 29/9/15
161  * 	- load IPTC metadata
162  * 	- load photoshop metadata
163  * 21/12/15
164  * 	- load TIFFTAG_IMAGEDESCRIPTION
165  * 11/4/16
166  * 	- non-int RGB images are tagged as scRGB ... matches photoshop
167  * 	  convention
168  * 26/5/16
169  * 	- add autorotate support
170  * 17/11/16
171  * 	- add multi-page read
172  * 17/1/17
173  * 	- invalidate operation on read error
174  * 27/1/17
175  * 	- if rows_per_strip is large, read with scanline API instead
176  * 9/5/17
177  * 	- remove missing res warning
178  * 19/5/17
179  * 	- page > 0 could break edge tiles or strips
180  * 26/4/18
181  * 	- add n-pages metadata item
182  * 21/7/18
183  * 	- check for non-byte-multiple bits_per_sample [HongxuChen]
184  * 16/8/18
185  * 	- shut down the input file as soon as we can [kleisauke]
186  * 28/3/19 omira-sch
187  * 	- better buffer sizing
188  * 	- ban chroma-subsampled, non-jpg compressed images
189  * 7/6/19
190  * 	- istiff reads the first directory rather than just testing the magic
191  * 	  number, so it ignores more TIFF-like, but not TIFF images
192  * 17/10/19
193  * 	- switch to source input
194  * 18/11/19
195  * 	- support ASSOCALPHA in any alpha band
196  * 27/1/20
197  * 	- read logluv images as XYZ
198  * 11/4/20 petoor
199  * 	- better handling of aligned reads in multipage tiffs
200  * 28/5/20
201  * 	- add subifd
202  * 6/6/20 MathemanFlo
203  * 	- support 2 and 4 bit greyscale load
204  * 27/3/21
205  * 	- add jp2k decompresion
206  * 24/7/21
207  * 	- add fail_on
208  * 30/9/21
209  * 	- fix tiled + packed formats
210  */
211 
212 /*
213 
214     This file is part of VIPS.
215 
216     VIPS is free software; you can redistribute it and/or modify
217     it under the terms of the GNU Lesser General Public License as published by
218     the Free Software Foundation; either version 2 of the License, or
219     (at your option) any later version.
220 
221     This program is distributed in the hope that it will be useful,
222     but WITHOUT ANY WARRANTY; without even the implied warranty of
223     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
224     GNU Lesser General Public License for more details.
225 
226     You should have received a copy of the GNU Lesser General Public License
227     along with this program; if not, write to the Free Software
228     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
229     02110-1301  USA
230 
231  */
232 
233 /*
234 
235     These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
236 
237  */
238 
239 /*
240 #define DEBUG_VERBOSE
241 #define DEBUG
242  */
243 
244 #ifdef HAVE_CONFIG_H
245 #include <config.h>
246 #endif /*HAVE_CONFIG_H*/
247 #include <vips/intl.h>
248 
249 #ifdef HAVE_TIFF
250 
251 #include <stdio.h>
252 #include <stdlib.h>
253 #include <string.h>
254 
255 #include <vips/vips.h>
256 #include <vips/internal.h>
257 #include <vips/thread.h>
258 
259 #include "pforeign.h"
260 #include "tiff.h"
261 
262 /* Aperio TIFFs (svs) use these compression types for jp2k-compressed tiles.
263  */
264 #define JP2K_YCC 33003
265 #define JP2K_RGB 33005
266 
267 /* Bioformats uses this tag for jp2k compressed tiles.
268  */
269 #define JP2K_LOSSY 33004
270 
271 /* Compression types we handle ourselves.
272  */
273 static int rtiff_we_decompress[] = {
274 	JP2K_YCC,
275 	JP2K_RGB,
276 	JP2K_LOSSY
277 };
278 
279 /* What we read from the tiff dir to set our read strategy. For multipage
280  * read, we need to read and compare lots of these, so it needs to be broken
281  * out as a separate thing.
282  */
283 typedef struct _RtiffHeader {
284 	guint32 width;
285 	guint32 height;
286 	int samples_per_pixel;
287 	int bits_per_sample;
288 	int photometric_interpretation;
289 	int inkset;
290 	int sample_format;
291 	gboolean separate;
292 	int orientation;
293 
294 	/* If there's a premultiplied alpha, the band we need to
295 	 * unpremultiply with. -1 for no unpremultiplication.
296 	 */
297 	int alpha_band;
298 	guint16 compression;
299 
300 	/* Is this directory tiled.
301 	 */
302 	gboolean tiled;
303 
304 	/* Fields for tiled images, as returned by libtiff.
305 	 */
306 	guint32 tile_width;
307 	guint32 tile_height;
308 	tsize_t tile_size;
309 	tsize_t tile_row_size;
310 
311 	/* Fields for strip images, as returned by libtiff.
312 	 */
313 	guint32 rows_per_strip;
314 	tsize_t strip_size;
315 	tsize_t scanline_size;
316 	int number_of_strips;
317 
318 	/* If read_scanlinewise is TRUE, the strips are too large to read in a
319 	 * single lump and we will use the scanline API.
320 	 */
321 	gboolean read_scanlinewise;
322 
323 	/* Strip read geometry. Number of lines we read at once (whole strip
324 	 * or 1) and size of the buffer we read to (a scanline, or a strip in
325 	 * size).
326 	 */
327 	guint32 read_height;
328 	tsize_t read_size;
329 
330 	/* Scale factor to get absolute cd/m2 from XYZ.
331 	 */
332 	double stonits;
333 
334 	/* Number of subifds, 0 for none.
335 	 */
336 	int subifd_count;
337 
338 	/* Optional IMAGEDESCRIPTION.
339 	 */
340 	char *image_description;
341 
342 	/* TRUE if the compression type is not supported by libtiff directly
343 	 * and we must read the raw data and decompress ourselves.
344 	 */
345 	gboolean we_decompress;
346 
347 } RtiffHeader;
348 
349 /* Scanline-type process function.
350  */
351 struct _Rtiff;
352 typedef void (*scanline_process_fn)( struct _Rtiff *,
353 	VipsPel *q, VipsPel *p, int n, void *client );
354 
355 /* Stuff we track during a read.
356  */
357 typedef struct _Rtiff {
358 	/* Parameters.
359 	 */
360 	VipsSource *source;
361 	VipsImage *out;
362 	int page;
363 	int n;
364 	gboolean autorotate;
365 	int subifd;
366 	VipsFailOn fail_on;
367 
368 	/* The TIFF we read.
369 	 */
370 	TIFF *tiff;
371 
372 	/* Number of pages (directories) in image.
373 	 */
374 	int n_pages;
375 
376 	/* The current page we have set.
377 	 */
378 	int current_page;
379 
380 	/* Process for this image type.
381 	 */
382 	scanline_process_fn sfn;
383 	void *client;
384 
385 	/* Set this is the processfn is just doing a memcpy.
386 	 */
387 	gboolean memcpy;
388 
389 	/* Geometry as read from the TIFF header. This is read for the first
390 	 * page, and equal for all other pages.
391 	 */
392 	RtiffHeader header;
393 
394 	/* Hold a single strip or tile, possibly just an image plane.
395 	 */
396 	tdata_t plane_buf;
397 
398 	/* Hold a plane-assembled strip or tile ... a set of samples_per_pixel
399 	 * strips or tiles interleaved.
400 	 */
401 	tdata_t contig_buf;
402 
403 	/* If we are decompressing, we need a buffer to read the raw tile to
404 	 * before running the decompressor.
405 	 */
406 	tdata_t compressed_buf;
407 	tsize_t compressed_buf_length;
408 
409 	/* The Y we are reading at. Used to verify strip read is sequential.
410 	 */
411 	int y_pos;
412 } Rtiff;
413 
414 /* Test for field exists.
415  */
416 static int
tfexists(TIFF * tif,ttag_t tag)417 tfexists( TIFF *tif, ttag_t tag )
418 {
419 	guint32 a, b;
420 
421 	if( TIFFGetField( tif, tag, &a, &b ) )
422 		return( 1 );
423 	else
424 		return( 0 );
425 }
426 
427 /* Get a guint32 field.
428  */
429 static int
tfget32(TIFF * tif,ttag_t tag,guint32 * out)430 tfget32( TIFF *tif, ttag_t tag, guint32 *out )
431 {
432 	guint32 fld;
433 
434 	if( !TIFFGetFieldDefaulted( tif, tag, &fld ) ) {
435 		vips_error( "tiff2vips",
436 			_( "required field %d missing" ), tag );
437 		return( 0 );
438 	}
439 
440 	*out = fld;
441 
442 	return( 1 );
443 }
444 
445 /* Get a guint16 field.
446  */
447 static int
tfget16(TIFF * tif,ttag_t tag,int * out)448 tfget16( TIFF *tif, ttag_t tag, int *out )
449 {
450 	guint16 fld;
451 
452 	if( !TIFFGetFieldDefaulted( tif, tag, &fld ) ) {
453 		vips_error( "tiff2vips",
454 			_( "required field %d missing" ), tag );
455 		return( 0 );
456 	}
457 
458 	*out = fld;
459 
460 	return( 1 );
461 }
462 
463 static int
get_resolution(TIFF * tiff,VipsImage * out)464 get_resolution( TIFF *tiff, VipsImage *out )
465 {
466 	float x, y;
467 	int ru;
468 
469 	if( TIFFGetFieldDefaulted( tiff, TIFFTAG_XRESOLUTION, &x ) &&
470 		TIFFGetFieldDefaulted( tiff, TIFFTAG_YRESOLUTION, &y ) &&
471 		tfget16( tiff, TIFFTAG_RESOLUTIONUNIT, &ru ) ) {
472 		switch( ru ) {
473 		case RESUNIT_NONE:
474 			break;
475 
476 		case RESUNIT_INCH:
477 			/* In pixels-per-inch ... convert to mm.
478 			 */
479 			x /= 10.0 * 2.54;
480 			y /= 10.0 * 2.54;
481 			vips_image_set_string( out,
482 				VIPS_META_RESOLUTION_UNIT, "in" );
483 			break;
484 
485 		case RESUNIT_CENTIMETER:
486 			/* In pixels-per-centimetre ... convert to mm.
487 			 */
488 			x /= 10.0;
489 			y /= 10.0;
490 			vips_image_set_string( out,
491 				VIPS_META_RESOLUTION_UNIT, "cm" );
492 			break;
493 
494 		default:
495 			vips_error( "tiff2vips",
496 				"%s", _( "unknown resolution unit" ) );
497 			return( -1 );
498 		}
499 	}
500 	else {
501 		/* We used to warn about missing res data, but it happens so
502 		 * often and is so harmless, why bother.
503 		 */
504 		x = 1.0;
505 		y = 1.0;
506 	}
507 
508 	out->Xres = x;
509 	out->Yres = y;
510 
511 	return( 0 );
512 }
513 
514 static int
get_sample_format(TIFF * tiff)515 get_sample_format( TIFF *tiff )
516 {
517 	int sample_format;
518 	guint16 v;
519 
520 	sample_format = SAMPLEFORMAT_INT;
521 
522 	if( TIFFGetFieldDefaulted( tiff, TIFFTAG_SAMPLEFORMAT, &v ) ) {
523 		/* Some images have this set to void, bizarre.
524 		 */
525 		if( v == SAMPLEFORMAT_VOID )
526 			v = SAMPLEFORMAT_UINT;
527 
528 		sample_format = v;
529 	}
530 
531 	return( sample_format );
532 }
533 
534 static int
get_orientation(TIFF * tiff)535 get_orientation( TIFF *tiff )
536 {
537 	int orientation;
538 	guint16 v;
539 
540 	orientation = ORIENTATION_TOPLEFT;
541 
542 	if( TIFFGetFieldDefaulted( tiff, TIFFTAG_ORIENTATION, &v ) )
543 		/* Can have mad values.
544 		 */
545 		orientation = VIPS_CLIP( 1, v, 8 );
546 
547 	return( orientation );
548 }
549 
550 /* Can be called many times.
551  */
552 static void
rtiff_free(Rtiff * rtiff)553 rtiff_free( Rtiff *rtiff )
554 {
555 	VIPS_FREEF( TIFFClose, rtiff->tiff );
556 	VIPS_UNREF( rtiff->source );
557 }
558 
559 static void
rtiff_close_cb(VipsImage * image,Rtiff * rtiff)560 rtiff_close_cb( VipsImage *image, Rtiff *rtiff )
561 {
562 	rtiff_free( rtiff );
563 }
564 
565 static void
rtiff_minimise_cb(VipsImage * image,Rtiff * rtiff)566 rtiff_minimise_cb( VipsImage *image, Rtiff *rtiff )
567 {
568 	/* We must not minimised tiled images. These can be read from many
569 	 * threads, and this minimise handler is not inside the lock that our
570 	 * tilecache is using to guarantee single-threaded access to our
571 	 * source.
572 	 */
573 	if( !rtiff->header.tiled &&
574 		rtiff->source )
575 		vips_source_minimise( rtiff->source );
576 }
577 
578 static Rtiff *
rtiff_new(VipsSource * source,VipsImage * out,int page,int n,gboolean autorotate,int subifd,VipsFailOn fail_on)579 rtiff_new( VipsSource *source, VipsImage *out,
580 	int page, int n, gboolean autorotate, int subifd, VipsFailOn fail_on )
581 {
582 	Rtiff *rtiff;
583 
584 	if( !(rtiff = VIPS_NEW( out, Rtiff )) )
585 		return( NULL );
586 
587 	g_object_ref( source );
588 	rtiff->source = source;
589 	rtiff->out = out;
590 	rtiff->page = page;
591 	rtiff->n = n;
592 	rtiff->autorotate = autorotate;
593 	rtiff->subifd = subifd;
594 	rtiff->fail_on = fail_on;
595 	rtiff->tiff = NULL;
596 	rtiff->n_pages = 0;
597 	rtiff->current_page = -1;
598 	rtiff->sfn = NULL;
599 	rtiff->client = NULL;
600 	rtiff->memcpy = FALSE;
601 	rtiff->plane_buf = NULL;
602 	rtiff->contig_buf = NULL;
603 	rtiff->y_pos = 0;
604 
605 	g_signal_connect( out, "close",
606 		G_CALLBACK( rtiff_close_cb ), rtiff );
607 	g_signal_connect( out, "minimise",
608 		G_CALLBACK( rtiff_minimise_cb ), rtiff );
609 
610 	if( rtiff->page < 0 ||
611 		rtiff->page > 1000000 ) {
612 		vips_error( "tiff2vips", _( "bad page number %d" ),
613 			rtiff->page );
614 		return( NULL );
615 	}
616 
617 	/* We allow n == -1, meaning all pages. It gets swapped for a real n
618 	 * value when we open the TIFF.
619 	 */
620 	if( rtiff->n != -1 &&
621 		(rtiff->n < 1 || rtiff->n > 1000000) ) {
622 		vips_error( "tiff2vips", _( "bad number of pages %d" ),
623 			rtiff->n );
624 		return( NULL );
625 	}
626 
627 	if( !(rtiff->tiff = vips__tiff_openin_source( source )) )
628 		return( NULL );
629 
630 	return( rtiff );
631 }
632 
633 static int
rtiff_strip_read(Rtiff * rtiff,int strip,tdata_t buf)634 rtiff_strip_read( Rtiff *rtiff, int strip, tdata_t buf )
635 {
636 	tsize_t length;
637 
638 #ifdef DEBUG_VERBOSE
639 	printf( "rtiff_strip_read: reading strip %d\n", strip );
640 #endif /*DEBUG_VERBOSE*/
641 
642 	if( rtiff->header.read_scanlinewise )
643 		length = TIFFReadScanline( rtiff->tiff,
644 			buf, strip, (tsample_t) 0 );
645 	else
646 		length = TIFFReadEncodedStrip( rtiff->tiff,
647 			strip, buf, (tsize_t) -1 );
648 
649 	if( length == -1 ) {
650 		vips_foreign_load_invalidate( rtiff->out );
651 		vips_error( "tiff2vips", "%s", _( "read error" ) );
652 		return( -1 );
653 	}
654 
655 	return( 0 );
656 }
657 
658 /* We need to hint to libtiff what format we'd like pixels in.
659  */
660 static void
rtiff_set_decode_format(Rtiff * rtiff)661 rtiff_set_decode_format( Rtiff *rtiff )
662 {
663 	/* Ask for YCbCr->RGB for jpg data.
664 	 */
665 	if( rtiff->header.compression == COMPRESSION_JPEG )
666 		TIFFSetField( rtiff->tiff,
667 			TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB );
668 
669 	/* Ask for SGI LOGLUV as 3xfloat.
670 	 */
671 	if( rtiff->header.photometric_interpretation ==
672 		PHOTOMETRIC_LOGLUV )
673 		TIFFSetField( rtiff->tiff,
674 			TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_FLOAT );
675 }
676 
677 static int
rtiff_set_page(Rtiff * rtiff,int page)678 rtiff_set_page( Rtiff *rtiff, int page )
679 {
680 	if( rtiff->current_page != page ) {
681 #ifdef DEBUG
682 		printf( "rtiff_set_page: selecting page %d, subifd %d\n",
683 			page, rtiff->subifd );
684 #endif /*DEBUG*/
685 
686 		if( !TIFFSetDirectory( rtiff->tiff, page ) ) {
687 			vips_error( "tiff2vips",
688 				_( "TIFF does not contain page %d" ), page );
689 			return( -1 );
690 		}
691 
692 		if( rtiff->subifd >= 0 ) {
693 			guint16 subifd_count;
694 			toff_t *subifd_offsets;
695 
696 			if( !TIFFGetField( rtiff->tiff, TIFFTAG_SUBIFD,
697 				&subifd_count, &subifd_offsets ) ) {
698 				vips_error( "tiff2vips",
699 					"%s", _( "no SUBIFD tag" ) );
700 				return( -1 );
701 			}
702 
703 			if( rtiff->subifd >= subifd_count ) {
704 				vips_error( "tiff2vips",
705 					_( "subifd %d out of range, "
706 						"only 0-%d available" ),
707 					rtiff->subifd,
708 					subifd_count - 1 );
709 				return( -1 );
710 			}
711 
712 			if( !TIFFSetSubDirectory( rtiff->tiff,
713 				subifd_offsets[rtiff->subifd] ) ) {
714 				vips_error( "tiff2vips",
715 					"%s", _( "subdirectory unreadable" ) );
716 				return( -1 );
717 			}
718 		}
719 
720 		rtiff->current_page = page;
721 
722 		/* These can get unset when we change directories. Make sure
723 		 * they are set again.
724 		 */
725 		rtiff_set_decode_format( rtiff );
726 	}
727 
728 	return( 0 );
729 }
730 
731 static int
rtiff_n_pages(Rtiff * rtiff)732 rtiff_n_pages( Rtiff *rtiff )
733 {
734 	int n;
735 
736 	(void) TIFFSetDirectory( rtiff->tiff, 0 );
737 
738 	for( n = 1; TIFFReadDirectory( rtiff->tiff ); n++ )
739 		;
740 
741 	/* Make sure the nest set_page() will set the directory.
742 	 */
743 	rtiff->current_page = -1;
744 
745 #ifdef DEBUG
746 	printf( "rtiff_n_pages: found %d pages\n", n );
747 #endif /*DEBUG*/
748 
749 	return( n );
750 }
751 
752 static int
rtiff_check_samples(Rtiff * rtiff,int samples_per_pixel)753 rtiff_check_samples( Rtiff *rtiff, int samples_per_pixel )
754 {
755 	if( rtiff->header.samples_per_pixel != samples_per_pixel ) {
756 		vips_error( "tiff2vips",
757 			_( "not %d bands" ), samples_per_pixel );
758 		return( -1 );
759 	}
760 
761 	return( 0 );
762 }
763 
764 /* Check n and n+1 so we can have an alpha.
765  */
766 static int
rtiff_check_min_samples(Rtiff * rtiff,int samples_per_pixel)767 rtiff_check_min_samples( Rtiff *rtiff, int samples_per_pixel )
768 {
769 	if( rtiff->header.samples_per_pixel < samples_per_pixel ) {
770 		vips_error( "tiff2vips",
771 			_( "not at least %d samples per pixel" ),
772 			samples_per_pixel );
773 		return( -1 );
774 	}
775 
776 	return( 0 );
777 }
778 
779 /* Only allow samples which are whole bytes in size.
780  */
781 static int
rtiff_non_fractional(Rtiff * rtiff)782 rtiff_non_fractional( Rtiff *rtiff )
783 {
784 	if( rtiff->header.bits_per_sample % 8 != 0 ||
785 		rtiff->header.bits_per_sample == 0 ) {
786 		vips_error( "tiff2vips", "%s", _( "samples_per_pixel "
787 			"not a whole number of bytes" ) );
788 		return( -1 );
789 	}
790 
791 	return( 0 );
792 }
793 
794 static int
rtiff_check_interpretation(Rtiff * rtiff,int photometric_interpretation)795 rtiff_check_interpretation( Rtiff *rtiff, int photometric_interpretation )
796 {
797 	if( rtiff->header.photometric_interpretation !=
798 		photometric_interpretation ) {
799 		vips_error( "tiff2vips",
800 			_( "not photometric interpretation %d" ),
801 			photometric_interpretation );
802 		return( -1 );
803 	}
804 
805 	return( 0 );
806 }
807 
808 static int
rtiff_check_bits(Rtiff * rtiff,int bits_per_sample)809 rtiff_check_bits( Rtiff *rtiff, int bits_per_sample )
810 {
811 	if( rtiff->header.bits_per_sample != bits_per_sample ) {
812 		vips_error( "tiff2vips",
813 			_( "not %d bits per sample" ), bits_per_sample );
814 		return( -1 );
815 	}
816 
817 	return( 0 );
818 }
819 
820 static int
rtiff_check_bits_palette(Rtiff * rtiff)821 rtiff_check_bits_palette( Rtiff *rtiff )
822 {
823 	if( rtiff->header.bits_per_sample != 16 &&
824 		rtiff->header.bits_per_sample != 8 &&
825 		rtiff->header.bits_per_sample != 4 &&
826 		rtiff->header.bits_per_sample != 2 &&
827 		rtiff->header.bits_per_sample != 1 ) {
828 		vips_error( "tiff2vips",
829 			_( "%d bits per sample palette image not supported" ),
830 			rtiff->header.bits_per_sample );
831 		return( -1 );
832 	}
833 
834 	return( 0 );
835 }
836 
837 static VipsBandFormat
rtiff_guess_format(Rtiff * rtiff)838 rtiff_guess_format( Rtiff *rtiff )
839 {
840 	int bits_per_sample = rtiff->header.bits_per_sample;
841 	int sample_format = rtiff->header.sample_format;
842 
843 	switch( bits_per_sample ) {
844 	case 1:
845 	case 2:
846 	case 4:
847 	case 8:
848 		if( sample_format == SAMPLEFORMAT_INT )
849 			return( VIPS_FORMAT_CHAR );
850 		if( sample_format == SAMPLEFORMAT_UINT )
851 			return( VIPS_FORMAT_UCHAR );
852 		break;
853 
854 	case 16:
855 		if( sample_format == SAMPLEFORMAT_INT )
856 			return( VIPS_FORMAT_SHORT );
857 		if( sample_format == SAMPLEFORMAT_UINT )
858 			return( VIPS_FORMAT_USHORT );
859 		break;
860 
861 	case 32:
862 		if( sample_format == SAMPLEFORMAT_INT )
863 			return( VIPS_FORMAT_INT );
864 		if( sample_format == SAMPLEFORMAT_UINT )
865 			return( VIPS_FORMAT_UINT );
866 		if( sample_format == SAMPLEFORMAT_IEEEFP )
867 			return( VIPS_FORMAT_FLOAT );
868 		break;
869 
870 	case 64:
871 		if( sample_format == SAMPLEFORMAT_IEEEFP )
872 			return( VIPS_FORMAT_DOUBLE );
873 		if( sample_format == SAMPLEFORMAT_COMPLEXIEEEFP )
874 			return( VIPS_FORMAT_COMPLEX );
875 		break;
876 
877 	case 128:
878 		if( sample_format == SAMPLEFORMAT_COMPLEXIEEEFP )
879 			return( VIPS_FORMAT_DPCOMPLEX );
880 		break;
881 
882 	default:
883 		break;
884 	}
885 
886 	vips_error( "tiff2vips", "%s", _( "unsupported tiff image type\n" ) );
887 
888 	return( VIPS_FORMAT_NOTSET );
889 }
890 
891 /* Per-scanline process function for VIPS_CODING_LABQ.
892  */
893 static void
rtiff_labpack_line(Rtiff * rtiff,VipsPel * q,VipsPel * p,int n,void * dummy)894 rtiff_labpack_line( Rtiff *rtiff, VipsPel *q, VipsPel *p, int n, void *dummy )
895 {
896 	int samples_per_pixel = rtiff->header.samples_per_pixel;
897 
898 	int x;
899 
900 	for( x = 0; x < n; x++ ) {
901 		q[0] = p[0];
902 		q[1] = p[1];
903 		q[2] = p[2];
904 		q[3] = 0;
905 
906 		q += 4;
907 		p += samples_per_pixel;
908 	}
909 }
910 
911 /* Read an 8-bit LAB image.
912  */
913 static int
rtiff_parse_labpack(Rtiff * rtiff,VipsImage * out)914 rtiff_parse_labpack( Rtiff *rtiff, VipsImage *out )
915 {
916 	if( rtiff_check_min_samples( rtiff, 3 ) ||
917 		rtiff_check_bits( rtiff, 8 ) ||
918 		rtiff_check_interpretation( rtiff, PHOTOMETRIC_CIELAB ) )
919 		return( -1 );
920 
921 	out->Bands = 4;
922 	out->BandFmt = VIPS_FORMAT_UCHAR;
923 	out->Coding = VIPS_CODING_LABQ;
924 	out->Type = VIPS_INTERPRETATION_LAB;
925 
926 	rtiff->sfn = rtiff_labpack_line;
927 
928 	return( 0 );
929 }
930 
931 
932 /* Per-scanline process function for 8-bit VIPS_CODING_LAB to 16-bit LabS with
933  * alpha.
934  */
935 static void
rtiff_lab_with_alpha_line(Rtiff * rtiff,VipsPel * q,VipsPel * p,int n,void * dummy)936 rtiff_lab_with_alpha_line( Rtiff *rtiff,
937 	VipsPel *q, VipsPel *p, int n, void *dummy )
938 {
939 	int samples_per_pixel = rtiff->header.samples_per_pixel;
940 
941 	unsigned char *p1;
942 	short *q1;
943 	int x;
944 
945 	p1 = (unsigned char *) p;
946 	q1 = (short *) q;
947 	for( x = 0; x < n; x++ ) {
948 		int i;
949 
950 		q1[0] = ((unsigned int) p1[0]) * 32767 / 255;
951 		q1[1] = ((short) p1[1]) << 8;
952 		q1[2] = ((short) p1[2]) << 8;
953 
954 		for( i = 3; i < samples_per_pixel; i++ )
955 			q1[i] = (p1[i] << 8) + p1[i];
956 
957 		q1 += samples_per_pixel;
958 		p1 += samples_per_pixel;
959 	}
960 }
961 
962 /* Read an 8-bit LAB image with alpha bands into 16-bit LabS.
963  */
964 static int
rtiff_parse_lab_with_alpha(Rtiff * rtiff,VipsImage * out)965 rtiff_parse_lab_with_alpha( Rtiff *rtiff, VipsImage *out )
966 {
967 	if( rtiff_check_min_samples( rtiff, 4 ) ||
968 		rtiff_check_bits( rtiff, 8 ) ||
969 		rtiff_check_interpretation( rtiff, PHOTOMETRIC_CIELAB ) )
970 		return( -1 );
971 
972 	out->Bands = rtiff->header.samples_per_pixel;
973 	out->BandFmt = VIPS_FORMAT_SHORT;
974 	out->Coding = VIPS_CODING_NONE;
975 	out->Type = VIPS_INTERPRETATION_LABS;
976 
977 	rtiff->sfn = rtiff_lab_with_alpha_line;
978 
979 	return( 0 );
980 }
981 
982 /* Per-scanline process function for LABS.
983  */
984 static void
rtiff_labs_line(Rtiff * rtiff,VipsPel * q,VipsPel * p,int n,void * dummy)985 rtiff_labs_line( Rtiff *rtiff, VipsPel *q, VipsPel *p, int n, void *dummy )
986 {
987 	int samples_per_pixel = rtiff->header.samples_per_pixel;
988 
989 	unsigned short *p1;
990 	short *q1;
991 	int x;
992 	int i;
993 
994 	p1 = (unsigned short *) p;
995 	q1 = (short *) q;
996 	for( x = 0; x < n; x++ ) {
997 		/* We use signed int16 for L.
998 		 */
999 		q1[0] = p1[0] >> 1;
1000 
1001 		for( i = 1; i < samples_per_pixel; i++ )
1002 			q1[i] = p1[i];
1003 
1004 		q1 += samples_per_pixel;
1005 		p1 += samples_per_pixel;
1006 	}
1007 }
1008 
1009 /* Read a 16-bit LAB image.
1010  */
1011 static int
rtiff_parse_labs(Rtiff * rtiff,VipsImage * out)1012 rtiff_parse_labs( Rtiff *rtiff, VipsImage *out )
1013 {
1014 	if( rtiff_check_min_samples( rtiff, 3 ) ||
1015 		rtiff_check_bits( rtiff, 16 ) ||
1016 		rtiff_check_interpretation( rtiff, PHOTOMETRIC_CIELAB ) )
1017 		return( -1 );
1018 
1019 	out->Bands = rtiff->header.samples_per_pixel;
1020 	out->BandFmt = VIPS_FORMAT_SHORT;
1021 	out->Coding = VIPS_CODING_NONE;
1022 	out->Type = VIPS_INTERPRETATION_LABS;
1023 
1024 	rtiff->sfn = rtiff_labs_line;
1025 
1026 	return( 0 );
1027 }
1028 
1029 /* libtiff delivers logluv as illuminant-free 0-1 XYZ in 3 x float.
1030  */
1031 static void
rtiff_logluv_line(Rtiff * rtiff,VipsPel * q,VipsPel * p,int n,void * dummy)1032 rtiff_logluv_line( Rtiff *rtiff, VipsPel *q, VipsPel *p, int n, void *dummy )
1033 {
1034 	int samples_per_pixel = rtiff->header.samples_per_pixel;
1035 
1036 	float *p1;
1037 	float *q1;
1038 	int x;
1039 	int i;
1040 
1041 	p1 = (float *) p;
1042 	q1 = (float *) q;
1043 	for( x = 0; x < n; x++ ) {
1044 		q1[0] = VIPS_D65_X0 * p1[0];
1045 		q1[1] = VIPS_D65_Y0 * p1[1];
1046 		q1[2] = VIPS_D65_Z0 * p1[2];
1047 
1048 		for( i = 3; i < samples_per_pixel; i++ )
1049 			q1[i] = p1[i];
1050 
1051 		q1 += samples_per_pixel;
1052 		p1 += samples_per_pixel;
1053 	}
1054 }
1055 
1056 /* LOGLUV images arrive from libtiff as float xyz.
1057  */
1058 static int
rtiff_parse_logluv(Rtiff * rtiff,VipsImage * out)1059 rtiff_parse_logluv( Rtiff *rtiff, VipsImage *out )
1060 {
1061 	if( rtiff_check_min_samples( rtiff, 3 ) ||
1062 		rtiff_check_interpretation( rtiff, PHOTOMETRIC_LOGLUV ) )
1063 		return( -1 );
1064 
1065 	out->Bands = rtiff->header.samples_per_pixel;
1066 	out->BandFmt = VIPS_FORMAT_FLOAT;
1067 	out->Coding = VIPS_CODING_NONE;
1068 	out->Type = VIPS_INTERPRETATION_XYZ;
1069 
1070 	rtiff->sfn = rtiff_logluv_line;
1071 
1072 	return( 0 );
1073 }
1074 
1075 /* Make a N-bit scanline process function. We pass in the code to expand the
1076  * bits down the byte since this does not generalize well.
1077  */
1078 #define NBIT_LINE( N, EXPAND ) \
1079 static void \
1080 rtiff_ ## N ## bit_line( Rtiff *rtiff, \
1081 	VipsPel *q, VipsPel *p, int n, void *flg ) \
1082 { \
1083 	int photometric = rtiff->header.photometric_interpretation; \
1084 	int mask = photometric == PHOTOMETRIC_MINISBLACK ?  0 : 0xff; \
1085 	int bps = rtiff->header.bits_per_sample; \
1086 	int load = 8 / bps - 1; \
1087 	\
1088 	int x; \
1089 	VipsPel bits; \
1090 	\
1091 	/* Stop a compiler warning. \
1092 	 */ \
1093 	bits = 0; \
1094 	\
1095 	for( x = 0; x < n; x++ ) { \
1096 		if( (x & load) == 0 ) \
1097 			/* Flip the bits for miniswhite. \
1098 			 */ \
1099 			bits = *p++ ^ mask; \
1100 	 	\
1101 		EXPAND( q[x], bits ); \
1102 		\
1103 		bits <<= bps; \
1104 	} \
1105 }
1106 
1107 /* Expand the top bit down a byte. Use a sign-extending shift.
1108  */
1109 #define EXPAND1( Q, BITS ) G_STMT_START { \
1110 	(Q) = (((signed char) (BITS & 128)) >> 7); \
1111 } G_STMT_END
1112 
1113 /* Expand the top two bits down a byte. Shift down, then expand up.
1114  */
1115 #define EXPAND2( Q, BITS ) G_STMT_START { \
1116 	VipsPel twobits = BITS >> 6; \
1117 	VipsPel fourbits = twobits | (twobits << 2); \
1118 	Q = fourbits | (fourbits << 4); \
1119 } G_STMT_END
1120 
1121 /* Expand the top four bits down a byte.
1122  */
1123 #define EXPAND4( Q, BITS ) G_STMT_START { \
1124 	Q = (BITS & 0xf0) | (BITS >> 4); \
1125 } G_STMT_END
1126 
1127 NBIT_LINE( 1, EXPAND1 )
1128 NBIT_LINE( 2, EXPAND2 )
1129 NBIT_LINE( 4, EXPAND4 )
1130 
1131 /* Read a 1-bit TIFF image.
1132  */
1133 static int
rtiff_parse_onebit(Rtiff * rtiff,VipsImage * out)1134 rtiff_parse_onebit( Rtiff *rtiff, VipsImage *out )
1135 {
1136 	if( rtiff_check_samples( rtiff, 1 ) ||
1137 		rtiff_check_bits( rtiff, 1 ) )
1138 		return( -1 );
1139 
1140 	out->Bands = 1;
1141 	out->BandFmt = VIPS_FORMAT_UCHAR;
1142 	out->Coding = VIPS_CODING_NONE;
1143 	out->Type = VIPS_INTERPRETATION_B_W;
1144 
1145 	rtiff->sfn = rtiff_1bit_line;
1146 
1147 	return( 0 );
1148 }
1149 
1150 /* Read a 2-bit TIFF image.
1151  */
1152 static int
rtiff_parse_twobit(Rtiff * rtiff,VipsImage * out)1153 rtiff_parse_twobit( Rtiff *rtiff, VipsImage *out )
1154 {
1155 	if( rtiff_check_samples( rtiff, 1 ) ||
1156 		rtiff_check_bits( rtiff, 2 ) )
1157 		return( -1 );
1158 
1159 	out->Bands = 1;
1160 	out->BandFmt = VIPS_FORMAT_UCHAR;
1161 	out->Coding = VIPS_CODING_NONE;
1162 	out->Type = VIPS_INTERPRETATION_B_W;
1163 
1164 	rtiff->sfn = rtiff_2bit_line;
1165 
1166 	return( 0 );
1167 }
1168 
1169 /* Read a 4-bit TIFF image.
1170  */
1171 static int
rtiff_parse_fourbit(Rtiff * rtiff,VipsImage * out)1172 rtiff_parse_fourbit( Rtiff *rtiff, VipsImage *out )
1173 {
1174 	if( rtiff_check_samples( rtiff, 1 ) ||
1175 		rtiff_check_bits( rtiff, 4 ) )
1176 		return( -1 );
1177 
1178 	out->Bands = 1;
1179 	out->BandFmt = VIPS_FORMAT_UCHAR;
1180 	out->Coding = VIPS_CODING_NONE;
1181 	out->Type = VIPS_INTERPRETATION_B_W;
1182 
1183 	rtiff->sfn = rtiff_4bit_line;
1184 
1185 	return( 0 );
1186 }
1187 
1188 /* Swap the sense of the first channel, if necessary.
1189  */
1190 #define GREY_LOOP( TYPE, MAX ) { \
1191 	TYPE *p1; \
1192 	TYPE *q1; \
1193 	\
1194 	p1 = (TYPE *) p; \
1195 	q1 = (TYPE *) q; \
1196 	for( x = 0; x < n; x++ ) { \
1197 		if( invert ) \
1198 			q1[0] = MAX - p1[0]; \
1199 		else \
1200 			q1[0] = p1[0]; \
1201 		\
1202 		for( i = 1; i < samples_per_pixel; i++ ) \
1203 			q1[i] = p1[i]; \
1204 		\
1205 		q1 += samples_per_pixel; \
1206 		p1 += samples_per_pixel; \
1207 	} \
1208 }
1209 
1210 /* Per-scanline process function for greyscale images.
1211  */
1212 static void
rtiff_greyscale_line(Rtiff * rtiff,VipsPel * q,VipsPel * p,int n,void * client)1213 rtiff_greyscale_line( Rtiff *rtiff,
1214 	VipsPel *q, VipsPel *p, int n, void *client )
1215 {
1216 	int samples_per_pixel = rtiff->header.samples_per_pixel;
1217 	int photometric_interpretation =
1218 		rtiff->header.photometric_interpretation;
1219 	VipsBandFormat format = rtiff_guess_format( rtiff );
1220 
1221 	/* Swapping black and white doesn't make sense for the signed formats.
1222 	 */
1223 	gboolean invert =
1224 		photometric_interpretation == PHOTOMETRIC_MINISWHITE &&
1225 		vips_band_format_isuint( format );
1226 
1227 	int x, i;
1228 
1229 	switch( format ) {
1230 	case VIPS_FORMAT_CHAR:
1231 		GREY_LOOP( gchar, 0 );
1232 		break;
1233 
1234 	case VIPS_FORMAT_UCHAR:
1235 		GREY_LOOP( guchar, UCHAR_MAX );
1236 		break;
1237 
1238 	case VIPS_FORMAT_SHORT:
1239 		GREY_LOOP( gshort, 0 );
1240 		break;
1241 
1242 	case VIPS_FORMAT_USHORT:
1243 		GREY_LOOP( gushort, USHRT_MAX );
1244 		break;
1245 
1246 	case VIPS_FORMAT_INT:
1247 		GREY_LOOP( gint, 0 );
1248 		break;
1249 
1250 	case VIPS_FORMAT_UINT:
1251 		GREY_LOOP( guint, UINT_MAX );
1252 		break;
1253 
1254 	case VIPS_FORMAT_FLOAT:
1255 		GREY_LOOP( float, 1.0 );
1256 		break;
1257 
1258 	case VIPS_FORMAT_DOUBLE:
1259 		GREY_LOOP( double, 1.0 );
1260 		break;
1261 
1262 	default:
1263 		g_assert_not_reached();
1264 	}
1265 }
1266 
1267 /* Read a grey-scale TIFF image. We have to invert the first band if
1268  * PHOTOMETRIC_MINISBLACK is set.
1269  */
1270 static int
rtiff_parse_greyscale(Rtiff * rtiff,VipsImage * out)1271 rtiff_parse_greyscale( Rtiff *rtiff, VipsImage *out )
1272 {
1273 	if( rtiff_check_min_samples( rtiff, 1 ) ||
1274 		rtiff_non_fractional( rtiff ) )
1275 		return( -1 );
1276 
1277 	out->Bands = rtiff->header.samples_per_pixel;
1278 	out->BandFmt = rtiff_guess_format( rtiff );
1279 	if( out->BandFmt == VIPS_FORMAT_NOTSET )
1280 		return( -1 );
1281 	out->Coding = VIPS_CODING_NONE;
1282 
1283 	if( rtiff->header.bits_per_sample == 16 )
1284 		out->Type = VIPS_INTERPRETATION_GREY16;
1285 	else
1286 		out->Type = VIPS_INTERPRETATION_B_W;
1287 
1288 	/* rtiff_greyscale_line() doesn't do complex.
1289 	 */
1290 	if( vips_check_noncomplex( "tiff2vips", out ) )
1291 		return( -1 );
1292 
1293 	rtiff->sfn = rtiff_greyscale_line;
1294 
1295 	return( 0 );
1296 }
1297 
1298 typedef struct {
1299 	/* LUTs mapping image indexes to RGB.
1300 	 */
1301 	VipsPel *red8;
1302 	VipsPel *green8;
1303 	VipsPel *blue8;
1304 
1305 	guint16 *red16;
1306 	guint16 *green16;
1307 	guint16 *blue16;
1308 
1309 	/* All maps equal, so we write mono.
1310 	 */
1311 	gboolean mono;
1312 } PaletteRead;
1313 
1314 /* 1/2/4 bit samples with an 8-bit palette.
1315  */
1316 static void
rtiff_palette_line_bit(Rtiff * rtiff,VipsPel * q,VipsPel * p,int n,void * client)1317 rtiff_palette_line_bit( Rtiff *rtiff,
1318 	VipsPel *q, VipsPel *p, int n, void *client )
1319 {
1320 	PaletteRead *read = (PaletteRead *) client;
1321 	int samples_per_pixel = rtiff->header.samples_per_pixel;
1322 	int bits_per_sample = rtiff->header.bits_per_sample;
1323 
1324 	int bit;
1325 	VipsPel data;
1326 	int x;
1327 
1328 	bit = 0;
1329 	data = 0;
1330 	for( x = 0; x < n * samples_per_pixel; x++ ) {
1331 		int i;
1332 
1333 		if( bit <= 0 ) {
1334 			data = *p++;
1335 			bit = 8;
1336 		}
1337 
1338 		i = data >> (8 - bits_per_sample);
1339 		data <<= bits_per_sample;
1340 		bit -= bits_per_sample;
1341 
1342 		/* The first band goes through the LUT, subsequent bands are
1343 		 * left-justified and copied.
1344 		 */
1345 		if( x % samples_per_pixel == 0 ) {
1346 			if( read->mono )
1347 				*q++ = read->red8[i];
1348 			else {
1349 				q[0] = read->red8[i];
1350 				q[1] = read->green8[i];
1351 				q[2] = read->blue8[i];
1352 				q += 3;
1353 			}
1354 		}
1355 		else
1356 			*q++ = VIPS_LSHIFT_INT( i, 8 - bits_per_sample );
1357 	}
1358 }
1359 
1360 /* 8-bit samples with an 8-bit palette.
1361  */
1362 static void
rtiff_palette_line8(Rtiff * rtiff,VipsPel * q,VipsPel * p,int n,void * client)1363 rtiff_palette_line8( Rtiff *rtiff, VipsPel *q, VipsPel *p, int n,
1364 	void *client )
1365 {
1366 	PaletteRead *read = (PaletteRead *) client;
1367 	int samples_per_pixel = rtiff->header.samples_per_pixel;
1368 
1369 	int x;
1370 	int s;
1371 
1372 	for( x = 0; x < n; x++ ) {
1373 		int i = p[0];
1374 
1375 		if( read->mono )
1376 			q[0] = read->red8[i];
1377 		else {
1378 			q[0] = read->red8[i];
1379 			q[1] = read->green8[i];
1380 			q[2] = read->blue8[i];
1381 			q += 2;
1382 		}
1383 
1384 		for( s = 1; s < samples_per_pixel; s++ )
1385 			q[s] = p[s];
1386 
1387 		q += samples_per_pixel;
1388 		p += samples_per_pixel;
1389 	}
1390 }
1391 
1392 /* 16-bit samples with 16-bit data in the palette.
1393  */
1394 static void
rtiff_palette_line16(Rtiff * rtiff,VipsPel * q,VipsPel * p,int n,void * client)1395 rtiff_palette_line16( Rtiff *rtiff, VipsPel *q, VipsPel *p, int n,
1396 	void *client )
1397 {
1398 	PaletteRead *read = (PaletteRead *) client;
1399 	int samples_per_pixel = rtiff->header.samples_per_pixel;
1400 
1401 	guint16 *p16, *q16;
1402 	int x;
1403 	int s;
1404 
1405 	q16 = (guint16 *) q;
1406 	p16 = (guint16 *) p;
1407 
1408 	for( x = 0; x < n; x++ ) {
1409 		int i = p16[0];
1410 
1411 		if( read->mono )
1412 			q16[0] = read->red16[i];
1413 		else {
1414 			q16[0] = read->red16[i];
1415 			q16[1] = read->green16[i];
1416 			q16[2] = read->blue16[i];
1417 			q16 += 2;
1418 		}
1419 
1420 		for( s = 1; s < samples_per_pixel; s++ )
1421 			q16[s] = p16[s];
1422 
1423 		q16 += samples_per_pixel;
1424 		p16 += samples_per_pixel;
1425 	}
1426 }
1427 
1428 /* Read a palette-ised TIFF image.
1429  */
1430 static int
rtiff_parse_palette(Rtiff * rtiff,VipsImage * out)1431 rtiff_parse_palette( Rtiff *rtiff, VipsImage *out )
1432 {
1433 	int samples_per_pixel = rtiff->header.samples_per_pixel;
1434 	int bits_per_sample = rtiff->header.bits_per_sample;
1435 
1436 	int len;
1437 	PaletteRead *read;
1438 	int i;
1439 
1440 	if( rtiff_check_bits_palette( rtiff ) ||
1441 		rtiff_check_min_samples( rtiff, 1 ) )
1442 		return( -1 );
1443 	len = 1 << bits_per_sample;
1444 
1445 	if( !(read = VIPS_NEW( out, PaletteRead )) ||
1446 		!(read->red8 = VIPS_ARRAY( out, len, VipsPel )) ||
1447 		!(read->green8 = VIPS_ARRAY( out, len, VipsPel )) ||
1448 		!(read->blue8 = VIPS_ARRAY( out, len, VipsPel )) )
1449 		return( -1 );
1450 
1451 	/* Get maps, convert to 8-bit data.
1452 	 */
1453 	if( !TIFFGetField( rtiff->tiff,
1454 		TIFFTAG_COLORMAP,
1455 		&read->red16, &read->green16, &read->blue16 ) ) {
1456 		vips_error( "tiff2vips", "%s", _( "bad colormap" ) );
1457 		return( -1 );
1458 	}
1459 
1460 	/* Old-style colourmaps were 8-bit. If all the top bytes are zero,
1461 	 * assume we have one of these.
1462 	 *
1463 	 * See: https://github.com/libvips/libvips/issues/220
1464 	 */
1465 	for( i = 0; i < len; i++ )
1466 		if( (read->red16[i] >> 8) |
1467 			(read->green16[i] >> 8) |
1468 			(read->blue16[i] >> 8) )
1469 			break;
1470 	if( i < len )
1471 		for( i = 0; i < len; i++ ) {
1472 			read->red8[i] = read->red16[i] >> 8;
1473 			read->green8[i] = read->green16[i] >> 8;
1474 			read->blue8[i] = read->blue16[i] >> 8;
1475 		}
1476 	else {
1477 		g_warning( "%s", _( "assuming 8-bit palette" ) );
1478 
1479 		for( i = 0; i < len; i++ ) {
1480 			read->red8[i] = read->red16[i] & 0xff;
1481 			read->green8[i] = read->green16[i] & 0xff;
1482 			read->blue8[i] = read->blue16[i] & 0xff;
1483 		}
1484 	}
1485 
1486 	/* Are all the maps equal? We have a mono image.
1487 	 */
1488 	read->mono = TRUE;
1489 	for( i = 0; i < len; i++ )
1490 		if( read->red16[i] != read->green16[i] ||
1491 			read->green16[i] != read->blue16[i] ) {
1492 			read->mono = FALSE;
1493 			break;
1494 		}
1495 
1496 	/* There's a TIFF extension, INDEXED, that is the preferred way to
1497 	 * encode mono palette images, but few applications support it. So we
1498 	 * just search the colormap.
1499 	 */
1500 
1501 	if( bits_per_sample <= 8 )
1502 		out->BandFmt = VIPS_FORMAT_UCHAR;
1503 	else
1504 		out->BandFmt = VIPS_FORMAT_USHORT;
1505 	out->Coding = VIPS_CODING_NONE;
1506 
1507 	if( read->mono ) {
1508 		out->Bands = samples_per_pixel;
1509 		if( bits_per_sample <= 8 )
1510 			out->Type = VIPS_INTERPRETATION_B_W;
1511 		else
1512 			out->Type = VIPS_INTERPRETATION_GREY16;
1513 	}
1514 	else {
1515 		out->Bands = samples_per_pixel + 2;
1516 		if( bits_per_sample <= 8 )
1517 			out->Type = VIPS_INTERPRETATION_sRGB;
1518 		else
1519 			out->Type = VIPS_INTERPRETATION_RGB16;
1520 	}
1521 
1522 	rtiff->client = read;
1523 	if( bits_per_sample < 8 )
1524 		rtiff->sfn = rtiff_palette_line_bit;
1525 	else if( bits_per_sample == 8 )
1526 		rtiff->sfn = rtiff_palette_line8;
1527 	else if( bits_per_sample == 16 )
1528 		rtiff->sfn = rtiff_palette_line16;
1529 	else
1530 		g_assert_not_reached();
1531 
1532 	return( 0 );
1533 }
1534 
1535 /* Per-scanline process function when we just need to copy.
1536  */
1537 static void
rtiff_memcpy_line(Rtiff * rtiff,VipsPel * q,VipsPel * p,int n,void * client)1538 rtiff_memcpy_line( Rtiff *rtiff, VipsPel *q, VipsPel *p, int n, void *client )
1539 {
1540 	VipsImage *im = (VipsImage *) client;
1541 	size_t len = n * VIPS_IMAGE_SIZEOF_PEL( im );
1542 
1543 	memcpy( q, p, len );
1544 }
1545 
1546 /* Read a regular multiband image where we can just copy pixels from the tiff
1547  * buffer.
1548  */
1549 static int
rtiff_parse_copy(Rtiff * rtiff,VipsImage * out)1550 rtiff_parse_copy( Rtiff *rtiff, VipsImage *out )
1551 {
1552 	int samples_per_pixel = rtiff->header.samples_per_pixel;
1553 	int photometric_interpretation =
1554 		rtiff->header.photometric_interpretation;
1555 	int inkset = rtiff->header.inkset;
1556 
1557 	if( rtiff_non_fractional( rtiff ) )
1558 		return( -1 );
1559 
1560 	out->Bands = samples_per_pixel;
1561 	out->BandFmt = rtiff_guess_format( rtiff );
1562 	if( out->BandFmt == VIPS_FORMAT_NOTSET )
1563 		return( -1 );
1564 	out->Coding = VIPS_CODING_NONE;
1565 
1566 	if( samples_per_pixel >= 3 &&
1567 		(photometric_interpretation == PHOTOMETRIC_RGB ||
1568 		 photometric_interpretation == PHOTOMETRIC_YCBCR) ) {
1569 		if( out->BandFmt == VIPS_FORMAT_USHORT )
1570 			out->Type = VIPS_INTERPRETATION_RGB16;
1571 		else if( !vips_band_format_isint( out->BandFmt ) )
1572 			/* Most float images use 0 - 1 for black - white.
1573 			 * Photoshop uses 0 - 1 and no gamma.
1574 			 */
1575 			out->Type = VIPS_INTERPRETATION_scRGB;
1576 		else
1577 			out->Type = VIPS_INTERPRETATION_sRGB;
1578 	}
1579 	else if( samples_per_pixel >= 3 &&
1580 		photometric_interpretation == PHOTOMETRIC_CIELAB )
1581 		out->Type = VIPS_INTERPRETATION_LAB;
1582 	else if( photometric_interpretation == PHOTOMETRIC_SEPARATED &&
1583 		samples_per_pixel >= 4 &&
1584 		inkset == INKSET_CMYK )
1585 		out->Type = VIPS_INTERPRETATION_CMYK;
1586 	else
1587 		out->Type = VIPS_INTERPRETATION_MULTIBAND;
1588 
1589 	rtiff->sfn = rtiff_memcpy_line;
1590 	rtiff->client = out;
1591 
1592 	/* We expand YCBCR images to RGB using JPEGCOLORMODE_RGB, and this
1593 	 * means we need a slightly larger read buffer for the edge pixels. In
1594 	 * turn, this means we can't just memcpy to libvips regions.
1595 	 */
1596 	rtiff->memcpy = photometric_interpretation != PHOTOMETRIC_YCBCR;
1597 
1598 	return( 0 );
1599 }
1600 
1601 typedef int (*reader_fn)( Rtiff *rtiff, VipsImage *out );
1602 
1603 /* We have a range of output paths. Look at the tiff header and try to
1604  * route the input image to the best output path.
1605  */
1606 static reader_fn
rtiff_pick_reader(Rtiff * rtiff)1607 rtiff_pick_reader( Rtiff *rtiff )
1608 {
1609 	int bits_per_sample = rtiff->header.bits_per_sample;
1610 	int photometric_interpretation =
1611 		rtiff->header.photometric_interpretation;
1612 	int samples_per_pixel = rtiff->header.samples_per_pixel;
1613 
1614 	if( photometric_interpretation == PHOTOMETRIC_CIELAB ) {
1615 		if( bits_per_sample == 8 ) {
1616 			if( samples_per_pixel > 3 )
1617 				return( rtiff_parse_lab_with_alpha );
1618 			else
1619 				return( rtiff_parse_labpack );
1620 		}
1621 		if( bits_per_sample == 16 )
1622 			return( rtiff_parse_labs );
1623 	}
1624 
1625 	if( photometric_interpretation == PHOTOMETRIC_LOGLUV )
1626 		return( rtiff_parse_logluv );
1627 
1628 	if( photometric_interpretation == PHOTOMETRIC_MINISWHITE ||
1629 		photometric_interpretation == PHOTOMETRIC_MINISBLACK ) {
1630 
1631 		if( bits_per_sample == 1)
1632 			return ( rtiff_parse_onebit );
1633 		else if ( bits_per_sample == 2 )
1634 			return ( rtiff_parse_twobit);
1635 		else if ( bits_per_sample == 4 )
1636 			return ( rtiff_parse_fourbit);
1637 		else
1638 			return( rtiff_parse_greyscale );
1639 	}
1640 
1641 	if( photometric_interpretation == PHOTOMETRIC_PALETTE )
1642 		return( rtiff_parse_palette );
1643 
1644 	return( rtiff_parse_copy );
1645 }
1646 
1647 /* Set the header on @out from our rtiff. rtiff_header_read() has already been
1648  * called.
1649  */
1650 static int
rtiff_set_header(Rtiff * rtiff,VipsImage * out)1651 rtiff_set_header( Rtiff *rtiff, VipsImage *out )
1652 {
1653 	guint32 data_length;
1654 	void *data;
1655 
1656 	rtiff_set_decode_format( rtiff );
1657 
1658 	if( rtiff->header.photometric_interpretation == PHOTOMETRIC_LOGLUV )
1659 		vips_image_set_double( out, "stonits", rtiff->header.stonits );
1660 
1661 	out->Xsize = rtiff->header.width;
1662 	out->Ysize = rtiff->header.height * rtiff->n;
1663 
1664 	VIPS_SETSTR( out->filename,
1665 		vips_connection_filename( VIPS_CONNECTION( rtiff->source ) ) );
1666 
1667 	if( rtiff->n > 1 )
1668 		vips_image_set_int( out,
1669 			VIPS_META_PAGE_HEIGHT, rtiff->header.height );
1670 
1671 	if( rtiff->header.subifd_count > 0 )
1672 		vips_image_set_int( out,
1673 			VIPS_META_N_SUBIFDS, rtiff->header.subifd_count );
1674 
1675 	vips_image_set_int( out, VIPS_META_N_PAGES, rtiff->n_pages );
1676 
1677 	/* Even though we could end up serving tiled data, always hint
1678 	 * THINSTRIP, since we're quite happy doing that too, and it could need
1679 	 * a lot less memory.
1680 	 */
1681         vips_image_pipelinev( out, VIPS_DEMAND_STYLE_THINSTRIP, NULL );
1682 
1683 	/* We have a range of output paths. Look at the tiff header and try to
1684 	 * route the input image to the best output path.
1685 	 */
1686 	if( rtiff_pick_reader( rtiff )( rtiff, out ) )
1687 		return( -1 );
1688 
1689 	/* Read any ICC profile.
1690 	 */
1691 	if( TIFFGetField( rtiff->tiff,
1692 		TIFFTAG_ICCPROFILE, &data_length, &data ) )
1693 		vips_image_set_blob_copy( out,
1694 			VIPS_META_ICC_NAME, data, data_length );
1695 
1696 	/* Read any XMP metadata.
1697 	 */
1698 	if( TIFFGetField( rtiff->tiff,
1699 		TIFFTAG_XMLPACKET, &data_length, &data ) )
1700 		vips_image_set_blob_copy( out,
1701 			VIPS_META_XMP_NAME, data, data_length );
1702 
1703 	/* Read any IPTC metadata.
1704 	 */
1705 	if( TIFFGetField( rtiff->tiff,
1706 		TIFFTAG_RICHTIFFIPTC, &data_length, &data ) ) {
1707 		vips_image_set_blob_copy( out,
1708 			VIPS_META_IPTC_NAME, data, data_length );
1709 
1710 		/* Older versions of libvips used this misspelt name :-( attach
1711 		 * under this name too for compatibility.
1712 		 */
1713 		vips_image_set_blob_copy( out, "ipct-data", data, data_length );
1714 	}
1715 
1716 	/* Read any photoshop metadata.
1717 	 */
1718 	if( TIFFGetField( rtiff->tiff,
1719 		TIFFTAG_PHOTOSHOP, &data_length, &data ) )
1720 		vips_image_set_blob_copy( out,
1721 			VIPS_META_PHOTOSHOP_NAME, data, data_length );
1722 
1723 	if( rtiff->header.image_description )
1724 		vips_image_set_string( out, VIPS_META_IMAGEDESCRIPTION,
1725 			rtiff->header.image_description );
1726 
1727 	if( get_resolution( rtiff->tiff, out ) )
1728 		return( -1 );
1729 
1730 	/* Set the "orientation" tag. This is picked up later by autorot, if
1731 	 * requested.
1732 	 */
1733 	vips_image_set_int( out,
1734 		VIPS_META_ORIENTATION, rtiff->header.orientation );
1735 
1736 	return( 0 );
1737 }
1738 
1739 /* Allocate a tile buffer. Have one of these for each thread so we can unpack
1740  * to vips in parallel.
1741  */
1742 static void *
rtiff_seq_start(VipsImage * out,void * a,void * b)1743 rtiff_seq_start( VipsImage *out, void *a, void *b )
1744 {
1745 	Rtiff *rtiff = (Rtiff *) a;
1746 	tdata_t *buf;
1747 
1748 	if( !(buf = vips_malloc( NULL, rtiff->header.tile_size )) )
1749 		return( NULL );
1750 
1751 	return( (void *) buf );
1752 }
1753 
1754 static int
rtiff_read_tile(Rtiff * rtiff,tdata_t * buf,int x,int y)1755 rtiff_read_tile( Rtiff *rtiff, tdata_t *buf, int x, int y )
1756 {
1757 #ifdef DEBUG_VERBOSE
1758 	printf( "rtiff_read_tile: x = %d, y = %d, we_decompress = %d\n",
1759 		x, y, rtiff->header.we_decompress );
1760 #endif /*DEBUG_VERBOSE*/
1761 
1762 	if( rtiff->header.we_decompress ) {
1763 		ttile_t tile_no = TIFFComputeTile( rtiff->tiff, x, y, 0, 0 );
1764 
1765 		tsize_t size;
1766 
1767 		size = TIFFReadRawTile( rtiff->tiff, tile_no,
1768 			rtiff->compressed_buf, rtiff->compressed_buf_length );
1769 		if( size <= 0 ) {
1770 			vips_foreign_load_invalidate( rtiff->out );
1771 			return( -1 );
1772 		}
1773 
1774 		switch( rtiff->header.compression ) {
1775 		case JP2K_YCC:
1776 		case JP2K_RGB:
1777 		case JP2K_LOSSY:
1778 			if( vips__foreign_load_jp2k_decompress(
1779 				rtiff->out,
1780 				rtiff->header.tile_width,
1781 				rtiff->header.tile_height,
1782 				TRUE,
1783 				rtiff->compressed_buf, size,
1784 				buf, rtiff->header.tile_size ) )
1785 				return( -1 );
1786 			break;
1787 
1788 		default:
1789 			g_assert_not_reached();
1790 			break;
1791 		}
1792 
1793 	}
1794 	else {
1795 		if( TIFFReadTile( rtiff->tiff, buf, x, y, 0, 0 ) < 0 ) {
1796 			vips_foreign_load_invalidate( rtiff->out );
1797 			return( -1 );
1798 		}
1799 	}
1800 
1801 	return( 0 );
1802 }
1803 
1804 /* Paint a tile from the file. This is a
1805  * special-case for when a region is exactly a tiff tile, and pixels need no
1806  * conversion. In this case, libtiff can read tiles directly to our output
1807  * region.
1808  */
1809 static int
rtiff_fill_region_aligned(VipsRegion * out,void * seq,void * a,void * b,gboolean * stop)1810 rtiff_fill_region_aligned( VipsRegion *out,
1811 	void *seq, void *a, void *b, gboolean *stop )
1812 {
1813 	Rtiff *rtiff = (Rtiff *) a;
1814 	VipsRect *r = &out->valid;
1815 	int page_height = rtiff->header.height;
1816 	int page_no = r->top / page_height;
1817 	int page_y = r->top % page_height;
1818 
1819 	g_assert( (r->left % rtiff->header.tile_width) == 0 );
1820 	g_assert( (r->top % rtiff->header.tile_height) == 0 );
1821 	g_assert( r->width == rtiff->header.tile_width );
1822 	g_assert( r->height == rtiff->header.tile_height );
1823 	g_assert( VIPS_REGION_LSKIP( out ) == VIPS_REGION_SIZEOF_LINE( out ) );
1824 
1825 #ifdef DEBUG_VERBOSE
1826 	printf( "rtiff_fill_region_aligned:\n" );
1827 #endif /*DEBUG_VERBOSE*/
1828 
1829 	/* Read that tile directly into the vips tile.
1830 	 */
1831 	if( rtiff_set_page( rtiff, rtiff->page + page_no ) ||
1832 		rtiff_read_tile( rtiff,
1833 			(tdata_t *) VIPS_REGION_ADDR( out, r->left, r->top ),
1834 		r->left, page_y ) )
1835 		return( -1 );
1836 
1837 	return( 0 );
1838 }
1839 
1840 /* Loop over the output region, painting in tiles from the file.
1841  */
1842 static int
rtiff_fill_region_unaligned(VipsRegion * out,void * seq,void * a,void * b,gboolean * stop)1843 rtiff_fill_region_unaligned( VipsRegion *out,
1844 	void *seq, void *a, void *b, gboolean *stop )
1845 {
1846 	tdata_t *buf = (tdata_t *) seq;
1847 	Rtiff *rtiff = (Rtiff *) a;
1848 	int tile_width = rtiff->header.tile_width;
1849 	int tile_height = rtiff->header.tile_height;
1850 	int page_height = rtiff->header.height;
1851 	int tile_row_size = rtiff->header.tile_row_size;
1852 	VipsRect *r = &out->valid;
1853 
1854 	int x, y, z;
1855 
1856 #ifdef DEBUG_VERBOSE
1857 	printf( "rtiff_fill_region_unaligned:\n" );
1858 #endif /*DEBUG_VERBOSE*/
1859 
1860 	y = 0;
1861 	while( y < r->height ) {
1862 		VipsRect tile, page, hit;
1863 
1864 		/* Not necessary, but it stops static analyzers complaining
1865 		 * about a used-before-set.
1866 		 */
1867 		hit.height = 0;
1868 
1869 		x = 0;
1870 		while( x < r->width ) {
1871 			/* page_no is within this toilet roll image, not tiff
1872 			 * file page number ... add the number of the start
1873 			 * page to get that.
1874 			 */
1875 			int page_no = (r->top + y) / page_height;
1876 			int page_y = (r->top + y) % page_height;
1877 
1878 			/* Coordinate of the tile on this page that xy falls in.
1879 			 */
1880 			int xs = ((r->left + x) / tile_width) * tile_width;
1881 			int ys = (page_y / tile_height) * tile_height;
1882 
1883 			if( rtiff_set_page( rtiff, rtiff->page + page_no ) ||
1884 				rtiff_read_tile( rtiff, buf, xs, ys ) )
1885 				return( -1 );
1886 
1887 			/* Position of tile on the page.
1888 			 */
1889 			tile.left = xs;
1890 			tile.top = ys;
1891 			tile.width = tile_width;
1892 			tile.height = tile_height;
1893 
1894 			/* It'll be clipped by this page.
1895 			 */
1896 			page.left = 0;
1897 			page.top = 0;
1898 			page.width = rtiff->header.width;
1899 			page.height = rtiff->header.height;
1900 			vips_rect_intersectrect( &tile, &page, &tile );
1901 
1902 			/* To image coordinates.
1903 			 */
1904 			tile.top += page_no * page_height;
1905 
1906 			/* And clip again by this region.
1907 			 */
1908 			vips_rect_intersectrect( &tile, r, &hit );
1909 
1910 			/* We are inside a tilecache, so requests will always
1911 			 * be aligned left-right to tile boundaries.
1912 			 *
1913 			 * this is not true vertically for toilet-roll images.
1914 			 */
1915 			g_assert( hit.left == tile.left );
1916 
1917 			/* Unpack to VIPS format.
1918 			 * Just unpack the section of the tile we need.
1919 			 */
1920 			for( z = 0; z < hit.height; z++ ) {
1921 				VipsPel *p = (VipsPel *) buf +
1922 					(hit.top - tile.top + z) *
1923 					tile_row_size;
1924 				VipsPel *q = VIPS_REGION_ADDR( out,
1925 					hit.left, hit.top + z );
1926 
1927 				rtiff->sfn( rtiff,
1928 					q, p, hit.width, rtiff->client );
1929 			}
1930 
1931 			x += hit.width;
1932 		}
1933 
1934 		/* This will be the same for all tiles in the row we've just
1935 		 * done.
1936 		 */
1937 		y += hit.height;
1938 	}
1939 
1940 	return( 0 );
1941 }
1942 
1943 /* Loop over the output region, painting in tiles from the file.
1944  */
1945 static int
rtiff_fill_region(VipsRegion * out,void * seq,void * a,void * b,gboolean * stop)1946 rtiff_fill_region( VipsRegion *out,
1947 	void *seq, void *a, void *b, gboolean *stop )
1948 {
1949 	Rtiff *rtiff = (Rtiff *) a;
1950 	int tile_width = rtiff->header.tile_width;
1951 	int tile_height = rtiff->header.tile_height;
1952 	int page_width = rtiff->header.width;
1953 	int page_height = rtiff->header.height;
1954 	VipsRect *r = &out->valid;
1955 	int page_no = r->top / page_height;
1956 	int page_y = r->top % page_height;
1957 
1958 	VipsGenerateFn generate;
1959 
1960 #ifdef DEBUG_VERBOSE
1961 	printf( "rtiff_fill_region: left = %d, top = %d, "
1962 		"width = %d, height = %d\n",
1963 		r->left, r->top, r->width, r->height );
1964 #endif /*DEBUG_VERBOSE*/
1965 
1966 	/* Special case: we are filling a single cache tile exactly sized to
1967 	 * match the tiff tile, and we have no repacking to do for this format.
1968 	 *
1969 	 * If we are not on the first page, pages must be a multiple of the
1970 	 * tile size of we'll miss alignment.
1971 	 */
1972 	if( (page_no == 0 || page_height % tile_height == 0) &&
1973 		r->left % tile_width == 0 &&
1974 		r->top % tile_height == 0 &&
1975 		r->width == tile_width &&
1976 		r->height == tile_height &&
1977 		r->left + tile_width <= page_width &&
1978 		page_y + tile_height <= page_height &&
1979 		VIPS_REGION_LSKIP( out ) == VIPS_REGION_SIZEOF_LINE( out ) &&
1980 		rtiff->memcpy )
1981 		generate = rtiff_fill_region_aligned;
1982 	else
1983 		generate = rtiff_fill_region_unaligned;
1984 
1985 	VIPS_GATE_START( "rtiff_fill_region: work" );
1986 
1987 	if( generate( out, seq, a, b, stop ) ) {
1988 		VIPS_GATE_STOP( "rtiff_fill_region: work" );
1989 		return( -1 );
1990 	}
1991 
1992 	VIPS_GATE_STOP( "rtiff_fill_region: work" );
1993 
1994 	return( 0 );
1995 }
1996 
1997 static int
rtiff_seq_stop(void * seq,void * a,void * b)1998 rtiff_seq_stop( void *seq, void *a, void *b )
1999 {
2000 	g_free( seq );
2001 
2002 	return( 0 );
2003 }
2004 
2005 /* Unpremultiply associative alpha, if any.
2006  */
2007 static int
rtiff_unpremultiply(Rtiff * rtiff,VipsImage * in,VipsImage ** out)2008 rtiff_unpremultiply( Rtiff *rtiff, VipsImage *in, VipsImage **out )
2009 {
2010 	if( rtiff->header.alpha_band != -1 ) {
2011 		VipsImage *x;
2012 
2013 		if(
2014 			vips_unpremultiply( in, &x,
2015 				"alpha_band", rtiff->header.alpha_band,
2016 				NULL ) ||
2017 			vips_cast( x, out, in->BandFmt, NULL ) ) {
2018 			g_object_unref( x );
2019 			return( -1 );
2020 		}
2021 		g_object_unref( x );
2022 	}
2023 	else {
2024 		*out = in;
2025 		g_object_ref( in );
2026 	}
2027 
2028 	return( 0 );
2029 }
2030 
2031 /* Tile-type TIFF reader core - pass in a per-tile transform. Generate into
2032  * the im and do it all partially.
2033  */
2034 static int
rtiff_read_tilewise(Rtiff * rtiff,VipsImage * out)2035 rtiff_read_tilewise( Rtiff *rtiff, VipsImage *out )
2036 {
2037 	int tile_width = rtiff->header.tile_width;
2038 	int tile_height = rtiff->header.tile_height;
2039 	VipsImage **t = (VipsImage **)
2040 		vips_object_local_array( VIPS_OBJECT( out ), 4 );
2041 
2042 	VipsImage *in;
2043 
2044 #ifdef DEBUG
2045 	printf( "tiff2vips: rtiff_read_tilewise\n" );
2046 #endif /*DEBUG*/
2047 
2048 	/* I don't have a sample images for tiled + separate, ban it for now.
2049 	 */
2050 	if( rtiff->header.separate ) {
2051 		vips_error( "tiff2vips",
2052 			"%s", _( "tiled separate planes not supported" ) );
2053 		return( -1 );
2054 	}
2055 
2056 	/* If we will be decompressing, we need a buffer large enough to hold
2057 	 * the largest compressed tile in any page.
2058 	 *
2059 	 * Allocate a buffer 2x the uncompressed tile size ... much simpler
2060 	 * than searching every page for the largest tile with
2061 	 * TIFFTAG_TILEBYTECOUNTS.
2062 	 */
2063 	if( rtiff->header.we_decompress ) {
2064 		rtiff->compressed_buf_length = 2 * rtiff->header.tile_size;
2065 		if( !(rtiff->compressed_buf = vips_malloc( VIPS_OBJECT( out ),
2066 			rtiff->compressed_buf_length )) )
2067 			return( -1 );
2068 	}
2069 
2070 	/* Read to this image, then cache to out, see below.
2071 	 */
2072 	t[0] = vips_image_new();
2073 
2074 	if( rtiff_set_header( rtiff, t[0] ) )
2075 		return( -1 );
2076 
2077 	/* Double check: in memcpy mode, the vips tilesize should exactly
2078 	 * match the tifftile size.
2079 	 */
2080 	if( rtiff->memcpy ) {
2081 		size_t vips_tile_size = VIPS_IMAGE_SIZEOF_PEL( t[0] ) *
2082 			tile_width * tile_height;
2083 
2084 		if( rtiff->header.tile_size != vips_tile_size ) {
2085 			vips_error( "tiff2vips",
2086 				"%s", _( "unsupported tiff image type" ) );
2087 			return( -1 );
2088 		}
2089 	}
2090 
2091 	/* Even though this is a tiled reader, we hint thinstrip since with
2092 	 * the cache we are quite happy serving that if anything downstream
2093 	 * would like it.
2094 	 */
2095         vips_image_pipelinev( t[0], VIPS_DEMAND_STYLE_THINSTRIP, NULL );
2096 
2097 	/* Generate to out, adding a cache. Enough tiles for two complete rows.
2098 	 */
2099 	if(
2100 		vips_image_generate( t[0],
2101 			rtiff_seq_start, rtiff_fill_region, rtiff_seq_stop,
2102 			rtiff, NULL ) ||
2103 		vips_tilecache( t[0], &t[1],
2104 			"tile_width", tile_width,
2105 			"tile_height", tile_height,
2106 			"max_tiles", 2 * (1 + t[0]->Xsize / tile_width),
2107 			NULL ) ||
2108 		rtiff_unpremultiply( rtiff, t[1], &t[2] ) )
2109 		return( -1 );
2110 	in = t[2];
2111 
2112 	/* Only do this if we have to.
2113 	 */
2114 	if( rtiff->autorotate &&
2115 		vips_image_get_orientation( in ) != 1 ) {
2116 		if( vips_autorot( in, &t[3], NULL ) )
2117 			return( -1 );
2118 		in = t[3];
2119 	}
2120 
2121 	if( vips_image_write( in, out ) )
2122 		return( -1 );
2123 
2124 	return( 0 );
2125 }
2126 
2127 /* Read a strip. If the image is in separate planes, read each plane and
2128  * interleave to the output.
2129  *
2130  * strip is the number of this strip in this page.
2131  */
2132 static int
rtiff_strip_read_interleaved(Rtiff * rtiff,tstrip_t strip,tdata_t buf)2133 rtiff_strip_read_interleaved( Rtiff *rtiff, tstrip_t strip, tdata_t buf )
2134 {
2135 	int samples_per_pixel = rtiff->header.samples_per_pixel;
2136 	int read_height = rtiff->header.read_height;
2137 	int bits_per_sample = rtiff->header.bits_per_sample;
2138 	int strip_y = strip * read_height;
2139 
2140 	if( rtiff->header.separate ) {
2141 		int page_width = rtiff->header.width;
2142 		int page_height = rtiff->header.height;
2143 		int strips_per_plane = 1 + (page_height - 1) / read_height;
2144 		int strip_height = VIPS_MIN( read_height,
2145 			page_height - strip_y );
2146 		int pels_per_strip = page_width * strip_height;
2147 		int bytes_per_sample = bits_per_sample >> 3;
2148 
2149 		int i, j, k;
2150 
2151 		for( i = 0; i < samples_per_pixel; i++ ) {
2152 			VipsPel *p;
2153 			VipsPel *q;
2154 
2155 			if( rtiff_strip_read( rtiff,
2156 				strips_per_plane * i + strip,
2157 				rtiff->plane_buf ) )
2158 				return( -1 );
2159 
2160 			p = (VipsPel *) rtiff->plane_buf;
2161 			q = i * bytes_per_sample + (VipsPel *) buf;
2162 			for( j = 0; j < pels_per_strip; j++ ) {
2163 				for( k = 0; k < bytes_per_sample; k++ )
2164 					q[k] = p[k];
2165 
2166 				p += bytes_per_sample;
2167 				q += bytes_per_sample * samples_per_pixel;
2168 			}
2169 		}
2170 	}
2171 	else {
2172 		if( rtiff_strip_read( rtiff, strip, buf ) )
2173 			return( -1 );
2174 	}
2175 
2176 	return( 0 );
2177 }
2178 
2179 static int
rtiff_stripwise_generate(VipsRegion * or,void * seq,void * a,void * b,gboolean * stop)2180 rtiff_stripwise_generate( VipsRegion *or,
2181 	void *seq, void *a, void *b, gboolean *stop )
2182 {
2183 	VipsImage *out = or->im;
2184 	Rtiff *rtiff = (Rtiff *) a;
2185 	int read_height = rtiff->header.read_height;
2186 	int page_height = rtiff->header.height;
2187 	tsize_t scanline_size = rtiff->header.scanline_size;
2188         VipsRect *r = &or->valid;
2189 
2190 	int y;
2191 
2192 #ifdef DEBUG_VERBOSE
2193 	printf( "rtiff_stripwise_generate: top = %d, height = %d\n",
2194 		r->top, r->height );
2195 	printf( "rtiff_stripwise_generate: y_top = %d\n", rtiff->y_pos );
2196 #endif /*DEBUG_VERBOSE*/
2197 
2198 	/* We're inside a tilecache where tiles are the full image width, so
2199 	 * this should always be true.
2200 	 */
2201 	g_assert( r->left == 0 );
2202 	g_assert( r->width == or->im->Xsize );
2203 	g_assert( VIPS_RECT_BOTTOM( r ) <= or->im->Ysize );
2204 
2205 	/* If we're reading more than one page, tiles won't fall on strip
2206 	 * boundaries.
2207 	 */
2208 
2209 	/* Tiles should always be a strip in height, unless it's the final
2210 	 * strip in the image.
2211 	 */
2212 	g_assert( r->height ==
2213 		VIPS_MIN( read_height, or->im->Ysize - r->top ) );
2214 
2215 	/* And check that y_pos is correct. It should be, since we are inside
2216 	 * a vips_sequential().
2217 	 */
2218 	if( r->top != rtiff->y_pos ) {
2219 		vips_error( "tiff2vips",
2220 			_( "out of order read -- at line %d, "
2221 			"but line %d requested" ), rtiff->y_pos, r->top );
2222 		return( -1 );
2223 	}
2224 
2225 	VIPS_GATE_START( "rtiff_stripwise_generate: work" );
2226 
2227 	y = 0;
2228 	while( y < r->height ) {
2229 		/* page_no is within this toilet roll image, not tiff
2230 		 * file page number ... add the number of the start
2231 		 * page to get that.
2232 		 */
2233 		int page_no = (r->top + y) / page_height;
2234 		int y_page = (r->top + y) % page_height;
2235 
2236 		/* Strip number.
2237 		 */
2238 		tstrip_t strip_no = y_page / read_height;
2239 
2240 		VipsRect image, page, strip, hit;
2241 
2242 		/* Our four (including the output region) rects, all in
2243 		 * output image coordinates.
2244 		 */
2245 		image.left = 0;
2246 		image.top = 0;
2247 		image.width = out->Xsize;
2248 		image.height = out->Ysize;
2249 
2250 		page.left = 0;
2251 		page.top = page_height * ((r->top + y) / page_height);
2252 		page.width = out->Xsize;
2253 		page.height = page_height;
2254 
2255 		strip.left = 0;
2256 		strip.top = page.top + strip_no * read_height;
2257 		strip.width = out->Xsize;
2258 		strip.height = read_height;
2259 
2260 		/* Clip strip against page and image ... the final strip will
2261 		 * be smaller.
2262 		 */
2263 		vips_rect_intersectrect( &strip, &image, &strip );
2264 		vips_rect_intersectrect( &strip, &page, &strip );
2265 
2266 		/* Now the bit that overlaps with the region we are filling.
2267 		 */
2268 		vips_rect_intersectrect( &strip, r, &hit );
2269 
2270 		g_assert( hit.height > 0 );
2271 
2272 		if( rtiff_set_page( rtiff, rtiff->page + page_no ) ) {
2273 			VIPS_GATE_STOP( "rtiff_stripwise_generate: work" );
2274 			return( -1 );
2275 		}
2276 
2277 		/* Read directly into the image if we can. Otherwise, we must
2278 		 * read to a temp buffer then unpack into the image.
2279 		 *
2280 		 * We need to read via a buffer if we need to reformat pixels,
2281 		 * or if this strip is not aligned on a tile boundary.
2282 		 */
2283 		if( rtiff->memcpy &&
2284 			hit.top == strip.top &&
2285 			hit.height == strip.height ) {
2286 			if( rtiff_strip_read_interleaved( rtiff, strip_no,
2287 				VIPS_REGION_ADDR( or, 0, r->top + y ) ) ) {
2288 				VIPS_GATE_STOP(
2289 					"rtiff_stripwise_generate: work" );
2290 				return( -1 );
2291 			}
2292 		}
2293 		else {
2294 			VipsPel *p;
2295 			VipsPel *q;
2296 			int z;
2297 
2298 			/* Read and interleave the entire strip.
2299 			 */
2300 			if( rtiff_strip_read_interleaved( rtiff, strip_no,
2301 				rtiff->contig_buf ) ) {
2302 				VIPS_GATE_STOP(
2303 					"rtiff_stripwise_generate: work" );
2304 				return( -1 );
2305 			}
2306 
2307 			/* Do any repacking to generate pixels in vips layout.
2308 			 */
2309 			p = (VipsPel *) rtiff->contig_buf +
2310 				(hit.top - strip.top) * scanline_size;
2311 			q = VIPS_REGION_ADDR( or, 0, r->top + y );
2312 			for( z = 0; z < hit.height; z++ ) {
2313 				rtiff->sfn( rtiff,
2314 					q, p, or->im->Xsize, rtiff->client );
2315 
2316 				p += scanline_size;
2317 				q += VIPS_REGION_LSKIP( or );
2318 			}
2319 		}
2320 
2321 		y += hit.height;
2322 		rtiff->y_pos += hit.height;
2323 	}
2324 
2325 	VIPS_GATE_STOP( "rtiff_stripwise_generate: work" );
2326 
2327 	return( 0 );
2328 }
2329 
2330 /* Stripwise reading.
2331  *
2332  * We could potentially read strips in any order, but this would give
2333  * catastrophic performance for operations like 90 degress rotate on a
2334  * large image. Only offer sequential read.
2335  */
2336 static int
rtiff_read_stripwise(Rtiff * rtiff,VipsImage * out)2337 rtiff_read_stripwise( Rtiff *rtiff, VipsImage *out )
2338 {
2339 	VipsImage **t = (VipsImage **)
2340 		vips_object_local_array( VIPS_OBJECT( out ), 4 );
2341 
2342 	VipsImage *in;
2343 
2344 #ifdef DEBUG
2345 	printf( "tiff2vips: rtiff_read_stripwise\n" );
2346 #endif /*DEBUG*/
2347 
2348 	t[0] = vips_image_new();
2349 	if( rtiff_set_header( rtiff, t[0] ) )
2350 		return( -1 );
2351 
2352         vips_image_pipelinev( t[0], VIPS_DEMAND_STYLE_THINSTRIP, NULL );
2353 
2354 	/* Double check: in memcpy mode, the vips linesize should exactly
2355 	 * match the tiff line size.
2356 	 */
2357 	if( rtiff->memcpy ) {
2358 		size_t vips_line_size;
2359 
2360 		/* Lines are smaller in plane-separated mode.
2361 		 */
2362 		if( rtiff->header.separate )
2363 			vips_line_size = VIPS_IMAGE_SIZEOF_ELEMENT( t[0] ) *
2364 				t[0]->Xsize;
2365 		else
2366 			vips_line_size = VIPS_IMAGE_SIZEOF_LINE( t[0] );
2367 
2368 		if( vips_line_size != rtiff->header.scanline_size ) {
2369 			vips_error( "tiff2vips",
2370 				"%s", _( "unsupported tiff image type" ) );
2371 			return( -1 );
2372 		}
2373 	}
2374 
2375 	/* If we have separate image planes, we must read to a plane buffer,
2376 	 * then interleave to the output.
2377 	 *
2378 	 * We don't need a separate buffer per thread since the _generate()
2379 	 * function runs inside the cache lock.
2380 	 */
2381 	if( rtiff->header.separate ) {
2382 		if( !(rtiff->plane_buf = vips_malloc( VIPS_OBJECT( out ),
2383 			rtiff->header.read_size )) )
2384 			return( -1 );
2385 	}
2386 
2387 	/* If we need to manipulate pixels, we must read to an interleaved
2388 	 * plane buffer before repacking to the output.
2389 	 *
2390 	 * If we are doing a multi-page read, we need a strip buffer, since
2391 	 * strips may not be aligned on tile boundaries.
2392 	 *
2393 	 * We don't need a separate buffer per thread since the _generate()
2394 	 * function runs inside the cache lock.
2395 	 */
2396 	if( !rtiff->memcpy ||
2397 		rtiff->n > 1 ) {
2398 		tsize_t size;
2399 
2400 		size = rtiff->header.read_size;
2401 		if( rtiff->header.separate )
2402 			size *= rtiff->header.samples_per_pixel;
2403 
2404 		if( !(rtiff->contig_buf =
2405 			vips_malloc( VIPS_OBJECT( out ), size )) )
2406 			return( -1 );
2407 	}
2408 
2409 	/* rows_per_strip can be very large if this is a separate plane image,
2410 	 * beware.
2411 	 */
2412 	if(
2413 		vips_image_generate( t[0],
2414 			NULL, rtiff_stripwise_generate, NULL,
2415 			rtiff, NULL ) ||
2416 		vips_sequential( t[0], &t[1],
2417 			"tile_height", rtiff->header.read_height,
2418 			NULL ) ||
2419 		rtiff_unpremultiply( rtiff, t[1], &t[2] ) )
2420 		return( -1 );
2421 	in = t[2];
2422 
2423 	/* Only do this if we have to.
2424 	 */
2425 	if( rtiff->autorotate &&
2426 		vips_image_get_orientation( in ) != 1 ) {
2427 		if( vips_autorot( in, &t[3], NULL ) )
2428 			return( -1 );
2429 		in = t[3];
2430 	}
2431 
2432 	if( vips_image_write( in, out ) )
2433 		return( -1 );
2434 
2435 	return( 0 );
2436 }
2437 
2438 /* Load from a tiff dir into one of our tiff header structs.
2439  */
2440 static int
rtiff_header_read(Rtiff * rtiff,RtiffHeader * header)2441 rtiff_header_read( Rtiff *rtiff, RtiffHeader *header )
2442 {
2443 	int i;
2444 	guint16 extra_samples_count;
2445 	guint16 *extra_samples_types;
2446 	guint16 subifd_count;
2447 	toff_t *subifd_offsets;
2448 	char *image_description;
2449 
2450 	if( !tfget32( rtiff->tiff, TIFFTAG_IMAGEWIDTH,
2451 			&header->width ) ||
2452 		!tfget32( rtiff->tiff, TIFFTAG_IMAGELENGTH,
2453 			&header->height ) ||
2454 		!tfget16( rtiff->tiff, TIFFTAG_SAMPLESPERPIXEL,
2455 			&header->samples_per_pixel ) ||
2456 		!tfget16( rtiff->tiff, TIFFTAG_BITSPERSAMPLE,
2457 			&header->bits_per_sample ) ||
2458 		!tfget16( rtiff->tiff, TIFFTAG_PHOTOMETRIC,
2459 			&header->photometric_interpretation ) ||
2460 		!tfget16( rtiff->tiff, TIFFTAG_INKSET,
2461 			&header->inkset ) )
2462 		return( -1 );
2463 
2464 	TIFFGetFieldDefaulted( rtiff->tiff,
2465 		TIFFTAG_COMPRESSION, &header->compression );
2466 
2467 	/* One of the types we decompress?
2468 	 */
2469 	for( i = 0; i < VIPS_NUMBER( rtiff_we_decompress ); i++ )
2470 		if( header->compression == rtiff_we_decompress[i] ) {
2471 #ifdef DEBUG
2472 			printf( "rtiff_header_read: "
2473 				"compression %d handled by us\n",
2474 				header->compression );
2475 #endif /*DEBUG*/
2476 			header->we_decompress = TRUE;
2477 			break;
2478 		}
2479 
2480 	/* We must set this here since it'll change the value of scanline_size.
2481 	 */
2482 	rtiff_set_decode_format( rtiff );
2483 
2484 	/* Request YCbCr expansion. libtiff complains if you do this for
2485 	 * non-jpg images. We must set this here since it changes the result
2486 	 * of scanline_size.
2487 	 */
2488 	if( header->compression != COMPRESSION_JPEG &&
2489 		header->photometric_interpretation == PHOTOMETRIC_YCBCR ) {
2490 		/* We rely on the jpg decompressor to upsample chroma
2491 		 * subsampled images. If there is chroma subsampling but
2492 		 * no jpg compression, we have to give up.
2493 		 *
2494 		 * tiffcp fails for images like this too.
2495 		 */
2496                 guint16 hsub, vsub;
2497 
2498                 TIFFGetFieldDefaulted( rtiff->tiff,
2499 			TIFFTAG_YCBCRSUBSAMPLING, &hsub, &vsub );
2500                 if( hsub != 1 ||
2501 			vsub != 1 ) {
2502 			vips_error( "tiff2vips",
2503 				"%s", _( "subsampled images not supported" ) );
2504 			return( -1 );
2505                 }
2506         }
2507 
2508 	if( header->photometric_interpretation == PHOTOMETRIC_LOGLUV ) {
2509 		if( header->compression != COMPRESSION_SGILOG &&
2510 			header->compression != COMPRESSION_SGILOG24 ) {
2511 			vips_error( "tiff2vips",
2512 				"%s", _( "not SGI-compressed LOGLUV" ) );
2513 			return( -1 );
2514 		}
2515 	}
2516 
2517 	/* For logluv, the calibration factor to get to absolute luminance.
2518 	 */
2519 	if( !TIFFGetField( rtiff->tiff, TIFFTAG_STONITS, &header->stonits ) )
2520 		header->stonits = 1.0;
2521 
2522 	/* Arbitrary sanity-checking limits.
2523 	 */
2524 	if( header->width <= 0 ||
2525 		header->width >= VIPS_MAX_COORD ||
2526 		header->height <= 0 ||
2527 		header->height >= VIPS_MAX_COORD ) {
2528 		vips_error( "tiff2vips",
2529 			"%s", _( "width/height out of range" ) );
2530 		return( -1 );
2531 	}
2532 
2533 	if( header->samples_per_pixel <= 0 ||
2534 		header->samples_per_pixel > 10000 ||
2535 		header->bits_per_sample <= 0 ||
2536 		header->bits_per_sample > 32 ) {
2537 		vips_error( "tiff2vips",
2538 			"%s", _( "samples out of range" ) );
2539 		return( -1 );
2540 	}
2541 
2542 	header->sample_format = get_sample_format( rtiff->tiff );
2543 	header->orientation = get_orientation( rtiff->tiff );
2544 
2545 	header->separate = FALSE;
2546 	if( tfexists( rtiff->tiff, TIFFTAG_PLANARCONFIG ) ) {
2547 		int v;
2548 
2549 		if( !tfget16( rtiff->tiff, TIFFTAG_PLANARCONFIG, &v ) )
2550 			return( -1 );
2551 		if( v == PLANARCONFIG_SEPARATE )
2552 			header->separate = TRUE;
2553 	}
2554 
2555 	/* TIFFGetField needs a guint16 to write count to.
2556 	 */
2557 	if( TIFFGetField( rtiff->tiff, TIFFTAG_SUBIFD,
2558 		&subifd_count, &subifd_offsets ) )
2559 		header->subifd_count = subifd_count;
2560 
2561 	/* IMAGEDESCRIPTION often has useful metadata. libtiff makes sure
2562 	 * that data is null-terminated and contains no embedded null
2563 	 * characters.
2564 	 */
2565 	if( TIFFGetField( rtiff->tiff,
2566 		TIFFTAG_IMAGEDESCRIPTION, &image_description ) )
2567 		header->image_description =
2568 			vips_strdup( VIPS_OBJECT( rtiff->out ),
2569 				image_description );
2570 
2571 	/* Tiles and strip images have slightly different fields.
2572 	 */
2573 	header->tiled = TIFFIsTiled( rtiff->tiff );
2574 
2575 #ifdef DEBUG
2576 	printf( "rtiff_header_read: header.width = %d\n",
2577 		header->width );
2578 	printf( "rtiff_header_read: header.height = %d\n",
2579 		header->height );
2580 	printf( "rtiff_header_read: header.samples_per_pixel = %d\n",
2581 		header->samples_per_pixel );
2582 	printf( "rtiff_header_read: header.bits_per_sample = %d\n",
2583 		header->bits_per_sample );
2584 	printf( "rtiff_header_read: header.sample_format = %d\n",
2585 		header->sample_format );
2586 	printf( "rtiff_header_read: header.orientation = %d\n",
2587 		header->orientation );
2588 	printf( "rtiff_header_read: header.tiled = %d\n",
2589 		header->tiled );
2590 #endif /*DEBUG*/
2591 
2592 	if( header->tiled ) {
2593 		if( !tfget32( rtiff->tiff,
2594 			TIFFTAG_TILEWIDTH, &header->tile_width ) ||
2595 			!tfget32( rtiff->tiff,
2596 				TIFFTAG_TILELENGTH, &header->tile_height ) )
2597 			return( -1 );
2598 
2599 #ifdef DEBUG
2600 		printf( "rtiff_header_read: header.tile_width = %d\n",
2601 			header->tile_width );
2602 		printf( "rtiff_header_read: header.tile_height = %d\n",
2603 			header->tile_height );
2604 #endif /*DEBUG*/
2605 
2606 		/* Arbitrary sanity-checking limits.
2607 		 */
2608 		if( header->tile_width <= 0 ||
2609 			header->tile_width > 10000 ||
2610 			header->tile_height <= 0 ||
2611 			header->tile_height > 10000 ) {
2612 			vips_error( "tiff2vips",
2613 				"%s", _( "tile size out of range" ) );
2614 			return( -1 );
2615 		}
2616 
2617 		header->tile_size = TIFFTileSize( rtiff->tiff );
2618 		header->tile_row_size = TIFFTileRowSize( rtiff->tiff );
2619 
2620 #ifdef DEBUG
2621 		printf( "rtiff_header_read: header.tile_size = %zd\n",
2622 			header->tile_size );
2623 		printf( "rtiff_header_read: header.tile_row_size = %zd\n",
2624 			header->tile_row_size );
2625 #endif /*DEBUG*/
2626 
2627 		/* Fuzzed TIFFs can give crazy values for tile_size. Sanity
2628 		 * check at 100mb per tile.
2629 		 */
2630 		if( header->tile_size <= 0 ||
2631 			header->tile_size > 100 * 1000 * 1000 ||
2632 			header->tile_row_size <= 0 ||
2633 			header->tile_row_size > 100 * 1000 * 1000 ) {
2634 			vips_error( "tiff2vips",
2635 				"%s", _( "tile size out of range" ) );
2636 			return( -1 );
2637 		}
2638 
2639 		/* Stop some compiler warnings.
2640 		 */
2641 		header->rows_per_strip = 0;
2642 		header->strip_size = 0;
2643 		header->number_of_strips = 0;
2644 		header->read_height = 0;
2645 		header->read_size = 0;
2646 	}
2647 	else {
2648 		if( !tfget32( rtiff->tiff,
2649 			TIFFTAG_ROWSPERSTRIP, &header->rows_per_strip ) )
2650 			return( -1 );
2651 		header->strip_size = TIFFStripSize( rtiff->tiff );
2652 		header->scanline_size = TIFFScanlineSize( rtiff->tiff );
2653 		header->number_of_strips = TIFFNumberOfStrips( rtiff->tiff );
2654 
2655 #ifdef DEBUG
2656 		printf( "rtiff_header_read: header.rows_per_strip = %d\n",
2657 			header->rows_per_strip );
2658 		printf( "rtiff_header_read: header.strip_size = %zd\n",
2659 			header->strip_size );
2660 		printf( "rtiff_header_read: header.scanline_size = %zd\n",
2661 			header->scanline_size );
2662 		printf( "rtiff_header_read: header.number_of_strips = %d\n",
2663 			header->number_of_strips );
2664 #endif /*DEBUG*/
2665 
2666 		/* libtiff has two strip-wise readers. TIFFReadEncodedStrip()
2667 		 * decompresses an entire strip to memory. It's fast, but it
2668 		 * will need a lot of ram if the strip is large.
2669 		 * TIFFReadScanline() reads a single scanline. It's slower, but
2670 		 * will save a lot of memory if strips are large.
2671 		 *
2672 		 * If this image has a strip size of over 128 lines, fall back
2673 		 * to TIFFReadScanline(), otherwise use TIFFReadEncodedStrip().
2674 		 *
2675 		 * Don't do this in plane-separate mode. TIFFReadScanline() is
2676 		 * too fiddly to use in this case.
2677 		 *
2678 		 * Don't try scanline reading for YCbCr images.
2679 		 * TIFFScanlineSize() will not work in this case due to
2680 		 * chroma subsampling.
2681 		 */
2682 		if( header->rows_per_strip > 128 &&
2683 			!header->separate &&
2684 			header->photometric_interpretation !=
2685 				PHOTOMETRIC_YCBCR ) {
2686 			header->read_scanlinewise = TRUE;
2687 			header->read_height = 1;
2688 			header->read_size = rtiff->header.scanline_size;
2689 		}
2690 		else {
2691 			header->read_scanlinewise = FALSE;
2692 
2693 			/* rows_per_strip can be 2 ** 32 - 1, meaning the
2694 			 * whole image. Clip this down to height to avoid
2695 			 * confusing vips.
2696 			 *
2697 			 * And it musn't be zero.
2698 			 */
2699 			header->read_height = VIPS_CLIP( 1,
2700 				header->rows_per_strip, header->height );
2701 			header->read_size = header->strip_size;
2702 		}
2703 
2704 #ifdef DEBUG
2705 		printf( "rtiff_header_read: header.read_scanlinewise = %d\n",
2706 			header->read_scanlinewise );
2707 		printf( "rtiff_header_read: header.read_height = %d\n",
2708 			header->read_height );
2709 		printf( "rtiff_header_read: header.read_size = %zd\n",
2710 			header->read_size );
2711 #endif /*DEBUG*/
2712 
2713 		/* Stop some compiler warnings.
2714 		 */
2715 		header->tile_width = 0;
2716 		header->tile_height = 0;
2717 		header->tile_size = 0;
2718 		header->tile_row_size = 0;
2719 	}
2720 
2721 	TIFFGetFieldDefaulted( rtiff->tiff, TIFFTAG_EXTRASAMPLES,
2722 		&extra_samples_count, &extra_samples_types );
2723 
2724 	header->alpha_band = -1;
2725 	if( extra_samples_count > 0 ) {
2726 		/* There must be exactly one band which is
2727 		 * EXTRASAMPLE_ASSOCALPHA. Note which one it is so we can
2728 		 * unpremultiply with the right channel.
2729 		 */
2730 		int i;
2731 
2732 		for( i = 0; i < extra_samples_count; i++ )
2733 			if( extra_samples_types[i] == EXTRASAMPLE_ASSOCALPHA ) {
2734 				if( header->alpha_band != -1 )
2735 					g_warning( "%s", _( "more than one "
2736 						"alpha -- ignoring" ) );
2737 
2738 				header->alpha_band = header->samples_per_pixel -
2739 					extra_samples_count + i;
2740 			}
2741 	}
2742 
2743 	return( 0 );
2744 }
2745 
2746 static int
rtiff_header_equal(RtiffHeader * h1,RtiffHeader * h2)2747 rtiff_header_equal( RtiffHeader *h1, RtiffHeader *h2 )
2748 {
2749 	if( h1->width != h2->width ||
2750 		h1->height != h2->height ||
2751 		h1->samples_per_pixel != h2->samples_per_pixel ||
2752 		h1->bits_per_sample != h2->bits_per_sample ||
2753 		h1->photometric_interpretation !=
2754 			h2->photometric_interpretation ||
2755 		h1->sample_format != h2->sample_format ||
2756 		h1->compression != h2->compression ||
2757 		h1->separate != h2->separate ||
2758 		h1->tiled != h2->tiled ||
2759 		h1->orientation != h2->orientation )
2760 		return( 0 );
2761 
2762 	if( h1->tiled ) {
2763 		if( h1->tile_width != h2->tile_width ||
2764 			h1->tile_height != h2->tile_height )
2765 			return( 0 );
2766 	}
2767 	else {
2768 		if( h1->read_height != h2->read_height ||
2769 			h1->read_size != h2->read_size ||
2770 			h1->number_of_strips != h2->number_of_strips )
2771 			return( 0 );
2772 	}
2773 
2774 	return( 1 );
2775 }
2776 
2777 static int
rtiff_header_read_all(Rtiff * rtiff)2778 rtiff_header_read_all( Rtiff *rtiff )
2779 {
2780 #ifdef DEBUG
2781 	printf( "rtiff_header_read_all: "
2782 		"reading header for page %d ...\n", rtiff->page );
2783 #endif /*DEBUG*/
2784 
2785 	/* -1 means "to the end".
2786 	 *
2787 	 * We must count pages before selecting and reading the header of the
2788 	 * first page, since scanning a TIFF can change the value of libtiff's
2789 	 * internal header fields in strange ways, especially if the TIFF is
2790 	 * corrupt.
2791 	 */
2792 	rtiff->n_pages = rtiff_n_pages( rtiff );
2793 
2794 	if( rtiff_set_page( rtiff, rtiff->page ) ||
2795 		rtiff_header_read( rtiff, &rtiff->header ) )
2796 		return( -1 );
2797 
2798 	/* If we're to read many pages, verify that they are all identical.
2799 	 */
2800 	if( rtiff->n == -1 )
2801 		rtiff->n = rtiff->n_pages - rtiff->page;
2802 	if( rtiff->n > 1 ) {
2803 		int i;
2804 
2805 		for( i = 1; i < rtiff->n; i++ ) {
2806 			RtiffHeader header;
2807 
2808 #ifdef DEBUG
2809 			printf( "rtiff_header_read_all: "
2810 				"verifying header for page %d ...\n",
2811 				rtiff->page + i );
2812 #endif /*DEBUG*/
2813 
2814 			if( rtiff_set_page( rtiff, rtiff->page + i ) ||
2815 				rtiff_header_read( rtiff, &header ) )
2816 				return( -1 );
2817 
2818 			if( !rtiff_header_equal( &rtiff->header, &header ) ) {
2819 				vips_error( "tiff2vips",
2820 					_( "page %d differs from page %d" ),
2821 					rtiff->page + i, rtiff->page );
2822 				return( -1 );
2823 			}
2824 		}
2825 
2826 		/* Make sure the next set_page() will reread the directory.
2827 		 */
2828 		rtiff->current_page = -1;
2829 	}
2830 
2831 	return( 0 );
2832 }
2833 
2834 typedef gboolean (*TiffPropertyFn)( TIFF *tif );
2835 
2836 static gboolean
vips__testtiff_source(VipsSource * source,TiffPropertyFn fn)2837 vips__testtiff_source( VipsSource *source, TiffPropertyFn fn )
2838 {
2839 	TIFF *tif;
2840 	gboolean property;
2841 
2842 	vips__tiff_init();
2843 
2844 	if( !(tif = vips__tiff_openin_source( source )) ) {
2845 		vips_error_clear();
2846 		return( FALSE );
2847 	}
2848 
2849 	property = fn ? fn( tif ) : TRUE;
2850 
2851 	TIFFClose( tif );
2852 
2853 	return( property );
2854 }
2855 
2856 gboolean
vips__istiff_source(VipsSource * source)2857 vips__istiff_source( VipsSource *source )
2858 {
2859 	return( vips__testtiff_source( source, NULL ) );
2860 }
2861 
2862 gboolean
vips__istifftiled_source(VipsSource * source)2863 vips__istifftiled_source( VipsSource *source )
2864 {
2865 	return( vips__testtiff_source( source, TIFFIsTiled ) );
2866 }
2867 
2868 int
vips__tiff_read_header_source(VipsSource * source,VipsImage * out,int page,int n,gboolean autorotate,int subifd,VipsFailOn fail_on)2869 vips__tiff_read_header_source( VipsSource *source, VipsImage *out,
2870 	int page, int n, gboolean autorotate, int subifd, VipsFailOn fail_on )
2871 {
2872 	Rtiff *rtiff;
2873 
2874 	vips__tiff_init();
2875 
2876 	if( !(rtiff = rtiff_new( source, out,
2877 		page, n, autorotate, subifd, fail_on )) ||
2878 		rtiff_header_read_all( rtiff ) )
2879 		return( -1 );
2880 
2881 	if( rtiff_set_header( rtiff, out ) )
2882 		return( -1 );
2883 
2884 	if( rtiff->autorotate &&
2885 		vips_image_get_orientation_swap( out ) ) {
2886 		VIPS_SWAP( int, out->Xsize, out->Ysize );
2887 		vips_autorot_remove_angle( out );
2888 	}
2889 
2890 	/* We never call vips_source_decode() since we need to be able to
2891 	 * seek() the whole way through the file. Just minimise instead,
2892 	 */
2893 	vips_source_minimise( source );
2894 
2895 	return( 0 );
2896 }
2897 
2898 int
vips__tiff_read_source(VipsSource * source,VipsImage * out,int page,int n,gboolean autorotate,int subifd,VipsFailOn fail_on)2899 vips__tiff_read_source( VipsSource *source, VipsImage *out,
2900 	int page, int n, gboolean autorotate, int subifd, VipsFailOn fail_on )
2901 {
2902 	Rtiff *rtiff;
2903 
2904 #ifdef DEBUG
2905 	printf( "tiff2vips: libtiff version is \"%s\"\n", TIFFGetVersion() );
2906 #endif /*DEBUG*/
2907 
2908 	vips__tiff_init();
2909 
2910 	if( !(rtiff = rtiff_new( source, out,
2911 		page, n, autorotate, subifd, fail_on )) ||
2912 		rtiff_header_read_all( rtiff ) )
2913 		return( -1 );
2914 
2915 	if( rtiff->header.tiled ) {
2916 		if( rtiff_read_tilewise( rtiff, out ) )
2917 			return( -1 );
2918 	}
2919 	else {
2920 		if( rtiff_read_stripwise( rtiff, out ) )
2921 			return( -1 );
2922 	}
2923 
2924 	/* We never call vips_source_decode() since we need to be able to
2925 	 * seek() the whole way through the file. Just minimise instead,
2926 	 */
2927 	vips_source_minimise( source );
2928 
2929 	return( 0 );
2930 }
2931 
2932 #endif /*HAVE_TIFF*/
2933