another DMC build fix
[wxWidgets.git] / src / common / imagtiff.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/imagtiff.cpp
3 // Purpose: wxImage TIFF handler
4 // Author: Robert Roebling
5 // RCS-ID: $Id$
6 // Copyright: (c) Robert Roebling
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
12
13 #ifdef __BORLANDC__
14 #pragma hdrstop
15 #endif
16
17 #if wxUSE_IMAGE && wxUSE_LIBTIFF
18
19 #include "wx/imagtiff.h"
20
21 #ifndef WX_PRECOMP
22 #include "wx/log.h"
23 #include "wx/app.h"
24 #include "wx/intl.h"
25 #include "wx/bitmap.h"
26 #include "wx/module.h"
27 #endif
28
29 extern "C"
30 {
31 #ifdef __DMC__
32 #include "tif_config.h"
33 #endif
34 #include "tiff.h"
35 #include "tiffio.h"
36 }
37 #include "wx/filefn.h"
38 #include "wx/wfstream.h"
39
40 #ifndef TIFFLINKAGEMODE
41 #if defined(__WATCOMC__) && defined(__WXMGL__)
42 #define TIFFLINKAGEMODE cdecl
43 #else
44 #define TIFFLINKAGEMODE LINKAGEMODE
45 #endif
46 #endif
47
48 //-----------------------------------------------------------------------------
49 // wxTIFFHandler
50 //-----------------------------------------------------------------------------
51
52 IMPLEMENT_DYNAMIC_CLASS(wxTIFFHandler,wxImageHandler)
53
54 #if wxUSE_STREAMS
55
56 // helper to translate our, possibly 64 bit, wxFileOffset to TIFF, always 32
57 // bit, toff_t
58 static toff_t wxFileOffsetToTIFF(wxFileOffset ofs)
59 {
60 if ( ofs == wxInvalidOffset )
61 return (toff_t)-1;
62
63 toff_t tofs = wx_truncate_cast(toff_t, ofs);
64 wxCHECK_MSG( (wxFileOffset)tofs == ofs, (toff_t)-1,
65 _T("TIFF library doesn't support large files") );
66
67 return tofs;
68 }
69
70 // another helper to convert standard seek mode to our
71 static wxSeekMode wxSeekModeFromTIFF(int whence)
72 {
73 switch ( whence )
74 {
75 case SEEK_SET:
76 return wxFromStart;
77
78 case SEEK_CUR:
79 return wxFromCurrent;
80
81 case SEEK_END:
82 return wxFromEnd;
83
84 default:
85 return wxFromCurrent;
86 }
87 }
88
89 extern "C"
90 {
91
92 tsize_t TIFFLINKAGEMODE
93 wxTIFFNullProc(thandle_t WXUNUSED(handle),
94 tdata_t WXUNUSED(buf),
95 tsize_t WXUNUSED(size))
96 {
97 return (tsize_t) -1;
98 }
99
100 tsize_t TIFFLINKAGEMODE
101 wxTIFFReadProc(thandle_t handle, tdata_t buf, tsize_t size)
102 {
103 wxInputStream *stream = (wxInputStream*) handle;
104 stream->Read( (void*) buf, (size_t) size );
105 return wx_truncate_cast(tsize_t, stream->LastRead());
106 }
107
108 tsize_t TIFFLINKAGEMODE
109 wxTIFFWriteProc(thandle_t handle, tdata_t buf, tsize_t size)
110 {
111 wxOutputStream *stream = (wxOutputStream*) handle;
112 stream->Write( (void*) buf, (size_t) size );
113 return wx_truncate_cast(tsize_t, stream->LastWrite());
114 }
115
116 toff_t TIFFLINKAGEMODE
117 wxTIFFSeekIProc(thandle_t handle, toff_t off, int whence)
118 {
119 wxInputStream *stream = (wxInputStream*) handle;
120
121 return wxFileOffsetToTIFF(stream->SeekI((wxFileOffset)off,
122 wxSeekModeFromTIFF(whence)));
123 }
124
125 toff_t TIFFLINKAGEMODE
126 wxTIFFSeekOProc(thandle_t handle, toff_t off, int whence)
127 {
128 wxOutputStream *stream = (wxOutputStream*) handle;
129
130 return wxFileOffsetToTIFF(stream->SeekO((wxFileOffset)off,
131 wxSeekModeFromTIFF(whence)));
132 }
133
134 int TIFFLINKAGEMODE
135 wxTIFFCloseIProc(thandle_t WXUNUSED(handle))
136 {
137 // there is no need to close the input stream
138 return 0;
139 }
140
141 int TIFFLINKAGEMODE
142 wxTIFFCloseOProc(thandle_t handle)
143 {
144 wxOutputStream *stream = (wxOutputStream*) handle;
145
146 return stream->Close() ? 0 : -1;
147 }
148
149 toff_t TIFFLINKAGEMODE
150 wxTIFFSizeProc(thandle_t handle)
151 {
152 wxStreamBase *stream = (wxStreamBase*) handle;
153 return (toff_t) stream->GetSize();
154 }
155
156 int TIFFLINKAGEMODE
157 wxTIFFMapProc(thandle_t WXUNUSED(handle),
158 tdata_t* WXUNUSED(pbase),
159 toff_t* WXUNUSED(psize))
160 {
161 return 0;
162 }
163
164 void TIFFLINKAGEMODE
165 wxTIFFUnmapProc(thandle_t WXUNUSED(handle),
166 tdata_t WXUNUSED(base),
167 toff_t WXUNUSED(size))
168 {
169 }
170
171 static void
172 TIFFwxWarningHandler(const char* module,
173 const char* WXUNUSED_IN_UNICODE(fmt),
174 va_list WXUNUSED_IN_UNICODE(ap))
175 {
176 if (module != NULL)
177 wxLogWarning(_("tiff module: %s"), wxString::FromAscii(module).c_str());
178
179 // FIXME: this is not terrible informative but better than crashing!
180 #if wxUSE_UNICODE
181 wxLogWarning(_("TIFF library warning."));
182 #else
183 wxVLogWarning(fmt, ap);
184 #endif
185 }
186
187 static void
188 TIFFwxErrorHandler(const char* module,
189 const char* WXUNUSED_IN_UNICODE(fmt),
190 va_list WXUNUSED_IN_UNICODE(ap))
191 {
192 if (module != NULL)
193 wxLogError(_("tiff module: %s"), wxString::FromAscii(module).c_str());
194
195 // FIXME: as above
196 #if wxUSE_UNICODE
197 wxLogError(_("TIFF library error."));
198 #else
199 wxVLogError(fmt, ap);
200 #endif
201 }
202
203 } // extern "C"
204
205 TIFF*
206 TIFFwxOpen(wxInputStream &stream, const char* name, const char* mode)
207 {
208 TIFF* tif = TIFFClientOpen(name, mode,
209 (thandle_t) &stream,
210 wxTIFFReadProc, wxTIFFNullProc,
211 wxTIFFSeekIProc, wxTIFFCloseIProc, wxTIFFSizeProc,
212 wxTIFFMapProc, wxTIFFUnmapProc);
213
214 return tif;
215 }
216
217 TIFF*
218 TIFFwxOpen(wxOutputStream &stream, const char* name, const char* mode)
219 {
220 TIFF* tif = TIFFClientOpen(name, mode,
221 (thandle_t) &stream,
222 wxTIFFNullProc, wxTIFFWriteProc,
223 wxTIFFSeekOProc, wxTIFFCloseOProc, wxTIFFSizeProc,
224 wxTIFFMapProc, wxTIFFUnmapProc);
225
226 return tif;
227 }
228
229 wxTIFFHandler::wxTIFFHandler()
230 {
231 m_name = wxT("TIFF file");
232 m_extension = wxT("tif");
233 m_type = wxBITMAP_TYPE_TIF;
234 m_mime = wxT("image/tiff");
235 TIFFSetWarningHandler((TIFFErrorHandler) TIFFwxWarningHandler);
236 TIFFSetErrorHandler((TIFFErrorHandler) TIFFwxErrorHandler);
237 }
238
239 bool wxTIFFHandler::LoadFile( wxImage *image, wxInputStream& stream, bool verbose, int index )
240 {
241 if (index == -1)
242 index = 0;
243
244 image->Destroy();
245
246 TIFF *tif = TIFFwxOpen( stream, "image", "r" );
247
248 if (!tif)
249 {
250 if (verbose)
251 wxLogError( _("TIFF: Error loading image.") );
252
253 return false;
254 }
255
256 if (!TIFFSetDirectory( tif, (tdir_t)index ))
257 {
258 if (verbose)
259 wxLogError( _("Invalid TIFF image index.") );
260
261 TIFFClose( tif );
262
263 return false;
264 }
265
266 uint32 w, h;
267 uint32 npixels;
268 uint32 *raster;
269
270 TIFFGetField( tif, TIFFTAG_IMAGEWIDTH, &w );
271 TIFFGetField( tif, TIFFTAG_IMAGELENGTH, &h );
272
273 uint16 extraSamples;
274 uint16* samplesInfo;
275 TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
276 &extraSamples, &samplesInfo);
277 const bool hasAlpha = (extraSamples == 1 &&
278 (samplesInfo[0] == EXTRASAMPLE_ASSOCALPHA ||
279 samplesInfo[0] == EXTRASAMPLE_UNASSALPHA));
280
281 npixels = w * h;
282
283 raster = (uint32*) _TIFFmalloc( npixels * sizeof(uint32) );
284
285 if (!raster)
286 {
287 if (verbose)
288 wxLogError( _("TIFF: Couldn't allocate memory.") );
289
290 TIFFClose( tif );
291
292 return false;
293 }
294
295 image->Create( (int)w, (int)h );
296 if (!image->Ok())
297 {
298 if (verbose)
299 wxLogError( _("TIFF: Couldn't allocate memory.") );
300
301 _TIFFfree( raster );
302 TIFFClose( tif );
303
304 return false;
305 }
306
307 if ( hasAlpha )
308 image->SetAlpha();
309
310 if (!TIFFReadRGBAImage( tif, w, h, raster, 0 ))
311 {
312 if (verbose)
313 wxLogError( _("TIFF: Error reading image.") );
314
315 _TIFFfree( raster );
316 image->Destroy();
317 TIFFClose( tif );
318
319 return false;
320 }
321
322 unsigned char *ptr = image->GetData();
323 ptr += w*3*(h-1);
324
325 unsigned char *alpha = hasAlpha ? image->GetAlpha() : NULL;
326 if ( hasAlpha )
327 alpha += w*(h-1);
328
329 uint32 pos = 0;
330
331 for (uint32 i = 0; i < h; i++)
332 {
333 for (uint32 j = 0; j < w; j++)
334 {
335 *(ptr++) = (unsigned char)TIFFGetR(raster[pos]);
336 *(ptr++) = (unsigned char)TIFFGetG(raster[pos]);
337 *(ptr++) = (unsigned char)TIFFGetB(raster[pos]);
338 if ( hasAlpha )
339 *(alpha++) = (unsigned char)TIFFGetA(raster[pos]);
340
341 pos++;
342 }
343
344 // subtract line we just added plus one line:
345 ptr -= 2*w*3;
346 if ( hasAlpha )
347 alpha -= 2*w;
348 }
349
350 // set the image resolution if it's available
351 uint16 tiffRes;
352 if ( TIFFGetField(tif, TIFFTAG_RESOLUTIONUNIT, &tiffRes) )
353 {
354 wxImageResolution res;
355 switch ( tiffRes )
356 {
357 default:
358 wxLogWarning(_("Unknown TIFF resolution unit %d ignored"),
359 tiffRes);
360 // fall through
361
362 case RESUNIT_NONE:
363 res = wxIMAGE_RESOLUTION_NONE;
364 break;
365
366 case RESUNIT_INCH:
367 res = wxIMAGE_RESOLUTION_INCHES;
368 break;
369
370 case RESUNIT_CENTIMETER:
371 res = wxIMAGE_RESOLUTION_CM;
372 break;
373 }
374
375 if ( res != wxIMAGE_RESOLUTION_NONE )
376 {
377 float xres, yres;
378 if ( TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres) )
379 image->SetOption(wxIMAGE_OPTION_RESOLUTIONX, wxRound(xres));
380
381 if ( TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres) )
382 image->SetOption(wxIMAGE_OPTION_RESOLUTIONY, wxRound(yres));
383 }
384 }
385
386
387 _TIFFfree( raster );
388
389 TIFFClose( tif );
390
391 return true;
392 }
393
394 int wxTIFFHandler::GetImageCount( wxInputStream& stream )
395 {
396 TIFF *tif = TIFFwxOpen( stream, "image", "r" );
397
398 if (!tif)
399 return 0;
400
401 int dircount = 0; // according to the libtiff docs, dircount should be set to 1 here???
402 do {
403 dircount++;
404 } while (TIFFReadDirectory(tif));
405
406 TIFFClose( tif );
407
408 return dircount;
409 }
410
411 bool wxTIFFHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
412 {
413 TIFF *tif = TIFFwxOpen( stream, "image", "w" );
414
415 if (!tif)
416 {
417 if (verbose)
418 wxLogError( _("TIFF: Error saving image.") );
419
420 return false;
421 }
422
423 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
424 TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, (uint32)image->GetWidth());
425 TIFFSetField(tif, TIFFTAG_IMAGELENGTH, (uint32)image->GetHeight());
426 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
427 TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
428
429 // save the image resolution if we have it
430 int xres, yres;
431 const wxImageResolution res = GetResolutionFromOptions(*image, &xres, &yres);
432 uint16 tiffRes;
433 switch ( res )
434 {
435 default:
436 wxFAIL_MSG( _T("unknown image resolution units") );
437 // fall through
438
439 case wxIMAGE_RESOLUTION_NONE:
440 tiffRes = RESUNIT_NONE;
441 break;
442
443 case wxIMAGE_RESOLUTION_INCHES:
444 tiffRes = RESUNIT_INCH;
445 break;
446
447 case wxIMAGE_RESOLUTION_CM:
448 tiffRes = RESUNIT_CENTIMETER;
449 break;
450 }
451
452 if ( tiffRes != RESUNIT_NONE )
453 {
454 TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, tiffRes);
455 TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)xres);
456 TIFFSetField(tif, TIFFTAG_YRESOLUTION, (float)yres);
457 }
458
459
460 int spp = image->GetOptionInt(wxIMAGE_OPTION_SAMPLESPERPIXEL);
461 if ( !spp )
462 spp = 3;
463
464 int bpp = image->GetOptionInt(wxIMAGE_OPTION_BITSPERSAMPLE);
465 if ( !bpp )
466 bpp = 8;
467
468 int compression = image->GetOptionInt(wxIMAGE_OPTION_COMPRESSION);
469 if ( !compression )
470 {
471 // we can't use COMPRESSION_LZW because current version of libtiff
472 // doesn't implement it ("no longer implemented due to Unisys patent
473 // enforcement") and other compression methods are lossy so we
474 // shouldn't use them by default -- and the only remaining one is none
475 compression = COMPRESSION_NONE;
476 }
477
478 TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, spp);
479 TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bpp);
480 TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, spp*bpp == 1 ? PHOTOMETRIC_MINISBLACK
481 : PHOTOMETRIC_RGB);
482 TIFFSetField(tif, TIFFTAG_COMPRESSION, compression);
483
484 // scanlinesize if determined by spp and bpp
485 tsize_t linebytes = (tsize_t)image->GetWidth() * spp * bpp / 8;
486
487 if ( (image->GetWidth() % 8 > 0) && (spp * bpp < 8) )
488 linebytes+=1;
489
490 unsigned char *buf;
491
492 if (TIFFScanlineSize(tif) > linebytes || (spp * bpp < 24))
493 {
494 buf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif));
495 if (!buf)
496 {
497 if (verbose)
498 wxLogError( _("TIFF: Couldn't allocate memory.") );
499
500 TIFFClose( tif );
501
502 return false;
503 }
504 }
505 else
506 {
507 buf = NULL;
508 }
509
510 TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP,TIFFDefaultStripSize(tif, (uint32) -1));
511
512 unsigned char *ptr = image->GetData();
513 for ( int row = 0; row < image->GetHeight(); row++ )
514 {
515 if ( buf )
516 {
517 if ( spp * bpp > 1 )
518 {
519 // color image
520 memcpy(buf, ptr, image->GetWidth());
521 }
522 else // black and white image
523 {
524 for ( int column = 0; column < linebytes; column++ )
525 {
526 uint8 reverse = 0;
527 for ( int bp = 0; bp < 8; bp++ )
528 {
529 if ( ptr[column*24 + bp*3] > 0 )
530 {
531 // check only red as this is sufficient
532 reverse = (uint8)(reverse | 128 >> bp);
533 }
534 }
535
536 buf[column] = reverse;
537 }
538 }
539 }
540
541 if ( TIFFWriteScanline(tif, buf ? buf : ptr, (uint32)row, 0) < 0 )
542 {
543 if (verbose)
544 wxLogError( _("TIFF: Error writing image.") );
545
546 TIFFClose( tif );
547 if (buf)
548 _TIFFfree(buf);
549
550 return false;
551 }
552
553 ptr += image->GetWidth()*3;
554 }
555
556 (void) TIFFClose(tif);
557
558 if (buf)
559 _TIFFfree(buf);
560
561 return true;
562 }
563
564 bool wxTIFFHandler::DoCanRead( wxInputStream& stream )
565 {
566 unsigned char hdr[2];
567
568 if ( !stream.Read(&hdr[0], WXSIZEOF(hdr)) )
569 return false;
570
571 return (hdr[0] == 'I' && hdr[1] == 'I') ||
572 (hdr[0] == 'M' && hdr[1] == 'M');
573 }
574
575 #endif // wxUSE_STREAMS
576
577 #endif // wxUSE_LIBTIFF