msvcrt: Implemented _ltoa_s.
[wine] / dlls / windowscodecs / tiffformat.c
1 /*
2  * Copyright 2010 Vincent Povirk for CodeWeavers
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 #include "config.h"
20 #include "wine/port.h"
21
22 #include <stdarg.h>
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26 #ifdef HAVE_TIFFIO_H
27 #include <tiffio.h>
28 #endif
29
30 #define COBJMACROS
31
32 #include "windef.h"
33 #include "winbase.h"
34 #include "objbase.h"
35 #include "wincodec.h"
36
37 #include "wincodecs_private.h"
38
39 #include "wine/debug.h"
40 #include "wine/library.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(wincodecs);
43
44 #ifdef SONAME_LIBTIFF
45
46 static CRITICAL_SECTION init_tiff_cs;
47 static CRITICAL_SECTION_DEBUG init_tiff_cs_debug =
48 {
49     0, 0, &init_tiff_cs,
50     { &init_tiff_cs_debug.ProcessLocksList,
51       &init_tiff_cs_debug.ProcessLocksList },
52     0, 0, { (DWORD_PTR)(__FILE__ ": init_tiff_cs") }
53 };
54 static CRITICAL_SECTION init_tiff_cs = { &init_tiff_cs_debug, -1, 0, 0, 0, 0 };
55
56 static void *libtiff_handle;
57 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
58 MAKE_FUNCPTR(TIFFClientOpen);
59 MAKE_FUNCPTR(TIFFClose);
60 MAKE_FUNCPTR(TIFFCurrentDirectory);
61 MAKE_FUNCPTR(TIFFGetField);
62 MAKE_FUNCPTR(TIFFIsByteSwapped);
63 MAKE_FUNCPTR(TIFFReadDirectory);
64 MAKE_FUNCPTR(TIFFReadEncodedStrip);
65 MAKE_FUNCPTR(TIFFSetDirectory);
66 #undef MAKE_FUNCPTR
67
68 static void *load_libtiff(void)
69 {
70     void *result;
71
72     EnterCriticalSection(&init_tiff_cs);
73
74     if (!libtiff_handle &&
75         (libtiff_handle = wine_dlopen(SONAME_LIBTIFF, RTLD_NOW, NULL, 0)) != NULL)
76     {
77
78 #define LOAD_FUNCPTR(f) \
79     if((p##f = wine_dlsym(libtiff_handle, #f, NULL, 0)) == NULL) { \
80         ERR("failed to load symbol %s\n", #f); \
81         libtiff_handle = NULL; \
82         LeaveCriticalSection(&init_tiff_cs); \
83         return NULL; \
84     }
85         LOAD_FUNCPTR(TIFFClientOpen);
86         LOAD_FUNCPTR(TIFFClose);
87         LOAD_FUNCPTR(TIFFCurrentDirectory);
88         LOAD_FUNCPTR(TIFFGetField);
89         LOAD_FUNCPTR(TIFFIsByteSwapped);
90         LOAD_FUNCPTR(TIFFReadDirectory);
91         LOAD_FUNCPTR(TIFFReadEncodedStrip);
92         LOAD_FUNCPTR(TIFFSetDirectory);
93 #undef LOAD_FUNCPTR
94
95     }
96
97     result = libtiff_handle;
98
99     LeaveCriticalSection(&init_tiff_cs);
100     return result;
101 }
102
103 static tsize_t tiff_stream_read(thandle_t client_data, tdata_t data, tsize_t size)
104 {
105     IStream *stream = (IStream*)client_data;
106     ULONG bytes_read;
107     HRESULT hr;
108
109     hr = IStream_Read(stream, data, size, &bytes_read);
110     if (FAILED(hr)) bytes_read = 0;
111     return bytes_read;
112 }
113
114 static tsize_t tiff_stream_write(thandle_t client_data, tdata_t data, tsize_t size)
115 {
116     IStream *stream = (IStream*)client_data;
117     ULONG bytes_written;
118     HRESULT hr;
119
120     hr = IStream_Write(stream, data, size, &bytes_written);
121     if (FAILED(hr)) bytes_written = 0;
122     return bytes_written;
123 }
124
125 static toff_t tiff_stream_seek(thandle_t client_data, toff_t offset, int whence)
126 {
127     IStream *stream = (IStream*)client_data;
128     LARGE_INTEGER move;
129     DWORD origin;
130     ULARGE_INTEGER new_position;
131     HRESULT hr;
132
133     move.QuadPart = offset;
134     switch (whence)
135     {
136         case SEEK_SET:
137             origin = STREAM_SEEK_SET;
138             break;
139         case SEEK_CUR:
140             origin = STREAM_SEEK_CUR;
141             break;
142         case SEEK_END:
143             origin = STREAM_SEEK_END;
144             break;
145         default:
146             ERR("unknown whence value %i\n", whence);
147             return -1;
148     }
149
150     hr = IStream_Seek(stream, move, origin, &new_position);
151     if (SUCCEEDED(hr)) return new_position.QuadPart;
152     else return -1;
153 }
154
155 static int tiff_stream_close(thandle_t client_data)
156 {
157     /* Caller is responsible for releasing the stream object. */
158     return 0;
159 }
160
161 static toff_t tiff_stream_size(thandle_t client_data)
162 {
163     IStream *stream = (IStream*)client_data;
164     STATSTG statstg;
165     HRESULT hr;
166
167     hr = IStream_Stat(stream, &statstg, STATFLAG_NONAME);
168
169     if (SUCCEEDED(hr)) return statstg.cbSize.QuadPart;
170     else return -1;
171 }
172
173 static int tiff_stream_map(thandle_t client_data, tdata_t *addr, toff_t *size)
174 {
175     /* Cannot mmap streams */
176     return 0;
177 }
178
179 static void tiff_stream_unmap(thandle_t client_data, tdata_t addr, toff_t size)
180 {
181     /* No need to ever do this, since we can't map things. */
182 }
183
184 static TIFF* tiff_open_stream(IStream *stream, const char *mode)
185 {
186     LARGE_INTEGER zero;
187
188     zero.QuadPart = 0;
189     IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
190
191     return pTIFFClientOpen("<IStream object>", mode, stream, tiff_stream_read,
192         tiff_stream_write, tiff_stream_seek, tiff_stream_close,
193         tiff_stream_size, tiff_stream_map, tiff_stream_unmap);
194 }
195
196 typedef struct {
197     const IWICBitmapDecoderVtbl *lpVtbl;
198     LONG ref;
199     IStream *stream;
200     CRITICAL_SECTION lock; /* Must be held when tiff is used or initiailzed is set */
201     TIFF *tiff;
202     BOOL initialized;
203 } TiffDecoder;
204
205 typedef struct {
206     const WICPixelFormatGUID *format;
207     int bps;
208     int samples;
209     int bpp;
210     int planar;
211     int indexed;
212     int reverse_bgr;
213     int invert_grayscale;
214     UINT width, height;
215     UINT tile_width, tile_height;
216     UINT tile_stride;
217     UINT tile_size;
218 } tiff_decode_info;
219
220 typedef struct {
221     const IWICBitmapFrameDecodeVtbl *lpVtbl;
222     LONG ref;
223     TiffDecoder *parent;
224     UINT index;
225     tiff_decode_info decode_info;
226     INT cached_tile_x, cached_tile_y;
227     BYTE *cached_tile;
228 } TiffFrameDecode;
229
230 static const IWICBitmapFrameDecodeVtbl TiffFrameDecode_Vtbl;
231
232 static HRESULT tiff_get_decode_info(TIFF *tiff, tiff_decode_info *decode_info)
233 {
234     uint16 photometric, bps, samples, planar;
235     uint16 extra_sample_count, *extra_samples;
236     int ret;
237
238     decode_info->indexed = 0;
239     decode_info->reverse_bgr = 0;
240     decode_info->invert_grayscale = 0;
241
242     ret = pTIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric);
243     if (!ret)
244     {
245         WARN("missing PhotometricInterpretation tag\n");
246         return E_FAIL;
247     }
248
249     ret = pTIFFGetField(tiff, TIFFTAG_BITSPERSAMPLE, &bps);
250     if (!ret) bps = 1;
251     decode_info->bps = bps;
252
253     ret = pTIFFGetField(tiff, TIFFTAG_SAMPLESPERPIXEL, &samples);
254     if (!ret) samples = 1;
255     decode_info->samples = samples;
256
257     if (samples == 1)
258         planar = 1;
259     else
260     {
261         ret = pTIFFGetField(tiff, TIFFTAG_PLANARCONFIG, &planar);
262         if (!ret) planar = 1;
263         if (planar != 1)
264         {
265             FIXME("unhandled planar configuration %u\n", planar);
266             return E_FAIL;
267         }
268     }
269     decode_info->planar = planar;
270
271     switch(photometric)
272     {
273     case 0: /* WhiteIsZero */
274         decode_info->invert_grayscale = 1;
275     case 1: /* BlackIsZero */
276         if (samples != 1)
277         {
278             FIXME("unhandled grayscale sample count %u\n", samples);
279             return E_FAIL;
280         }
281
282         decode_info->bpp = bps;
283         switch (bps)
284         {
285         case 1:
286             decode_info->format = &GUID_WICPixelFormatBlackWhite;
287             break;
288         case 4:
289             decode_info->format = &GUID_WICPixelFormat4bppGray;
290             break;
291         case 8:
292             decode_info->format = &GUID_WICPixelFormat8bppGray;
293             break;
294         default:
295             FIXME("unhandled greyscale bit count %u\n", bps);
296             return E_FAIL;
297         }
298         break;
299     case 2: /* RGB */
300         decode_info->bpp = bps * samples;
301
302         if (samples == 4)
303         {
304             ret = pTIFFGetField(tiff, TIFFTAG_EXTRASAMPLES, &extra_sample_count, &extra_samples);
305             if (!ret)
306             {
307                 WARN("Cannot get extra sample type for RGB data, ret=%i count=%i\n", ret, extra_sample_count);
308                 return E_FAIL;
309             }
310         }
311         else if (samples != 3)
312         {
313             FIXME("unhandled RGB sample count %u\n", samples);
314             return E_FAIL;
315         }
316
317         switch(bps)
318         {
319         case 8:
320             decode_info->reverse_bgr = 1;
321             if (samples == 3)
322                 decode_info->format = &GUID_WICPixelFormat24bppBGR;
323             else
324                 switch(extra_samples[0])
325                 {
326                 case 1: /* Associated (pre-multiplied) alpha data */
327                     decode_info->format = &GUID_WICPixelFormat32bppPBGRA;
328                     break;
329                 case 2: /* Unassociated alpha data */
330                     decode_info->format = &GUID_WICPixelFormat32bppBGRA;
331                     break;
332                 default:
333                     FIXME("unhandled extra sample type %i\n", extra_samples[0]);
334                     return E_FAIL;
335                 }
336             break;
337         case 16:
338             if (samples == 3)
339                 decode_info->format = &GUID_WICPixelFormat48bppRGB;
340             else
341                 switch(extra_samples[0])
342                 {
343                 case 1: /* Associated (pre-multiplied) alpha data */
344                     decode_info->format = &GUID_WICPixelFormat64bppPRGBA;
345                     break;
346                 case 2: /* Unassociated alpha data */
347                     decode_info->format = &GUID_WICPixelFormat64bppRGBA;
348                     break;
349                 default:
350                     FIXME("unhandled extra sample type %i\n", extra_samples[0]);
351                     return E_FAIL;
352                 }
353             break;
354         default:
355             FIXME("unhandled RGB bit count %u\n", bps);
356             return E_FAIL;
357         }
358         break;
359     case 3: /* RGB Palette */
360         if (samples != 1)
361         {
362             FIXME("unhandled indexed sample count %u\n", samples);
363             return E_FAIL;
364         }
365
366         decode_info->indexed = 1;
367         decode_info->bpp = bps;
368         switch (bps)
369         {
370         case 4:
371             decode_info->format = &GUID_WICPixelFormat4bppIndexed;
372             break;
373         case 8:
374             decode_info->format = &GUID_WICPixelFormat8bppIndexed;
375             break;
376         default:
377             FIXME("unhandled indexed bit count %u\n", bps);
378             return E_FAIL;
379         }
380         break;
381     case 4: /* Transparency mask */
382     case 5: /* CMYK */
383     case 6: /* YCbCr */
384     case 8: /* CIELab */
385     default:
386         FIXME("unhandled PhotometricInterpretation %u\n", photometric);
387         return E_FAIL;
388     }
389
390     ret = pTIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &decode_info->width);
391     if (!ret)
392     {
393         WARN("missing image width\n");
394         return E_FAIL;
395     }
396
397     ret = pTIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &decode_info->height);
398     if (!ret)
399     {
400         WARN("missing image length\n");
401         return E_FAIL;
402     }
403
404     ret = pTIFFGetField(tiff, TIFFTAG_ROWSPERSTRIP, &decode_info->tile_height);
405     if (ret)
406     {
407         if (decode_info->tile_height > decode_info->height)
408             decode_info->tile_height = decode_info->height;
409         decode_info->tile_width = decode_info->width;
410         decode_info->tile_stride = ((decode_info->bpp * decode_info->tile_width + 7)/8);
411         decode_info->tile_size = decode_info->tile_height * decode_info->tile_stride;
412     }
413     else
414     {
415         /* Probably a tiled image */
416         FIXME("missing RowsPerStrip value\n");
417         return E_FAIL;
418     }
419
420     return S_OK;
421 }
422
423 static HRESULT WINAPI TiffDecoder_QueryInterface(IWICBitmapDecoder *iface, REFIID iid,
424     void **ppv)
425 {
426     TiffDecoder *This = (TiffDecoder*)iface;
427     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
428
429     if (!ppv) return E_INVALIDARG;
430
431     if (IsEqualIID(&IID_IUnknown, iid) || IsEqualIID(&IID_IWICBitmapDecoder, iid))
432     {
433         *ppv = This;
434     }
435     else
436     {
437         *ppv = NULL;
438         return E_NOINTERFACE;
439     }
440
441     IUnknown_AddRef((IUnknown*)*ppv);
442     return S_OK;
443 }
444
445 static ULONG WINAPI TiffDecoder_AddRef(IWICBitmapDecoder *iface)
446 {
447     TiffDecoder *This = (TiffDecoder*)iface;
448     ULONG ref = InterlockedIncrement(&This->ref);
449
450     TRACE("(%p) refcount=%u\n", iface, ref);
451
452     return ref;
453 }
454
455 static ULONG WINAPI TiffDecoder_Release(IWICBitmapDecoder *iface)
456 {
457     TiffDecoder *This = (TiffDecoder*)iface;
458     ULONG ref = InterlockedDecrement(&This->ref);
459
460     TRACE("(%p) refcount=%u\n", iface, ref);
461
462     if (ref == 0)
463     {
464         if (This->tiff) pTIFFClose(This->tiff);
465         if (This->stream) IStream_Release(This->stream);
466         This->lock.DebugInfo->Spare[0] = 0;
467         DeleteCriticalSection(&This->lock);
468         HeapFree(GetProcessHeap(), 0, This);
469     }
470
471     return ref;
472 }
473
474 static HRESULT WINAPI TiffDecoder_QueryCapability(IWICBitmapDecoder *iface, IStream *pIStream,
475     DWORD *pdwCapability)
476 {
477     FIXME("(%p,%p,%p): stub\n", iface, pIStream, pdwCapability);
478     return E_NOTIMPL;
479 }
480
481 static HRESULT WINAPI TiffDecoder_Initialize(IWICBitmapDecoder *iface, IStream *pIStream,
482     WICDecodeOptions cacheOptions)
483 {
484     TiffDecoder *This = (TiffDecoder*)iface;
485     TIFF *tiff;
486     HRESULT hr=S_OK;
487
488     TRACE("(%p,%p,%x): stub\n", iface, pIStream, cacheOptions);
489
490     EnterCriticalSection(&This->lock);
491
492     if (This->initialized)
493     {
494         hr = WINCODEC_ERR_WRONGSTATE;
495         goto exit;
496     }
497
498     tiff = tiff_open_stream(pIStream, "r");
499
500     if (!tiff)
501     {
502         hr = E_FAIL;
503         goto exit;
504     }
505
506     This->tiff = tiff;
507     This->stream = pIStream;
508     IStream_AddRef(pIStream);
509     This->initialized = TRUE;
510
511 exit:
512     LeaveCriticalSection(&This->lock);
513     return hr;
514 }
515
516 static HRESULT WINAPI TiffDecoder_GetContainerFormat(IWICBitmapDecoder *iface,
517     GUID *pguidContainerFormat)
518 {
519     memcpy(pguidContainerFormat, &GUID_ContainerFormatTiff, sizeof(GUID));
520     return S_OK;
521 }
522
523 static HRESULT WINAPI TiffDecoder_GetDecoderInfo(IWICBitmapDecoder *iface,
524     IWICBitmapDecoderInfo **ppIDecoderInfo)
525 {
526     FIXME("(%p,%p): stub\n", iface, ppIDecoderInfo);
527     return E_NOTIMPL;
528 }
529
530 static HRESULT WINAPI TiffDecoder_CopyPalette(IWICBitmapDecoder *iface,
531     IWICPalette *pIPalette)
532 {
533     FIXME("(%p,%p): stub\n", iface, pIPalette);
534     return E_NOTIMPL;
535 }
536
537 static HRESULT WINAPI TiffDecoder_GetMetadataQueryReader(IWICBitmapDecoder *iface,
538     IWICMetadataQueryReader **ppIMetadataQueryReader)
539 {
540     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
541     return E_NOTIMPL;
542 }
543
544 static HRESULT WINAPI TiffDecoder_GetPreview(IWICBitmapDecoder *iface,
545     IWICBitmapSource **ppIBitmapSource)
546 {
547     FIXME("(%p,%p): stub\n", iface, ppIBitmapSource);
548     return E_NOTIMPL;
549 }
550
551 static HRESULT WINAPI TiffDecoder_GetColorContexts(IWICBitmapDecoder *iface,
552     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
553 {
554     FIXME("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);
555     return E_NOTIMPL;
556 }
557
558 static HRESULT WINAPI TiffDecoder_GetThumbnail(IWICBitmapDecoder *iface,
559     IWICBitmapSource **ppIThumbnail)
560 {
561     TRACE("(%p,%p)\n", iface, ppIThumbnail);
562     return WINCODEC_ERR_CODECNOTHUMBNAIL;
563 }
564
565 static HRESULT WINAPI TiffDecoder_GetFrameCount(IWICBitmapDecoder *iface,
566     UINT *pCount)
567 {
568     TiffDecoder *This = (TiffDecoder*)iface;
569
570     if (!This->tiff)
571     {
572         WARN("(%p) <-- WINCODEC_ERR_WRONGSTATE\n", iface);
573         return WINCODEC_ERR_WRONGSTATE;
574     }
575
576     EnterCriticalSection(&This->lock);
577     while (pTIFFReadDirectory(This->tiff)) { }
578     *pCount = pTIFFCurrentDirectory(This->tiff)+1;
579     LeaveCriticalSection(&This->lock);
580
581     TRACE("(%p) <-- %i\n", iface, *pCount);
582
583     return S_OK;
584 }
585
586 static HRESULT WINAPI TiffDecoder_GetFrame(IWICBitmapDecoder *iface,
587     UINT index, IWICBitmapFrameDecode **ppIBitmapFrame)
588 {
589     TiffDecoder *This = (TiffDecoder*)iface;
590     TiffFrameDecode *result;
591     int res;
592     tiff_decode_info decode_info;
593     HRESULT hr;
594
595     TRACE("(%p,%u,%p)\n", iface, index, ppIBitmapFrame);
596
597     if (!This->tiff)
598         return WINCODEC_ERR_WRONGSTATE;
599
600     EnterCriticalSection(&This->lock);
601     res = pTIFFSetDirectory(This->tiff, index);
602     if (!res) hr = E_INVALIDARG;
603     else hr = tiff_get_decode_info(This->tiff, &decode_info);
604     LeaveCriticalSection(&This->lock);
605
606     if (SUCCEEDED(hr))
607     {
608         result = HeapAlloc(GetProcessHeap(), 0, sizeof(TiffFrameDecode));
609
610         if (result)
611         {
612             result->lpVtbl = &TiffFrameDecode_Vtbl;
613             result->ref = 1;
614             result->parent = This;
615             result->index = index;
616             result->decode_info = decode_info;
617             result->cached_tile_x = -1;
618             result->cached_tile = HeapAlloc(GetProcessHeap(), 0, decode_info.tile_size);
619
620             if (result->cached_tile)
621                 *ppIBitmapFrame = (IWICBitmapFrameDecode*)result;
622             else
623             {
624                 hr = E_OUTOFMEMORY;
625                 HeapFree(GetProcessHeap(), 0, result);
626             }
627         }
628         else hr = E_OUTOFMEMORY;
629     }
630
631     if (FAILED(hr)) *ppIBitmapFrame = NULL;
632
633     return hr;
634 }
635
636 static const IWICBitmapDecoderVtbl TiffDecoder_Vtbl = {
637     TiffDecoder_QueryInterface,
638     TiffDecoder_AddRef,
639     TiffDecoder_Release,
640     TiffDecoder_QueryCapability,
641     TiffDecoder_Initialize,
642     TiffDecoder_GetContainerFormat,
643     TiffDecoder_GetDecoderInfo,
644     TiffDecoder_CopyPalette,
645     TiffDecoder_GetMetadataQueryReader,
646     TiffDecoder_GetPreview,
647     TiffDecoder_GetColorContexts,
648     TiffDecoder_GetThumbnail,
649     TiffDecoder_GetFrameCount,
650     TiffDecoder_GetFrame
651 };
652
653 static HRESULT WINAPI TiffFrameDecode_QueryInterface(IWICBitmapFrameDecode *iface, REFIID iid,
654     void **ppv)
655 {
656     TiffFrameDecode *This = (TiffFrameDecode*)iface;
657     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
658
659     if (!ppv) return E_INVALIDARG;
660
661     if (IsEqualIID(&IID_IUnknown, iid) ||
662         IsEqualIID(&IID_IWICBitmapSource, iid) ||
663         IsEqualIID(&IID_IWICBitmapFrameDecode, iid))
664     {
665         *ppv = This;
666     }
667     else
668     {
669         *ppv = NULL;
670         return E_NOINTERFACE;
671     }
672
673     IUnknown_AddRef((IUnknown*)*ppv);
674     return S_OK;
675 }
676
677 static ULONG WINAPI TiffFrameDecode_AddRef(IWICBitmapFrameDecode *iface)
678 {
679     TiffFrameDecode *This = (TiffFrameDecode*)iface;
680     ULONG ref = InterlockedIncrement(&This->ref);
681
682     TRACE("(%p) refcount=%u\n", iface, ref);
683
684     return ref;
685 }
686
687 static ULONG WINAPI TiffFrameDecode_Release(IWICBitmapFrameDecode *iface)
688 {
689     TiffFrameDecode *This = (TiffFrameDecode*)iface;
690     ULONG ref = InterlockedDecrement(&This->ref);
691
692     TRACE("(%p) refcount=%u\n", iface, ref);
693
694     if (ref == 0)
695     {
696         HeapFree(GetProcessHeap(), 0, This->cached_tile);
697         HeapFree(GetProcessHeap(), 0, This);
698     }
699
700     return ref;
701 }
702
703 static HRESULT WINAPI TiffFrameDecode_GetSize(IWICBitmapFrameDecode *iface,
704     UINT *puiWidth, UINT *puiHeight)
705 {
706     TiffFrameDecode *This = (TiffFrameDecode*)iface;
707
708     *puiWidth = This->decode_info.width;
709     *puiHeight = This->decode_info.height;
710
711     TRACE("(%p) <-- %ux%u\n", iface, *puiWidth, *puiHeight);
712
713     return S_OK;
714 }
715
716 static HRESULT WINAPI TiffFrameDecode_GetPixelFormat(IWICBitmapFrameDecode *iface,
717     WICPixelFormatGUID *pPixelFormat)
718 {
719     TiffFrameDecode *This = (TiffFrameDecode*)iface;
720
721     memcpy(pPixelFormat, This->decode_info.format, sizeof(GUID));
722
723     TRACE("(%p) <-- %s\n", This, debugstr_guid(This->decode_info.format));
724
725     return S_OK;
726 }
727
728 static HRESULT WINAPI TiffFrameDecode_GetResolution(IWICBitmapFrameDecode *iface,
729     double *pDpiX, double *pDpiY)
730 {
731     FIXME("(%p,%p,%p)\n", iface, pDpiX, pDpiY);
732     return E_NOTIMPL;
733 }
734
735 static HRESULT WINAPI TiffFrameDecode_CopyPalette(IWICBitmapFrameDecode *iface,
736     IWICPalette *pIPalette)
737 {
738     TiffFrameDecode *This = (TiffFrameDecode*)iface;
739     uint16 *red, *green, *blue;
740     WICColor colors[256];
741     int color_count, ret, i;
742
743     TRACE("(%p,%p)\n", iface, pIPalette);
744
745     color_count = 1<<This->decode_info.bps;
746
747     EnterCriticalSection(&This->parent->lock);
748     ret = pTIFFGetField(This->parent->tiff, TIFFTAG_COLORMAP, &red, &green, &blue);
749     LeaveCriticalSection(&This->parent->lock);
750
751     if (!ret)
752     {
753         WARN("Couldn't read color map\n");
754         return E_FAIL;
755     }
756
757     for (i=0; i<color_count; i++)
758     {
759         colors[i] = 0xff000000 |
760             ((red[i]<<8) & 0xff0000) |
761             (green[i] & 0xff00) |
762             ((blue[i]>>8) & 0xff);
763     }
764
765     return IWICPalette_InitializeCustom(pIPalette, colors, color_count);
766 }
767
768 static HRESULT TiffFrameDecode_ReadTile(TiffFrameDecode *This, UINT tile_x, UINT tile_y)
769 {
770     HRESULT hr=S_OK;
771     tsize_t ret;
772     int swap_bytes;
773
774     swap_bytes = pTIFFIsByteSwapped(This->parent->tiff);
775
776     ret = pTIFFSetDirectory(This->parent->tiff, This->index);
777
778     if (ret == -1)
779         hr = E_FAIL;
780
781     if (hr == S_OK)
782     {
783         ret = pTIFFReadEncodedStrip(This->parent->tiff, tile_y, This->cached_tile, This->decode_info.tile_size);
784
785         if (ret == -1)
786             hr = E_FAIL;
787     }
788
789     if (hr == S_OK && This->decode_info.reverse_bgr)
790     {
791         if (This->decode_info.bps == 8)
792         {
793             UINT i, total_pixels, sample_count;
794             BYTE *pixel, temp;
795
796             total_pixels = This->decode_info.tile_width * This->decode_info.tile_height;
797             pixel = This->cached_tile;
798             sample_count = This->decode_info.samples;
799             for (i=0; i<total_pixels; i++)
800             {
801                 temp = pixel[2];
802                 pixel[2] = pixel[0];
803                 pixel[0] = temp;
804                 pixel += sample_count;
805             }
806         }
807     }
808
809     if (hr == S_OK && swap_bytes && This->decode_info.bps > 8)
810     {
811         UINT row, i, samples_per_row;
812         BYTE *sample, temp;
813
814         samples_per_row = This->decode_info.tile_width * This->decode_info.samples;
815
816         switch(This->decode_info.bps)
817         {
818         case 16:
819             for (row=0; row<This->decode_info.tile_height; row++)
820             {
821                 sample = This->cached_tile + row * This->decode_info.tile_stride;
822                 for (i=0; i<samples_per_row; i++)
823                 {
824                     temp = sample[1];
825                     sample[1] = sample[0];
826                     sample[0] = temp;
827                     sample += 2;
828                 }
829             }
830             break;
831         default:
832             ERR("unhandled bps for byte swap %u\n", This->decode_info.bps);
833             return E_FAIL;
834         }
835     }
836
837     if (hr == S_OK && This->decode_info.invert_grayscale)
838     {
839         BYTE *byte, *end;
840
841         if (This->decode_info.samples != 1)
842         {
843             ERR("cannot invert grayscale image with %u samples\n", This->decode_info.samples);
844             return E_FAIL;
845         }
846
847         end = This->cached_tile+This->decode_info.tile_size;
848
849         for (byte = This->cached_tile; byte != end; byte++)
850             *byte = ~(*byte);
851     }
852
853     if (hr == S_OK)
854     {
855         This->cached_tile_x = tile_x;
856         This->cached_tile_y = tile_y;
857     }
858
859     return hr;
860 }
861
862 static HRESULT WINAPI TiffFrameDecode_CopyPixels(IWICBitmapFrameDecode *iface,
863     const WICRect *prc, UINT cbStride, UINT cbBufferSize, BYTE *pbBuffer)
864 {
865     TiffFrameDecode *This = (TiffFrameDecode*)iface;
866     UINT min_tile_x, max_tile_x, min_tile_y, max_tile_y;
867     UINT tile_x, tile_y;
868     WICRect rc;
869     HRESULT hr=S_OK;
870     BYTE *dst_tilepos;
871     UINT bytesperrow;
872     WICRect rect;
873
874     TRACE("(%p,%p,%u,%u,%p)\n", iface, prc, cbStride, cbBufferSize, pbBuffer);
875
876     if (!prc)
877     {
878         rect.X = 0;
879         rect.Y = 0;
880         rect.Width = This->decode_info.width;
881         rect.Height = This->decode_info.height;
882         prc = &rect;
883     }
884     else
885     {
886         if (prc->X < 0 || prc->Y < 0 || prc->X+prc->Width > This->decode_info.width ||
887             prc->Y+prc->Height > This->decode_info.height)
888             return E_INVALIDARG;
889     }
890
891     bytesperrow = ((This->decode_info.bpp * prc->Width)+7)/8;
892
893     if (cbStride < bytesperrow)
894         return E_INVALIDARG;
895
896     if ((cbStride * prc->Height) > cbBufferSize)
897         return E_INVALIDARG;
898
899     min_tile_x = prc->X / This->decode_info.tile_width;
900     min_tile_y = prc->Y / This->decode_info.tile_height;
901     max_tile_x = (prc->X+prc->Width-1) / This->decode_info.tile_width;
902     max_tile_y = (prc->Y+prc->Height-1) / This->decode_info.tile_height;
903
904     EnterCriticalSection(&This->parent->lock);
905
906     for (tile_x=min_tile_x; tile_x <= max_tile_x; tile_x++)
907     {
908         for (tile_y=min_tile_y; tile_y <= max_tile_y; tile_y++)
909         {
910             if (tile_x != This->cached_tile_x || tile_y != This->cached_tile_y)
911             {
912                 hr = TiffFrameDecode_ReadTile(This, tile_x, tile_y);
913             }
914
915             if (SUCCEEDED(hr))
916             {
917                 if (prc->X < tile_x * This->decode_info.tile_width)
918                     rc.X = 0;
919                 else
920                     rc.X = prc->X - tile_x * This->decode_info.tile_width;
921
922                 if (prc->Y < tile_y * This->decode_info.tile_height)
923                     rc.Y = 0;
924                 else
925                     rc.Y = prc->Y - tile_y * This->decode_info.tile_height;
926
927                 if (prc->X+prc->Width > (tile_x+1) * This->decode_info.tile_width)
928                     rc.Width = This->decode_info.tile_width - rc.X;
929                 else if (prc->X < tile_x * This->decode_info.tile_width)
930                     rc.Width = prc->Width + prc->X - tile_x * This->decode_info.tile_width;
931                 else
932                     rc.Width = prc->Width;
933
934                 if (prc->Y+prc->Height > (tile_y+1) * This->decode_info.tile_height)
935                     rc.Height = This->decode_info.tile_height - rc.Y;
936                 else if (prc->Y < tile_y * This->decode_info.tile_height)
937                     rc.Height = prc->Height + prc->Y - tile_y * This->decode_info.tile_height;
938                 else
939                     rc.Height = prc->Height;
940
941                 dst_tilepos = pbBuffer + (cbStride * ((rc.Y + tile_y * This->decode_info.tile_height) - prc->Y)) +
942                     ((This->decode_info.bpp * ((rc.X + tile_x * This->decode_info.tile_width) - prc->X) + 7) / 8);
943
944                 hr = copy_pixels(This->decode_info.bpp, This->cached_tile,
945                     This->decode_info.tile_width, This->decode_info.tile_height, This->decode_info.tile_stride,
946                     &rc, cbStride, cbBufferSize, dst_tilepos);
947             }
948
949             if (FAILED(hr))
950             {
951                 LeaveCriticalSection(&This->parent->lock);
952                 TRACE("<-- 0x%x\n", hr);
953                 return hr;
954             }
955         }
956     }
957
958     LeaveCriticalSection(&This->parent->lock);
959
960     return S_OK;
961 }
962
963 static HRESULT WINAPI TiffFrameDecode_GetMetadataQueryReader(IWICBitmapFrameDecode *iface,
964     IWICMetadataQueryReader **ppIMetadataQueryReader)
965 {
966     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
967     return E_NOTIMPL;
968 }
969
970 static HRESULT WINAPI TiffFrameDecode_GetColorContexts(IWICBitmapFrameDecode *iface,
971     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
972 {
973     FIXME("(%p,%u,%p,%p): stub\n", iface, cCount, ppIColorContexts, pcActualCount);
974     return E_NOTIMPL;
975 }
976
977 static HRESULT WINAPI TiffFrameDecode_GetThumbnail(IWICBitmapFrameDecode *iface,
978     IWICBitmapSource **ppIThumbnail)
979 {
980     FIXME("(%p,%p): stub\n", iface, ppIThumbnail);
981     return E_NOTIMPL;
982 }
983
984 static const IWICBitmapFrameDecodeVtbl TiffFrameDecode_Vtbl = {
985     TiffFrameDecode_QueryInterface,
986     TiffFrameDecode_AddRef,
987     TiffFrameDecode_Release,
988     TiffFrameDecode_GetSize,
989     TiffFrameDecode_GetPixelFormat,
990     TiffFrameDecode_GetResolution,
991     TiffFrameDecode_CopyPalette,
992     TiffFrameDecode_CopyPixels,
993     TiffFrameDecode_GetMetadataQueryReader,
994     TiffFrameDecode_GetColorContexts,
995     TiffFrameDecode_GetThumbnail
996 };
997
998 HRESULT TiffDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
999 {
1000     HRESULT ret;
1001     TiffDecoder *This;
1002
1003     TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);
1004
1005     *ppv = NULL;
1006
1007     if (pUnkOuter) return CLASS_E_NOAGGREGATION;
1008
1009     if (!load_libtiff())
1010     {
1011         ERR("Failed reading TIFF because unable to load %s\n",SONAME_LIBTIFF);
1012         return E_FAIL;
1013     }
1014
1015     This = HeapAlloc(GetProcessHeap(), 0, sizeof(TiffDecoder));
1016     if (!This) return E_OUTOFMEMORY;
1017
1018     This->lpVtbl = &TiffDecoder_Vtbl;
1019     This->ref = 1;
1020     This->stream = NULL;
1021     InitializeCriticalSection(&This->lock);
1022     This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": TiffDecoder.lock");
1023     This->tiff = NULL;
1024     This->initialized = FALSE;
1025
1026     ret = IUnknown_QueryInterface((IUnknown*)This, iid, ppv);
1027     IUnknown_Release((IUnknown*)This);
1028
1029     return ret;
1030 }
1031
1032 #else /* !SONAME_LIBTIFF */
1033
1034 HRESULT TiffDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
1035 {
1036     ERR("Trying to load TIFF picture, but Wine was compiled without TIFF support.\n");
1037     return E_FAIL;
1038 }
1039
1040 #endif