1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
10 // Intel License Agreement
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
19 // * Redistribution's of source code must retain the above copyright notice,
20 // this list of conditions and the following disclaimer.
22 // * Redistribution's in binary form must reproduce the above copyright notice,
23 // this list of conditions and the following disclaimer in the documentation
24 // and/or other materials provided with the distribution.
26 // * The name of Intel Corporation may not be used to endorse or promote products
27 // derived from this software without specific prior written permission.
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
42 /****************************************************************************************\
43 A part of the file implements TIFF reader on base of libtiff library
44 (see otherlibs/_graphics/readme.txt for copyright notice)
45 \****************************************************************************************/
48 #include "grfmt_tiff.h"
50 static const char fmtSignTiffII[] = "II\x2a\x00";
51 static const char fmtSignTiffMM[] = "MM\x00\x2a";
53 GrFmtTiff::GrFmtTiff()
57 m_description = "TIFF Files (*.tiff;*.tif)";
60 GrFmtTiff::~GrFmtTiff()
64 bool GrFmtTiff::CheckSignature( const char* signature )
66 return memcmp( signature, fmtSignTiffII, 4 ) == 0 ||
67 memcmp( signature, fmtSignTiffMM, 4 ) == 0;
71 GrFmtReader* GrFmtTiff::NewReader( const char* filename )
73 return new GrFmtTiffReader( filename );
77 GrFmtWriter* GrFmtTiff::NewWriter( const char* filename )
79 return new GrFmtTiffWriter( filename );
88 static int grfmt_tiff_err_handler_init = 0;
90 static void GrFmtSilentTIFFErrorHandler( const char*, const char*, va_list ) {}
92 GrFmtTiffReader::GrFmtTiffReader( const char* filename ) : GrFmtReader( filename )
96 if( !grfmt_tiff_err_handler_init )
98 grfmt_tiff_err_handler_init = 1;
100 TIFFSetErrorHandler( GrFmtSilentTIFFErrorHandler );
101 TIFFSetWarningHandler( GrFmtSilentTIFFErrorHandler );
106 GrFmtTiffReader::~GrFmtTiffReader()
111 void GrFmtTiffReader::Close()
115 TIFF* tif = (TIFF*)m_tif;
122 bool GrFmtTiffReader::CheckFormat( const char* signature )
124 return memcmp( signature, fmtSignTiffII, 4 ) == 0 ||
125 memcmp( signature, fmtSignTiffMM, 4 ) == 0;
129 bool GrFmtTiffReader::ReadHeader()
135 TIFF* tif = TIFFOpen( m_filename, "r" );
139 int width = 0, height = 0, photometric = 0, compression = 0;
142 if( TIFFRGBAImageOK( tif, errmsg ) &&
143 TIFFGetField( tif, TIFFTAG_IMAGEWIDTH, &width ) &&
144 TIFFGetField( tif, TIFFTAG_IMAGELENGTH, &height ) &&
145 TIFFGetField( tif, TIFFTAG_PHOTOMETRIC, &photometric ) &&
146 (!TIFFGetField( tif, TIFFTAG_COMPRESSION, &compression ) ||
147 (compression != COMPRESSION_LZW &&
148 compression != COMPRESSION_OJPEG)))
152 m_iscolor = photometric > 1;
165 bool GrFmtTiffReader::ReadData( uchar* data, int step, int color )
170 color = color > 0 || (color < 0 && m_iscolor);
172 if( m_tif && m_width && m_height )
174 TIFF* tif = (TIFF*)m_tif;
175 int tile_width0 = m_width, tile_height0 = 0;
177 int is_tiled = TIFFIsTiled(tif);
180 TIFFGetField( tif, TIFFTAG_ROWSPERSTRIP, &tile_height0 ) ||
182 TIFFGetField( tif, TIFFTAG_TILEWIDTH, &tile_width0 ) &&
183 TIFFGetField( tif, TIFFTAG_TILELENGTH, &tile_height0 ))
185 if( tile_width0 <= 0 )
186 tile_width0 = m_width;
188 if( tile_height0 <= 0 )
189 tile_height0 = m_height;
191 buffer = new uchar[tile_height0*tile_width0*4];
193 for( y = 0; y < m_height; y += tile_height0, data += step*tile_height0 )
195 int tile_height = tile_height0;
197 if( y + tile_height > m_height )
198 tile_height = m_height - y;
200 for( x = 0; x < m_width; x += tile_width0 )
202 int tile_width = tile_width0, ok;
204 if( x + tile_width > m_width )
205 tile_width = m_width - x;
208 ok = TIFFReadRGBAStrip( tif, y, (uint32*)buffer );
210 ok = TIFFReadRGBATile( tif, x, y, (uint32*)buffer );
215 for( i = 0; i < tile_height; i++ )
217 icvCvt_BGRA2BGR_8u_C4C3R( buffer + i*tile_width*4, 0,
218 data + x*3 + step*(tile_height - i - 1), 0,
219 cvSize(tile_width,1), 2 );
221 icvCvt_BGRA2Gray_8u_C4C1R( buffer + i*tile_width*4, 0,
222 data + x + step*(tile_height - i - 1), 0,
223 cvSize(tile_width,1), 2 );
241 static const int tiffMask[] = { 0xff, 0xff, 0xffffffff, 0xffff, 0xffffffff };
243 /************************ TIFF reader *****************************/
245 GrFmtTiffReader::GrFmtTiffReader( const char* filename ) : GrFmtReader( filename )
250 m_max_pal_length = 0;
255 GrFmtTiffReader::~GrFmtTiffReader()
260 delete[] m_temp_palette;
263 void GrFmtTiffReader::Close()
269 bool GrFmtTiffReader::CheckFormat( const char* signature )
271 return memcmp( signature, fmtSignTiffII, 4 ) == 0 ||
272 memcmp( signature, fmtSignTiffMM, 4 ) == 0;
276 int GrFmtTiffReader::GetWordEx()
278 int val = m_strm.GetWord();
279 if( m_byteorder == TIFF_ORDER_MM )
280 val = ((val)>>8)|(((val)&0xff)<<8);
285 int GrFmtTiffReader::GetDWordEx()
287 int val = m_strm.GetDWord();
288 if( m_byteorder == TIFF_ORDER_MM )
294 int GrFmtTiffReader::ReadTable( int offset, int count,
295 TiffFieldType fieldType,
296 int*& array, int& arraysize )
301 return RBS_BAD_HEADER;
303 if( fieldType != TIFF_TYPE_SHORT &&
304 fieldType != TIFF_TYPE_LONG &&
305 fieldType != TIFF_TYPE_BYTE )
306 return RBS_BAD_HEADER;
308 if( count > arraysize )
311 arraysize = arraysize*3/2;
312 if( arraysize < count )
314 array = new int[arraysize];
319 int pos = m_strm.GetPos();
320 m_strm.SetPos( offset );
322 if( fieldType == TIFF_TYPE_LONG )
324 if( m_byteorder == TIFF_ORDER_MM )
325 for( i = 0; i < count; i++ )
326 array[i] = ((RMByteStream&)m_strm).GetDWord();
328 for( i = 0; i < count; i++ )
329 array[i] = ((RLByteStream&)m_strm).GetDWord();
331 else if( fieldType == TIFF_TYPE_SHORT )
333 if( m_byteorder == TIFF_ORDER_MM )
334 for( i = 0; i < count; i++ )
335 array[i] = ((RMByteStream&)m_strm).GetWord();
337 for( i = 0; i < count; i++ )
338 array[i] = ((RLByteStream&)m_strm).GetWord();
340 else // fieldType == TIFF_TYPE_BYTE
341 for( i = 0; i < count; i++ )
342 array[i] = m_strm.GetByte();
348 assert( (offset & ~tiffMask[fieldType]) == 0 );
356 bool GrFmtTiffReader::ReadHeader()
359 int photometric = -1;
363 const int MAX_CHANNELS = 4;
364 int bpp_arr[MAX_CHANNELS];
366 assert( strlen(m_filename) != 0 );
367 if( !m_strm.Open( m_filename )) return false;
373 m_compression = TIFF_UNCOMP;
374 m_rows_per_strip = -1;
377 if( setjmp( m_strm.JmpBuf()) == 0 )
379 m_byteorder = (TiffByteOrder)m_strm.GetWord();
381 int header_offset = GetDWordEx();
383 m_strm.SetPos( header_offset );
385 // read the first tag directory
386 int i, j, count = GetWordEx();
388 for( i = 0; i < count; i++ )
391 TiffTag tag = (TiffTag)GetWordEx();
392 TiffFieldType fieldType = (TiffFieldType)GetWordEx();
393 int count = GetDWordEx();
394 int value = GetDWordEx();
397 if( m_byteorder == TIFF_ORDER_MM )
399 if( fieldType == TIFF_TYPE_SHORT )
400 value = (unsigned)value >> 16;
401 else if( fieldType == TIFF_TYPE_BYTE )
402 value = (unsigned)value >> 24;
405 value &= tiffMask[fieldType];
414 case TIFF_TAG_HEIGHT:
418 case TIFF_TAG_BITS_PER_SAMPLE:
420 int* bpp_arr_ref = bpp_arr;
422 if( count > MAX_CHANNELS )
425 if( ReadTable( value, count, fieldType, bpp_arr_ref, count ) < 0 )
428 for( j = 1; j < count; j++ )
430 if( bpp_arr[j] != bpp_arr[0] )
439 case TIFF_TAG_COMPRESSION:
440 m_compression = (TiffCompression)value;
441 if( m_compression != TIFF_UNCOMP &&
442 m_compression != TIFF_HUFFMAN &&
443 m_compression != TIFF_PACKBITS )
447 case TIFF_TAG_PHOTOMETRIC:
449 if( (unsigned)photometric > 3 )
453 case TIFF_TAG_STRIP_OFFSETS:
455 if( ReadTable( value, count, fieldType, m_offsets, m_maxoffsets ) < 0 )
459 case TIFF_TAG_SAMPLES_PER_PIXEL:
461 if( channels != 1 && channels != 3 && channels != 4 )
465 case TIFF_TAG_ROWS_PER_STRIP:
466 m_rows_per_strip = value;
469 case TIFF_TAG_PLANAR_CONFIG:
471 int planar_config = value;
472 if( planar_config != 1 )
477 case TIFF_TAG_COLOR_MAP:
478 if( fieldType != TIFF_TYPE_SHORT || count < 2 )
480 if( ReadTable( value, count, fieldType,
481 m_temp_palette, m_max_pal_length ) < 0 )
483 pal_length = count / 3;
484 if( pal_length > 256 )
486 for( i = 0; i < pal_length; i++ )
488 m_palette[i].r = (uchar)(m_temp_palette[i] >> 8);
489 m_palette[i].g = (uchar)(m_temp_palette[i + pal_length] >> 8);
490 m_palette[i].b = (uchar)(m_temp_palette[i + pal_length*2] >> 8);
493 case TIFF_TAG_STRIP_COUNTS:
498 if( m_strips == 1 && m_rows_per_strip == -1 )
499 m_rows_per_strip = m_height;
501 if( m_width > 0 && m_height > 0 && m_strips > 0 &&
502 (m_height + m_rows_per_strip - 1)/m_rows_per_strip == m_strips )
507 if( photometric == 0 || photometric == 1 && channels == 1 )
509 FillGrayPalette( m_palette, m_bpp, photometric == 0 );
516 if( (photometric == 0 || photometric == 1 ||
517 photometric == 3 && pal_length == (1 << m_bpp)) &&
518 m_compression != TIFF_HUFFMAN && channels == 1 )
522 FillGrayPalette( m_palette, m_bpp, photometric == 0 );
527 m_iscolor = IsColorPalette( m_palette, m_bpp );
531 else if( photometric == 2 && pal_length < 0 &&
532 (channels == 3 || channels == 4) &&
533 m_compression == TIFF_UNCOMP )
551 m_width = m_height = -1;
559 bool GrFmtTiffReader::ReadData( uchar* data, int step, int color )
561 const int buffer_size = 1 << 12;
562 uchar buffer[buffer_size];
563 uchar gray_palette[256];
566 int src_pitch = (m_width*m_bpp + 7)/8;
569 if( m_strips < 0 || !m_strm.IsOpened())
572 if( src_pitch+32 > buffer_size )
573 src = new uchar[src_pitch+32];
578 CvtPaletteToGray( m_palette, gray_palette, 1 << m_bpp );
581 if( setjmp( m_strm.JmpBuf()) == 0 )
583 for( int s = 0; s < m_strips; s++ )
585 int y_limit = m_rows_per_strip;
588 if( y_limit > m_height ) y_limit = m_height;
590 m_strm.SetPos( m_offsets[s] );
592 if( m_compression == TIFF_UNCOMP )
594 for( ; y < y_limit; y++, data += step )
596 m_strm.GetBytes( src, src_pitch );
601 FillColorRow1( data, src, m_width, m_palette );
604 FillColorRow4( data, src, m_width, m_palette );
607 FillColorRow8( data, src, m_width, m_palette );
610 icvCvt_RGB2BGR_8u_C3R( src, 0, data, 0, cvSize(m_width,1) );
613 icvCvt_BGRA2BGR_8u_C4C3R( src, 0, data, 0, cvSize(m_width,1), 2 );
617 goto bad_decoding_end;
623 FillGrayRow1( data, src, m_width, gray_palette );
626 FillGrayRow4( data, src, m_width, gray_palette );
629 FillGrayRow8( data, src, m_width, gray_palette );
632 icvCvt_BGR2Gray_8u_C3C1R( src, 0, data, 0, cvSize(m_width,1), 2 );
635 icvCvt_BGRA2Gray_8u_C4C1R( src, 0, data, 0, cvSize(m_width,1), 2 );
639 goto bad_decoding_end;
655 if( src != buffer ) delete[] src;
661 //////////////////////////////////////////////////////////////////////////////////////////
663 GrFmtTiffWriter::GrFmtTiffWriter( const char* filename ) : GrFmtWriter( filename )
667 GrFmtTiffWriter::~GrFmtTiffWriter()
671 void GrFmtTiffWriter::WriteTag( TiffTag tag, TiffFieldType fieldType,
672 int count, int value )
674 m_strm.PutWord( tag );
675 m_strm.PutWord( fieldType );
676 m_strm.PutDWord( count );
677 m_strm.PutDWord( value );
681 bool GrFmtTiffWriter::WriteImage( const uchar* data, int step,
682 int width, int height, int /*depth*/, int channels )
685 int fileStep = width*channels;
687 assert( data && width > 0 && height > 0 && step >= fileStep);
689 if( m_strm.Open( m_filename ) )
691 int rowsPerStrip = (1 << 13)/fileStep;
693 if( rowsPerStrip < 1 )
696 if( rowsPerStrip > height )
697 rowsPerStrip = height;
699 int i, stripCount = (height + rowsPerStrip - 1) / rowsPerStrip;
700 /*#if defined _DEBUG || !defined WIN32
701 int uncompressedRowSize = rowsPerStrip * fileStep;
703 int directoryOffset = 0;
705 int* stripOffsets = new int[stripCount];
706 short* stripCounts = new short[stripCount];
707 uchar* buffer = new uchar[fileStep + 32];
708 int stripOffsetsOffset = 0;
709 int stripCountsOffset = 0;
710 int bitsPerSample = 8; // TODO support 16 bit
713 m_strm.PutBytes( fmtSignTiffII, 4 );
714 m_strm.PutDWord( directoryOffset );
716 // write an image data first (the most reasonable way
717 // for compressed images)
718 for( i = 0; i < stripCount; i++ )
720 int limit = y + rowsPerStrip;
725 stripOffsets[i] = m_strm.GetPos();
727 for( ; y < limit; y++, data += step )
730 icvCvt_BGR2RGB_8u_C3R( data, 0, buffer, 0, cvSize(width,1) );
731 else if( channels == 4 )
732 icvCvt_BGRA2RGBA_8u_C4R( data, 0, buffer, 0, cvSize(width,1) );
734 m_strm.PutBytes( channels > 1 ? buffer : data, fileStep );
737 stripCounts[i] = (short)(m_strm.GetPos() - stripOffsets[i]);
738 /*assert( stripCounts[i] == uncompressedRowSize ||
739 stripCounts[i] < uncompressedRowSize &&
740 i == stripCount - 1);*/
745 stripOffsetsOffset = m_strm.GetPos();
746 for( i = 0; i < stripCount; i++ )
747 m_strm.PutDWord( stripOffsets[i] );
749 stripCountsOffset = m_strm.GetPos();
750 for( i = 0; i < stripCount; i++ )
751 m_strm.PutWord( stripCounts[i] );
753 else if(stripCount == 2)
755 stripOffsetsOffset = m_strm.GetPos();
756 for (i = 0; i < stripCount; i++)
758 m_strm.PutDWord (stripOffsets [i]);
760 stripCountsOffset = stripCounts [0] + (stripCounts [1] << 16);
764 stripOffsetsOffset = stripOffsets[0];
765 stripCountsOffset = stripCounts[0];
770 bitsPerSample = m_strm.GetPos();
778 directoryOffset = m_strm.GetPos();
783 /* warning: specification 5.0 of Tiff want to have tags in
784 ascending order. This is a non-fatal error, but this cause
785 warning with some tools. So, keep this in ascending order */
787 WriteTag( TIFF_TAG_WIDTH, TIFF_TYPE_LONG, 1, width );
788 WriteTag( TIFF_TAG_HEIGHT, TIFF_TYPE_LONG, 1, height );
789 WriteTag( TIFF_TAG_BITS_PER_SAMPLE,
790 TIFF_TYPE_SHORT, channels, bitsPerSample );
791 WriteTag( TIFF_TAG_COMPRESSION, TIFF_TYPE_LONG, 1, TIFF_UNCOMP );
792 WriteTag( TIFF_TAG_PHOTOMETRIC, TIFF_TYPE_SHORT, 1, channels > 1 ? 2 : 1 );
794 WriteTag( TIFF_TAG_STRIP_OFFSETS, TIFF_TYPE_LONG,
795 stripCount, stripOffsetsOffset );
797 WriteTag( TIFF_TAG_SAMPLES_PER_PIXEL, TIFF_TYPE_SHORT, 1, channels );
798 WriteTag( TIFF_TAG_ROWS_PER_STRIP, TIFF_TYPE_LONG, 1, rowsPerStrip );
800 WriteTag( TIFF_TAG_STRIP_COUNTS,
801 stripCount > 1 ? TIFF_TYPE_SHORT : TIFF_TYPE_LONG,
802 stripCount, stripCountsOffset );
807 // write directory offset
808 FILE* f = fopen( m_filename, "r+b" );
809 buffer[0] = (uchar)directoryOffset;
810 buffer[1] = (uchar)(directoryOffset >> 8);
811 buffer[2] = (uchar)(directoryOffset >> 16);
812 buffer[3] = (uchar)(directoryOffset >> 24);
814 fseek( f, 4, SEEK_SET );
815 fwrite( buffer, 1, 4, f );
818 delete[] stripOffsets;
819 delete[] stripCounts;