Release 1.5.29.
[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 #include "wincodecsdk.h"
37
38 #include "wincodecs_private.h"
39
40 #include "wine/debug.h"
41 #include "wine/library.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(wincodecs);
44
45 #ifdef SONAME_LIBTIFF
46
47 static CRITICAL_SECTION init_tiff_cs;
48 static CRITICAL_SECTION_DEBUG init_tiff_cs_debug =
49 {
50     0, 0, &init_tiff_cs,
51     { &init_tiff_cs_debug.ProcessLocksList,
52       &init_tiff_cs_debug.ProcessLocksList },
53     0, 0, { (DWORD_PTR)(__FILE__ ": init_tiff_cs") }
54 };
55 static CRITICAL_SECTION init_tiff_cs = { &init_tiff_cs_debug, -1, 0, 0, 0, 0 };
56
57 static const WCHAR wszTiffCompressionMethod[] = {'T','i','f','f','C','o','m','p','r','e','s','s','i','o','n','M','e','t','h','o','d',0};
58 static const WCHAR wszCompressionQuality[] = {'C','o','m','p','r','e','s','s','i','o','n','Q','u','a','l','i','t','y',0};
59
60 static void *libtiff_handle;
61 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
62 MAKE_FUNCPTR(TIFFClientOpen);
63 MAKE_FUNCPTR(TIFFClose);
64 MAKE_FUNCPTR(TIFFCurrentDirOffset);
65 MAKE_FUNCPTR(TIFFGetField);
66 MAKE_FUNCPTR(TIFFIsByteSwapped);
67 MAKE_FUNCPTR(TIFFNumberOfDirectories);
68 MAKE_FUNCPTR(TIFFReadDirectory);
69 MAKE_FUNCPTR(TIFFReadEncodedStrip);
70 MAKE_FUNCPTR(TIFFReadEncodedTile);
71 MAKE_FUNCPTR(TIFFSetDirectory);
72 MAKE_FUNCPTR(TIFFSetField);
73 MAKE_FUNCPTR(TIFFWriteDirectory);
74 MAKE_FUNCPTR(TIFFWriteScanline);
75 #undef MAKE_FUNCPTR
76
77 static void *load_libtiff(void)
78 {
79     void *result;
80
81     EnterCriticalSection(&init_tiff_cs);
82
83     if (!libtiff_handle &&
84         (libtiff_handle = wine_dlopen(SONAME_LIBTIFF, RTLD_NOW, NULL, 0)) != NULL)
85     {
86         void * (*pTIFFSetWarningHandler)(void *);
87         void * (*pTIFFSetWarningHandlerExt)(void *);
88
89 #define LOAD_FUNCPTR(f) \
90     if((p##f = wine_dlsym(libtiff_handle, #f, NULL, 0)) == NULL) { \
91         ERR("failed to load symbol %s\n", #f); \
92         libtiff_handle = NULL; \
93         LeaveCriticalSection(&init_tiff_cs); \
94         return NULL; \
95     }
96         LOAD_FUNCPTR(TIFFClientOpen);
97         LOAD_FUNCPTR(TIFFClose);
98         LOAD_FUNCPTR(TIFFCurrentDirOffset);
99         LOAD_FUNCPTR(TIFFGetField);
100         LOAD_FUNCPTR(TIFFIsByteSwapped);
101         LOAD_FUNCPTR(TIFFNumberOfDirectories);
102         LOAD_FUNCPTR(TIFFReadDirectory);
103         LOAD_FUNCPTR(TIFFReadEncodedStrip);
104         LOAD_FUNCPTR(TIFFReadEncodedTile);
105         LOAD_FUNCPTR(TIFFSetDirectory);
106         LOAD_FUNCPTR(TIFFSetField);
107         LOAD_FUNCPTR(TIFFWriteDirectory);
108         LOAD_FUNCPTR(TIFFWriteScanline);
109 #undef LOAD_FUNCPTR
110
111         if ((pTIFFSetWarningHandler = wine_dlsym(libtiff_handle, "TIFFSetWarningHandler", NULL, 0)))
112             pTIFFSetWarningHandler(NULL);
113         if ((pTIFFSetWarningHandlerExt = wine_dlsym(libtiff_handle, "TIFFSetWarningHandlerExt", NULL, 0)))
114             pTIFFSetWarningHandlerExt(NULL);
115     }
116
117     result = libtiff_handle;
118
119     LeaveCriticalSection(&init_tiff_cs);
120     return result;
121 }
122
123 static tsize_t tiff_stream_read(thandle_t client_data, tdata_t data, tsize_t size)
124 {
125     IStream *stream = (IStream*)client_data;
126     ULONG bytes_read;
127     HRESULT hr;
128
129     hr = IStream_Read(stream, data, size, &bytes_read);
130     if (FAILED(hr)) bytes_read = 0;
131     return bytes_read;
132 }
133
134 static tsize_t tiff_stream_write(thandle_t client_data, tdata_t data, tsize_t size)
135 {
136     IStream *stream = (IStream*)client_data;
137     ULONG bytes_written;
138     HRESULT hr;
139
140     hr = IStream_Write(stream, data, size, &bytes_written);
141     if (FAILED(hr)) bytes_written = 0;
142     return bytes_written;
143 }
144
145 static toff_t tiff_stream_seek(thandle_t client_data, toff_t offset, int whence)
146 {
147     IStream *stream = (IStream*)client_data;
148     LARGE_INTEGER move;
149     DWORD origin;
150     ULARGE_INTEGER new_position;
151     HRESULT hr;
152
153     move.QuadPart = offset;
154     switch (whence)
155     {
156         case SEEK_SET:
157             origin = STREAM_SEEK_SET;
158             break;
159         case SEEK_CUR:
160             origin = STREAM_SEEK_CUR;
161             break;
162         case SEEK_END:
163             origin = STREAM_SEEK_END;
164             break;
165         default:
166             ERR("unknown whence value %i\n", whence);
167             return -1;
168     }
169
170     hr = IStream_Seek(stream, move, origin, &new_position);
171     if (SUCCEEDED(hr)) return new_position.QuadPart;
172     else return -1;
173 }
174
175 static int tiff_stream_close(thandle_t client_data)
176 {
177     /* Caller is responsible for releasing the stream object. */
178     return 0;
179 }
180
181 static toff_t tiff_stream_size(thandle_t client_data)
182 {
183     IStream *stream = (IStream*)client_data;
184     STATSTG statstg;
185     HRESULT hr;
186
187     hr = IStream_Stat(stream, &statstg, STATFLAG_NONAME);
188
189     if (SUCCEEDED(hr)) return statstg.cbSize.QuadPart;
190     else return -1;
191 }
192
193 static int tiff_stream_map(thandle_t client_data, tdata_t *addr, toff_t *size)
194 {
195     /* Cannot mmap streams */
196     return 0;
197 }
198
199 static void tiff_stream_unmap(thandle_t client_data, tdata_t addr, toff_t size)
200 {
201     /* No need to ever do this, since we can't map things. */
202 }
203
204 static TIFF* tiff_open_stream(IStream *stream, const char *mode)
205 {
206     LARGE_INTEGER zero;
207
208     zero.QuadPart = 0;
209     IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL);
210
211     return pTIFFClientOpen("<IStream object>", mode, stream, tiff_stream_read,
212         tiff_stream_write, tiff_stream_seek, tiff_stream_close,
213         tiff_stream_size, tiff_stream_map, tiff_stream_unmap);
214 }
215
216 typedef struct {
217     IWICBitmapDecoder IWICBitmapDecoder_iface;
218     LONG ref;
219     IStream *stream;
220     CRITICAL_SECTION lock; /* Must be held when tiff is used or initiailzed is set */
221     TIFF *tiff;
222     BOOL initialized;
223 } TiffDecoder;
224
225 typedef struct {
226     const WICPixelFormatGUID *format;
227     int bps;
228     int samples;
229     int bpp;
230     int planar;
231     int indexed;
232     int reverse_bgr;
233     int invert_grayscale;
234     UINT width, height;
235     UINT tile_width, tile_height;
236     UINT tile_stride;
237     UINT tile_size;
238     int tiled;
239     UINT tiles_across;
240     UINT resolution_unit;
241     float xres, yres;
242 } tiff_decode_info;
243
244 typedef struct {
245     IWICBitmapFrameDecode IWICBitmapFrameDecode_iface;
246     IWICMetadataBlockReader IWICMetadataBlockReader_iface;
247     LONG ref;
248     TiffDecoder *parent;
249     UINT index;
250     tiff_decode_info decode_info;
251     INT cached_tile_x, cached_tile_y;
252     BYTE *cached_tile;
253 } TiffFrameDecode;
254
255 static const IWICBitmapFrameDecodeVtbl TiffFrameDecode_Vtbl;
256 static const IWICMetadataBlockReaderVtbl TiffFrameDecode_BlockVtbl;
257
258 static inline TiffDecoder *impl_from_IWICBitmapDecoder(IWICBitmapDecoder *iface)
259 {
260     return CONTAINING_RECORD(iface, TiffDecoder, IWICBitmapDecoder_iface);
261 }
262
263 static inline TiffFrameDecode *impl_from_IWICBitmapFrameDecode(IWICBitmapFrameDecode *iface)
264 {
265     return CONTAINING_RECORD(iface, TiffFrameDecode, IWICBitmapFrameDecode_iface);
266 }
267
268 static inline TiffFrameDecode *impl_from_IWICMetadataBlockReader(IWICMetadataBlockReader *iface)
269 {
270     return CONTAINING_RECORD(iface, TiffFrameDecode, IWICMetadataBlockReader_iface);
271 }
272
273 static HRESULT tiff_get_decode_info(TIFF *tiff, tiff_decode_info *decode_info)
274 {
275     uint16 photometric, bps, samples, planar;
276     uint16 extra_sample_count, extra_sample, *extra_samples;
277     int ret;
278
279     decode_info->indexed = 0;
280     decode_info->reverse_bgr = 0;
281     decode_info->invert_grayscale = 0;
282     decode_info->tiled = 0;
283
284     ret = pTIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric);
285     if (!ret)
286     {
287         WARN("missing PhotometricInterpretation tag\n");
288         return E_FAIL;
289     }
290
291     ret = pTIFFGetField(tiff, TIFFTAG_BITSPERSAMPLE, &bps);
292     if (!ret) bps = 1;
293     decode_info->bps = bps;
294
295     ret = pTIFFGetField(tiff, TIFFTAG_SAMPLESPERPIXEL, &samples);
296     if (!ret) samples = 1;
297     decode_info->samples = samples;
298
299     if (samples == 1)
300         planar = 1;
301     else
302     {
303         ret = pTIFFGetField(tiff, TIFFTAG_PLANARCONFIG, &planar);
304         if (!ret) planar = 1;
305         if (planar != 1)
306         {
307             FIXME("unhandled planar configuration %u\n", planar);
308             return E_FAIL;
309         }
310     }
311     decode_info->planar = planar;
312
313     switch(photometric)
314     {
315     case 0: /* WhiteIsZero */
316         decode_info->invert_grayscale = 1;
317         /* fall through */
318     case 1: /* BlackIsZero */
319         if (samples != 1)
320         {
321             FIXME("unhandled grayscale sample count %u\n", samples);
322             return E_FAIL;
323         }
324
325         decode_info->bpp = bps;
326         switch (bps)
327         {
328         case 1:
329             decode_info->format = &GUID_WICPixelFormatBlackWhite;
330             break;
331         case 4:
332             decode_info->format = &GUID_WICPixelFormat4bppGray;
333             break;
334         case 8:
335             decode_info->format = &GUID_WICPixelFormat8bppGray;
336             break;
337         default:
338             FIXME("unhandled greyscale bit count %u\n", bps);
339             return E_FAIL;
340         }
341         break;
342     case 2: /* RGB */
343         decode_info->bpp = bps * samples;
344
345         if (samples == 4)
346         {
347             ret = pTIFFGetField(tiff, TIFFTAG_EXTRASAMPLES, &extra_sample_count, &extra_samples);
348             if (!ret)
349             {
350                 extra_sample_count = 1;
351                 extra_sample = 0;
352                 extra_samples = &extra_sample;
353             }
354         }
355         else if (samples != 3)
356         {
357             FIXME("unhandled RGB sample count %u\n", samples);
358             return E_FAIL;
359         }
360
361         switch(bps)
362         {
363         case 8:
364             decode_info->reverse_bgr = 1;
365             if (samples == 3)
366                 decode_info->format = &GUID_WICPixelFormat24bppBGR;
367             else
368                 switch(extra_samples[0])
369                 {
370                 case 1: /* Associated (pre-multiplied) alpha data */
371                     decode_info->format = &GUID_WICPixelFormat32bppPBGRA;
372                     break;
373                 case 0: /* Unspecified data */
374                 case 2: /* Unassociated alpha data */
375                     decode_info->format = &GUID_WICPixelFormat32bppBGRA;
376                     break;
377                 default:
378                     FIXME("unhandled extra sample type %i\n", extra_samples[0]);
379                     return E_FAIL;
380                 }
381             break;
382         case 16:
383             if (samples == 3)
384                 decode_info->format = &GUID_WICPixelFormat48bppRGB;
385             else
386                 switch(extra_samples[0])
387                 {
388                 case 1: /* Associated (pre-multiplied) alpha data */
389                     decode_info->format = &GUID_WICPixelFormat64bppPRGBA;
390                     break;
391                 case 0: /* Unspecified data */
392                 case 2: /* Unassociated alpha data */
393                     decode_info->format = &GUID_WICPixelFormat64bppRGBA;
394                     break;
395                 default:
396                     FIXME("unhandled extra sample type %i\n", extra_samples[0]);
397                     return E_FAIL;
398                 }
399             break;
400         default:
401             FIXME("unhandled RGB bit count %u\n", bps);
402             return E_FAIL;
403         }
404         break;
405     case 3: /* RGB Palette */
406         if (samples != 1)
407         {
408             FIXME("unhandled indexed sample count %u\n", samples);
409             return E_FAIL;
410         }
411
412         decode_info->indexed = 1;
413         decode_info->bpp = bps;
414         switch (bps)
415         {
416         case 4:
417             decode_info->format = &GUID_WICPixelFormat4bppIndexed;
418             break;
419         case 8:
420             decode_info->format = &GUID_WICPixelFormat8bppIndexed;
421             break;
422         default:
423             FIXME("unhandled indexed bit count %u\n", bps);
424             return E_FAIL;
425         }
426         break;
427     case 4: /* Transparency mask */
428     case 5: /* CMYK */
429     case 6: /* YCbCr */
430     case 8: /* CIELab */
431     default:
432         FIXME("unhandled PhotometricInterpretation %u\n", photometric);
433         return E_FAIL;
434     }
435
436     ret = pTIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &decode_info->width);
437     if (!ret)
438     {
439         WARN("missing image width\n");
440         return E_FAIL;
441     }
442
443     ret = pTIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &decode_info->height);
444     if (!ret)
445     {
446         WARN("missing image length\n");
447         return E_FAIL;
448     }
449
450     if ((ret = pTIFFGetField(tiff, TIFFTAG_TILEWIDTH, &decode_info->tile_width)))
451     {
452         decode_info->tiled = 1;
453
454         ret = pTIFFGetField(tiff, TIFFTAG_TILELENGTH, &decode_info->tile_height);
455         if (!ret)
456         {
457             WARN("missing tile height\n");
458             return E_FAIL;
459         }
460
461         decode_info->tile_stride = ((decode_info->bpp * decode_info->tile_width + 7)/8);
462         decode_info->tile_size = decode_info->tile_height * decode_info->tile_stride;
463         decode_info->tiles_across = (decode_info->width + decode_info->tile_width - 1) / decode_info->tile_width;
464     }
465     else if ((ret = pTIFFGetField(tiff, TIFFTAG_ROWSPERSTRIP, &decode_info->tile_height)))
466     {
467         if (decode_info->tile_height > decode_info->height)
468             decode_info->tile_height = decode_info->height;
469         decode_info->tile_width = decode_info->width;
470         decode_info->tile_stride = ((decode_info->bpp * decode_info->tile_width + 7)/8);
471         decode_info->tile_size = decode_info->tile_height * decode_info->tile_stride;
472     }
473     else
474     {
475         /* Some broken TIFF files have a single strip and lack the RowsPerStrip tag */
476         decode_info->tile_height = decode_info->height;
477         decode_info->tile_width = decode_info->width;
478         decode_info->tile_stride = ((decode_info->bpp * decode_info->tile_width + 7)/8);
479         decode_info->tile_size = decode_info->tile_height * decode_info->tile_stride;
480     }
481
482     decode_info->resolution_unit = 0;
483     pTIFFGetField(tiff, TIFFTAG_RESOLUTIONUNIT, &decode_info->resolution_unit);
484     if (decode_info->resolution_unit != 0)
485     {
486         ret = pTIFFGetField(tiff, TIFFTAG_XRESOLUTION, &decode_info->xres);
487         if (!ret)
488         {
489             WARN("missing X resolution\n");
490             decode_info->resolution_unit = 0;
491         }
492
493         ret = pTIFFGetField(tiff, TIFFTAG_YRESOLUTION, &decode_info->yres);
494         if (!ret)
495         {
496             WARN("missing Y resolution\n");
497             decode_info->resolution_unit = 0;
498         }
499     }
500
501     return S_OK;
502 }
503
504 static HRESULT WINAPI TiffDecoder_QueryInterface(IWICBitmapDecoder *iface, REFIID iid,
505     void **ppv)
506 {
507     TiffDecoder *This = impl_from_IWICBitmapDecoder(iface);
508     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
509
510     if (!ppv) return E_INVALIDARG;
511
512     if (IsEqualIID(&IID_IUnknown, iid) ||
513         IsEqualIID(&IID_IWICBitmapDecoder, iid))
514     {
515         *ppv = &This->IWICBitmapDecoder_iface;
516     }
517     else
518     {
519         *ppv = NULL;
520         return E_NOINTERFACE;
521     }
522
523     IUnknown_AddRef((IUnknown*)*ppv);
524     return S_OK;
525 }
526
527 static ULONG WINAPI TiffDecoder_AddRef(IWICBitmapDecoder *iface)
528 {
529     TiffDecoder *This = impl_from_IWICBitmapDecoder(iface);
530     ULONG ref = InterlockedIncrement(&This->ref);
531
532     TRACE("(%p) refcount=%u\n", iface, ref);
533
534     return ref;
535 }
536
537 static ULONG WINAPI TiffDecoder_Release(IWICBitmapDecoder *iface)
538 {
539     TiffDecoder *This = impl_from_IWICBitmapDecoder(iface);
540     ULONG ref = InterlockedDecrement(&This->ref);
541
542     TRACE("(%p) refcount=%u\n", iface, ref);
543
544     if (ref == 0)
545     {
546         if (This->tiff) pTIFFClose(This->tiff);
547         if (This->stream) IStream_Release(This->stream);
548         This->lock.DebugInfo->Spare[0] = 0;
549         DeleteCriticalSection(&This->lock);
550         HeapFree(GetProcessHeap(), 0, This);
551     }
552
553     return ref;
554 }
555
556 static HRESULT WINAPI TiffDecoder_QueryCapability(IWICBitmapDecoder *iface, IStream *stream,
557     DWORD *capability)
558 {
559     HRESULT hr;
560
561     TRACE("(%p,%p,%p)\n", iface, stream, capability);
562
563     if (!stream || !capability) return E_INVALIDARG;
564
565     hr = IWICBitmapDecoder_Initialize(iface, stream, WICDecodeMetadataCacheOnDemand);
566     if (hr != S_OK) return hr;
567
568     *capability = WICBitmapDecoderCapabilityCanDecodeAllImages |
569                   WICBitmapDecoderCapabilityCanDecodeSomeImages |
570                   WICBitmapDecoderCapabilityCanEnumerateMetadata;
571     return S_OK;
572 }
573
574 static HRESULT WINAPI TiffDecoder_Initialize(IWICBitmapDecoder *iface, IStream *pIStream,
575     WICDecodeOptions cacheOptions)
576 {
577     TiffDecoder *This = impl_from_IWICBitmapDecoder(iface);
578     TIFF *tiff;
579     HRESULT hr=S_OK;
580
581     TRACE("(%p,%p,%x): stub\n", iface, pIStream, cacheOptions);
582
583     EnterCriticalSection(&This->lock);
584
585     if (This->initialized)
586     {
587         hr = WINCODEC_ERR_WRONGSTATE;
588         goto exit;
589     }
590
591     tiff = tiff_open_stream(pIStream, "r");
592
593     if (!tiff)
594     {
595         hr = E_FAIL;
596         goto exit;
597     }
598
599     This->tiff = tiff;
600     This->stream = pIStream;
601     IStream_AddRef(pIStream);
602     This->initialized = TRUE;
603
604 exit:
605     LeaveCriticalSection(&This->lock);
606     return hr;
607 }
608
609 static HRESULT WINAPI TiffDecoder_GetContainerFormat(IWICBitmapDecoder *iface,
610     GUID *pguidContainerFormat)
611 {
612     if (!pguidContainerFormat) return E_INVALIDARG;
613
614     memcpy(pguidContainerFormat, &GUID_ContainerFormatTiff, sizeof(GUID));
615     return S_OK;
616 }
617
618 static HRESULT WINAPI TiffDecoder_GetDecoderInfo(IWICBitmapDecoder *iface,
619     IWICBitmapDecoderInfo **ppIDecoderInfo)
620 {
621     HRESULT hr;
622     IWICComponentInfo *compinfo;
623
624     TRACE("(%p,%p)\n", iface, ppIDecoderInfo);
625
626     hr = CreateComponentInfo(&CLSID_WICTiffDecoder, &compinfo);
627     if (FAILED(hr)) return hr;
628
629     hr = IWICComponentInfo_QueryInterface(compinfo, &IID_IWICBitmapDecoderInfo,
630         (void**)ppIDecoderInfo);
631
632     IWICComponentInfo_Release(compinfo);
633
634     return hr;
635 }
636
637 static HRESULT WINAPI TiffDecoder_CopyPalette(IWICBitmapDecoder *iface,
638     IWICPalette *pIPalette)
639 {
640     FIXME("(%p,%p): stub\n", iface, pIPalette);
641     return E_NOTIMPL;
642 }
643
644 static HRESULT WINAPI TiffDecoder_GetMetadataQueryReader(IWICBitmapDecoder *iface,
645     IWICMetadataQueryReader **ppIMetadataQueryReader)
646 {
647     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
648     return E_NOTIMPL;
649 }
650
651 static HRESULT WINAPI TiffDecoder_GetPreview(IWICBitmapDecoder *iface,
652     IWICBitmapSource **ppIBitmapSource)
653 {
654     TRACE("(%p,%p)\n", iface, ppIBitmapSource);
655
656     if (!ppIBitmapSource) return E_INVALIDARG;
657
658     *ppIBitmapSource = NULL;
659     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
660 }
661
662 static HRESULT WINAPI TiffDecoder_GetColorContexts(IWICBitmapDecoder *iface,
663     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
664 {
665     FIXME("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);
666     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
667 }
668
669 static HRESULT WINAPI TiffDecoder_GetThumbnail(IWICBitmapDecoder *iface,
670     IWICBitmapSource **ppIThumbnail)
671 {
672     TRACE("(%p,%p)\n", iface, ppIThumbnail);
673
674     if (!ppIThumbnail) return E_INVALIDARG;
675
676     *ppIThumbnail = NULL;
677     return WINCODEC_ERR_CODECNOTHUMBNAIL;
678 }
679
680 static HRESULT WINAPI TiffDecoder_GetFrameCount(IWICBitmapDecoder *iface,
681     UINT *pCount)
682 {
683     TiffDecoder *This = impl_from_IWICBitmapDecoder(iface);
684
685     if (!pCount) return E_INVALIDARG;
686
687     EnterCriticalSection(&This->lock);
688     *pCount = This->tiff ? pTIFFNumberOfDirectories(This->tiff) : 0;
689     LeaveCriticalSection(&This->lock);
690
691     TRACE("(%p) <-- %i\n", iface, *pCount);
692
693     return S_OK;
694 }
695
696 static HRESULT WINAPI TiffDecoder_GetFrame(IWICBitmapDecoder *iface,
697     UINT index, IWICBitmapFrameDecode **ppIBitmapFrame)
698 {
699     TiffDecoder *This = impl_from_IWICBitmapDecoder(iface);
700     TiffFrameDecode *result;
701     int res;
702     tiff_decode_info decode_info;
703     HRESULT hr;
704
705     TRACE("(%p,%u,%p)\n", iface, index, ppIBitmapFrame);
706
707     if (!This->tiff)
708         return WINCODEC_ERR_FRAMEMISSING;
709
710     EnterCriticalSection(&This->lock);
711     res = pTIFFSetDirectory(This->tiff, index);
712     if (!res) hr = E_INVALIDARG;
713     else hr = tiff_get_decode_info(This->tiff, &decode_info);
714     LeaveCriticalSection(&This->lock);
715
716     if (SUCCEEDED(hr))
717     {
718         result = HeapAlloc(GetProcessHeap(), 0, sizeof(TiffFrameDecode));
719
720         if (result)
721         {
722             result->IWICBitmapFrameDecode_iface.lpVtbl = &TiffFrameDecode_Vtbl;
723             result->IWICMetadataBlockReader_iface.lpVtbl = &TiffFrameDecode_BlockVtbl;
724             result->ref = 1;
725             result->parent = This;
726             result->index = index;
727             result->decode_info = decode_info;
728             result->cached_tile_x = -1;
729             result->cached_tile = HeapAlloc(GetProcessHeap(), 0, decode_info.tile_size);
730
731             if (result->cached_tile)
732                 *ppIBitmapFrame = &result->IWICBitmapFrameDecode_iface;
733             else
734             {
735                 hr = E_OUTOFMEMORY;
736                 HeapFree(GetProcessHeap(), 0, result);
737             }
738         }
739         else hr = E_OUTOFMEMORY;
740     }
741
742     if (FAILED(hr)) *ppIBitmapFrame = NULL;
743
744     return hr;
745 }
746
747 static const IWICBitmapDecoderVtbl TiffDecoder_Vtbl = {
748     TiffDecoder_QueryInterface,
749     TiffDecoder_AddRef,
750     TiffDecoder_Release,
751     TiffDecoder_QueryCapability,
752     TiffDecoder_Initialize,
753     TiffDecoder_GetContainerFormat,
754     TiffDecoder_GetDecoderInfo,
755     TiffDecoder_CopyPalette,
756     TiffDecoder_GetMetadataQueryReader,
757     TiffDecoder_GetPreview,
758     TiffDecoder_GetColorContexts,
759     TiffDecoder_GetThumbnail,
760     TiffDecoder_GetFrameCount,
761     TiffDecoder_GetFrame
762 };
763
764 static HRESULT WINAPI TiffFrameDecode_QueryInterface(IWICBitmapFrameDecode *iface, REFIID iid,
765     void **ppv)
766 {
767     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
768     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
769
770     if (!ppv) return E_INVALIDARG;
771
772     if (IsEqualIID(&IID_IUnknown, iid) ||
773         IsEqualIID(&IID_IWICBitmapSource, iid) ||
774         IsEqualIID(&IID_IWICBitmapFrameDecode, iid))
775     {
776         *ppv = &This->IWICBitmapFrameDecode_iface;
777     }
778     else if (IsEqualIID(&IID_IWICMetadataBlockReader, iid))
779     {
780         *ppv = &This->IWICMetadataBlockReader_iface;
781     }
782     else
783     {
784         *ppv = NULL;
785         return E_NOINTERFACE;
786     }
787
788     IUnknown_AddRef((IUnknown*)*ppv);
789     return S_OK;
790 }
791
792 static ULONG WINAPI TiffFrameDecode_AddRef(IWICBitmapFrameDecode *iface)
793 {
794     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
795     ULONG ref = InterlockedIncrement(&This->ref);
796
797     TRACE("(%p) refcount=%u\n", iface, ref);
798
799     return ref;
800 }
801
802 static ULONG WINAPI TiffFrameDecode_Release(IWICBitmapFrameDecode *iface)
803 {
804     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
805     ULONG ref = InterlockedDecrement(&This->ref);
806
807     TRACE("(%p) refcount=%u\n", iface, ref);
808
809     if (ref == 0)
810     {
811         HeapFree(GetProcessHeap(), 0, This->cached_tile);
812         HeapFree(GetProcessHeap(), 0, This);
813     }
814
815     return ref;
816 }
817
818 static HRESULT WINAPI TiffFrameDecode_GetSize(IWICBitmapFrameDecode *iface,
819     UINT *puiWidth, UINT *puiHeight)
820 {
821     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
822
823     *puiWidth = This->decode_info.width;
824     *puiHeight = This->decode_info.height;
825
826     TRACE("(%p) <-- %ux%u\n", iface, *puiWidth, *puiHeight);
827
828     return S_OK;
829 }
830
831 static HRESULT WINAPI TiffFrameDecode_GetPixelFormat(IWICBitmapFrameDecode *iface,
832     WICPixelFormatGUID *pPixelFormat)
833 {
834     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
835
836     memcpy(pPixelFormat, This->decode_info.format, sizeof(GUID));
837
838     TRACE("(%p) <-- %s\n", This, debugstr_guid(This->decode_info.format));
839
840     return S_OK;
841 }
842
843 static HRESULT WINAPI TiffFrameDecode_GetResolution(IWICBitmapFrameDecode *iface,
844     double *pDpiX, double *pDpiY)
845 {
846     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
847
848     switch (This->decode_info.resolution_unit)
849     {
850     default:
851         FIXME("unknown resolution unit %i\n", This->decode_info.resolution_unit);
852         /* fall through */
853     case 0: /* Not set */
854         *pDpiX = *pDpiY = 96.0;
855         break;
856     case 1: /* Relative measurements */
857         *pDpiX = 96.0;
858         *pDpiY = 96.0 * This->decode_info.yres / This->decode_info.xres;
859         break;
860     case 2: /* Inch */
861         *pDpiX = This->decode_info.xres;
862         *pDpiY = This->decode_info.yres;
863         break;
864     case 3: /* Centimeter */
865         *pDpiX = This->decode_info.xres / 2.54;
866         *pDpiY = This->decode_info.yres / 2.54;
867         break;
868     }
869
870     TRACE("(%p) <-- %f,%f unit=%i\n", iface, *pDpiX, *pDpiY, This->decode_info.resolution_unit);
871
872     return S_OK;
873 }
874
875 static HRESULT WINAPI TiffFrameDecode_CopyPalette(IWICBitmapFrameDecode *iface,
876     IWICPalette *pIPalette)
877 {
878     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
879     uint16 *red, *green, *blue;
880     WICColor colors[256];
881     int color_count, ret, i;
882
883     TRACE("(%p,%p)\n", iface, pIPalette);
884
885     color_count = 1<<This->decode_info.bps;
886
887     EnterCriticalSection(&This->parent->lock);
888     ret = pTIFFGetField(This->parent->tiff, TIFFTAG_COLORMAP, &red, &green, &blue);
889     LeaveCriticalSection(&This->parent->lock);
890
891     if (!ret)
892     {
893         WARN("Couldn't read color map\n");
894         return WINCODEC_ERR_PALETTEUNAVAILABLE;
895     }
896
897     for (i=0; i<color_count; i++)
898     {
899         colors[i] = 0xff000000 |
900             ((red[i]<<8) & 0xff0000) |
901             (green[i] & 0xff00) |
902             ((blue[i]>>8) & 0xff);
903     }
904
905     return IWICPalette_InitializeCustom(pIPalette, colors, color_count);
906 }
907
908 static HRESULT TiffFrameDecode_ReadTile(TiffFrameDecode *This, UINT tile_x, UINT tile_y)
909 {
910     HRESULT hr=S_OK;
911     tsize_t ret;
912     int swap_bytes;
913
914     swap_bytes = pTIFFIsByteSwapped(This->parent->tiff);
915
916     ret = pTIFFSetDirectory(This->parent->tiff, This->index);
917
918     if (ret == -1)
919         hr = E_FAIL;
920
921     if (hr == S_OK)
922     {
923         if (This->decode_info.tiled)
924         {
925             ret = pTIFFReadEncodedTile(This->parent->tiff, tile_x + tile_y * This->decode_info.tiles_across, This->cached_tile, This->decode_info.tile_size);
926         }
927         else
928         {
929             ret = pTIFFReadEncodedStrip(This->parent->tiff, tile_y, This->cached_tile, This->decode_info.tile_size);
930         }
931
932         if (ret == -1)
933             hr = E_FAIL;
934     }
935
936     if (hr == S_OK && This->decode_info.reverse_bgr)
937     {
938         if (This->decode_info.bps == 8)
939         {
940             UINT sample_count = This->decode_info.samples;
941
942             reverse_bgr8(sample_count, This->cached_tile, This->decode_info.tile_width,
943                 This->decode_info.tile_height, This->decode_info.tile_width * sample_count);
944         }
945     }
946
947     if (hr == S_OK && swap_bytes && This->decode_info.bps > 8)
948     {
949         UINT row, i, samples_per_row;
950         BYTE *sample, temp;
951
952         samples_per_row = This->decode_info.tile_width * This->decode_info.samples;
953
954         switch(This->decode_info.bps)
955         {
956         case 16:
957             for (row=0; row<This->decode_info.tile_height; row++)
958             {
959                 sample = This->cached_tile + row * This->decode_info.tile_stride;
960                 for (i=0; i<samples_per_row; i++)
961                 {
962                     temp = sample[1];
963                     sample[1] = sample[0];
964                     sample[0] = temp;
965                     sample += 2;
966                 }
967             }
968             break;
969         default:
970             ERR("unhandled bps for byte swap %u\n", This->decode_info.bps);
971             return E_FAIL;
972         }
973     }
974
975     if (hr == S_OK && This->decode_info.invert_grayscale)
976     {
977         BYTE *byte, *end;
978
979         if (This->decode_info.samples != 1)
980         {
981             ERR("cannot invert grayscale image with %u samples\n", This->decode_info.samples);
982             return E_FAIL;
983         }
984
985         end = This->cached_tile+This->decode_info.tile_size;
986
987         for (byte = This->cached_tile; byte != end; byte++)
988             *byte = ~(*byte);
989     }
990
991     if (hr == S_OK)
992     {
993         This->cached_tile_x = tile_x;
994         This->cached_tile_y = tile_y;
995     }
996
997     return hr;
998 }
999
1000 static HRESULT WINAPI TiffFrameDecode_CopyPixels(IWICBitmapFrameDecode *iface,
1001     const WICRect *prc, UINT cbStride, UINT cbBufferSize, BYTE *pbBuffer)
1002 {
1003     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
1004     UINT min_tile_x, max_tile_x, min_tile_y, max_tile_y;
1005     UINT tile_x, tile_y;
1006     WICRect rc;
1007     HRESULT hr=S_OK;
1008     BYTE *dst_tilepos;
1009     UINT bytesperrow;
1010     WICRect rect;
1011
1012     TRACE("(%p,%p,%u,%u,%p)\n", iface, prc, cbStride, cbBufferSize, pbBuffer);
1013
1014     if (!prc)
1015     {
1016         rect.X = 0;
1017         rect.Y = 0;
1018         rect.Width = This->decode_info.width;
1019         rect.Height = This->decode_info.height;
1020         prc = &rect;
1021     }
1022     else
1023     {
1024         if (prc->X < 0 || prc->Y < 0 || prc->X+prc->Width > This->decode_info.width ||
1025             prc->Y+prc->Height > This->decode_info.height)
1026             return E_INVALIDARG;
1027     }
1028
1029     bytesperrow = ((This->decode_info.bpp * prc->Width)+7)/8;
1030
1031     if (cbStride < bytesperrow)
1032         return E_INVALIDARG;
1033
1034     if ((cbStride * prc->Height) > cbBufferSize)
1035         return E_INVALIDARG;
1036
1037     min_tile_x = prc->X / This->decode_info.tile_width;
1038     min_tile_y = prc->Y / This->decode_info.tile_height;
1039     max_tile_x = (prc->X+prc->Width-1) / This->decode_info.tile_width;
1040     max_tile_y = (prc->Y+prc->Height-1) / This->decode_info.tile_height;
1041
1042     EnterCriticalSection(&This->parent->lock);
1043
1044     for (tile_x=min_tile_x; tile_x <= max_tile_x; tile_x++)
1045     {
1046         for (tile_y=min_tile_y; tile_y <= max_tile_y; tile_y++)
1047         {
1048             if (tile_x != This->cached_tile_x || tile_y != This->cached_tile_y)
1049             {
1050                 hr = TiffFrameDecode_ReadTile(This, tile_x, tile_y);
1051             }
1052
1053             if (SUCCEEDED(hr))
1054             {
1055                 if (prc->X < tile_x * This->decode_info.tile_width)
1056                     rc.X = 0;
1057                 else
1058                     rc.X = prc->X - tile_x * This->decode_info.tile_width;
1059
1060                 if (prc->Y < tile_y * This->decode_info.tile_height)
1061                     rc.Y = 0;
1062                 else
1063                     rc.Y = prc->Y - tile_y * This->decode_info.tile_height;
1064
1065                 if (prc->X+prc->Width > (tile_x+1) * This->decode_info.tile_width)
1066                     rc.Width = This->decode_info.tile_width - rc.X;
1067                 else if (prc->X < tile_x * This->decode_info.tile_width)
1068                     rc.Width = prc->Width + prc->X - tile_x * This->decode_info.tile_width;
1069                 else
1070                     rc.Width = prc->Width;
1071
1072                 if (prc->Y+prc->Height > (tile_y+1) * This->decode_info.tile_height)
1073                     rc.Height = This->decode_info.tile_height - rc.Y;
1074                 else if (prc->Y < tile_y * This->decode_info.tile_height)
1075                     rc.Height = prc->Height + prc->Y - tile_y * This->decode_info.tile_height;
1076                 else
1077                     rc.Height = prc->Height;
1078
1079                 dst_tilepos = pbBuffer + (cbStride * ((rc.Y + tile_y * This->decode_info.tile_height) - prc->Y)) +
1080                     ((This->decode_info.bpp * ((rc.X + tile_x * This->decode_info.tile_width) - prc->X) + 7) / 8);
1081
1082                 hr = copy_pixels(This->decode_info.bpp, This->cached_tile,
1083                     This->decode_info.tile_width, This->decode_info.tile_height, This->decode_info.tile_stride,
1084                     &rc, cbStride, cbBufferSize, dst_tilepos);
1085             }
1086
1087             if (FAILED(hr))
1088             {
1089                 LeaveCriticalSection(&This->parent->lock);
1090                 TRACE("<-- 0x%x\n", hr);
1091                 return hr;
1092             }
1093         }
1094     }
1095
1096     LeaveCriticalSection(&This->parent->lock);
1097
1098     return S_OK;
1099 }
1100
1101 static HRESULT WINAPI TiffFrameDecode_GetMetadataQueryReader(IWICBitmapFrameDecode *iface,
1102     IWICMetadataQueryReader **ppIMetadataQueryReader)
1103 {
1104     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
1105     return E_NOTIMPL;
1106 }
1107
1108 static HRESULT WINAPI TiffFrameDecode_GetColorContexts(IWICBitmapFrameDecode *iface,
1109     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
1110 {
1111     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
1112     const BYTE *profile;
1113     UINT len;
1114     HRESULT hr;
1115
1116     TRACE("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);
1117
1118     EnterCriticalSection(&This->parent->lock);
1119
1120     if (pTIFFGetField(This->parent->tiff, TIFFTAG_ICCPROFILE, &len, &profile))
1121     {
1122         if (cCount && ppIColorContexts)
1123         {
1124             hr = IWICColorContext_InitializeFromMemory(*ppIColorContexts, profile, len);
1125             if (FAILED(hr))
1126             {
1127                 LeaveCriticalSection(&This->parent->lock);
1128                 return hr;
1129             }
1130         }
1131         *pcActualCount = 1;
1132     }
1133     else
1134         *pcActualCount = 0;
1135
1136     LeaveCriticalSection(&This->parent->lock);
1137
1138     return S_OK;
1139 }
1140
1141 static HRESULT WINAPI TiffFrameDecode_GetThumbnail(IWICBitmapFrameDecode *iface,
1142     IWICBitmapSource **ppIThumbnail)
1143 {
1144     TRACE("(%p,%p)\n", iface, ppIThumbnail);
1145
1146     if (!ppIThumbnail) return E_INVALIDARG;
1147
1148     *ppIThumbnail = NULL;
1149     return WINCODEC_ERR_CODECNOTHUMBNAIL;
1150 }
1151
1152 static const IWICBitmapFrameDecodeVtbl TiffFrameDecode_Vtbl = {
1153     TiffFrameDecode_QueryInterface,
1154     TiffFrameDecode_AddRef,
1155     TiffFrameDecode_Release,
1156     TiffFrameDecode_GetSize,
1157     TiffFrameDecode_GetPixelFormat,
1158     TiffFrameDecode_GetResolution,
1159     TiffFrameDecode_CopyPalette,
1160     TiffFrameDecode_CopyPixels,
1161     TiffFrameDecode_GetMetadataQueryReader,
1162     TiffFrameDecode_GetColorContexts,
1163     TiffFrameDecode_GetThumbnail
1164 };
1165
1166 static HRESULT WINAPI TiffFrameDecode_Block_QueryInterface(IWICMetadataBlockReader *iface,
1167     REFIID iid, void **ppv)
1168 {
1169     TiffFrameDecode *This = impl_from_IWICMetadataBlockReader(iface);
1170     return IWICBitmapFrameDecode_QueryInterface(&This->IWICBitmapFrameDecode_iface, iid, ppv);
1171 }
1172
1173 static ULONG WINAPI TiffFrameDecode_Block_AddRef(IWICMetadataBlockReader *iface)
1174 {
1175     TiffFrameDecode *This = impl_from_IWICMetadataBlockReader(iface);
1176     return IWICBitmapFrameDecode_AddRef(&This->IWICBitmapFrameDecode_iface);
1177 }
1178
1179 static ULONG WINAPI TiffFrameDecode_Block_Release(IWICMetadataBlockReader *iface)
1180 {
1181     TiffFrameDecode *This = impl_from_IWICMetadataBlockReader(iface);
1182     return IWICBitmapFrameDecode_Release(&This->IWICBitmapFrameDecode_iface);
1183 }
1184
1185 static HRESULT WINAPI TiffFrameDecode_Block_GetContainerFormat(IWICMetadataBlockReader *iface,
1186     GUID *guid)
1187 {
1188     TRACE("(%p,%p)\n", iface, guid);
1189
1190     if (!guid) return E_INVALIDARG;
1191
1192     *guid = GUID_ContainerFormatTiff;
1193     return S_OK;
1194 }
1195
1196 static HRESULT WINAPI TiffFrameDecode_Block_GetCount(IWICMetadataBlockReader *iface,
1197     UINT *count)
1198 {
1199     TRACE("%p,%p\n", iface, count);
1200
1201     if (!count) return E_INVALIDARG;
1202
1203     *count = 1;
1204     return S_OK;
1205 }
1206
1207 static HRESULT create_metadata_reader(TiffFrameDecode *This, IWICMetadataReader **reader)
1208 {
1209     HRESULT hr;
1210     LARGE_INTEGER dir_offset;
1211     IWICMetadataReader *metadata_reader;
1212     IWICPersistStream *persist;
1213
1214     /* FIXME: Use IWICComponentFactory_CreateMetadataReader once it's implemented */
1215
1216     hr = CoCreateInstance(&CLSID_WICIfdMetadataReader, NULL, CLSCTX_INPROC_SERVER,
1217                           &IID_IWICMetadataReader, (void **)&metadata_reader);
1218     if (FAILED(hr)) return hr;
1219
1220     hr = IWICMetadataReader_QueryInterface(metadata_reader, &IID_IWICPersistStream, (void **)&persist);
1221     if (FAILED(hr))
1222     {
1223         IWICMetadataReader_Release(metadata_reader);
1224         return hr;
1225     }
1226
1227     EnterCriticalSection(&This->parent->lock);
1228
1229     dir_offset.QuadPart = pTIFFCurrentDirOffset(This->parent->tiff);
1230     hr = IStream_Seek(This->parent->stream, dir_offset, STREAM_SEEK_SET, NULL);
1231     if (SUCCEEDED(hr))
1232     {
1233         BOOL byte_swapped = pTIFFIsByteSwapped(This->parent->tiff);
1234 #ifdef WORDS_BIGENDIAN
1235         DWORD persist_options = byte_swapped ? WICPersistOptionsLittleEndian : WICPersistOptionsBigEndian;
1236 #else
1237         DWORD persist_options = byte_swapped ? WICPersistOptionsBigEndian : WICPersistOptionsLittleEndian;
1238 #endif
1239         persist_options |= WICPersistOptionsNoCacheStream;
1240         hr = IWICPersistStream_LoadEx(persist, This->parent->stream, NULL, persist_options);
1241         if (FAILED(hr))
1242             ERR("IWICPersistStream_LoadEx error %#x\n", hr);
1243     }
1244
1245     LeaveCriticalSection(&This->parent->lock);
1246
1247     IWICPersistStream_Release(persist);
1248
1249     if (FAILED(hr))
1250     {
1251         IWICMetadataReader_Release(metadata_reader);
1252         return hr;
1253     }
1254
1255     *reader = metadata_reader;
1256     return S_OK;
1257 }
1258
1259 static HRESULT WINAPI TiffFrameDecode_Block_GetReaderByIndex(IWICMetadataBlockReader *iface,
1260     UINT index, IWICMetadataReader **reader)
1261 {
1262     TiffFrameDecode *This = impl_from_IWICMetadataBlockReader(iface);
1263
1264     TRACE("(%p,%u,%p)\n", iface, index, reader);
1265
1266     if (!reader || index != 0) return E_INVALIDARG;
1267
1268     return create_metadata_reader(This, reader);
1269 }
1270
1271 static HRESULT WINAPI TiffFrameDecode_Block_GetEnumerator(IWICMetadataBlockReader *iface,
1272     IEnumUnknown **enum_metadata)
1273 {
1274     FIXME("(%p,%p): stub\n", iface, enum_metadata);
1275     return E_NOTIMPL;
1276 }
1277
1278 static const IWICMetadataBlockReaderVtbl TiffFrameDecode_BlockVtbl =
1279 {
1280     TiffFrameDecode_Block_QueryInterface,
1281     TiffFrameDecode_Block_AddRef,
1282     TiffFrameDecode_Block_Release,
1283     TiffFrameDecode_Block_GetContainerFormat,
1284     TiffFrameDecode_Block_GetCount,
1285     TiffFrameDecode_Block_GetReaderByIndex,
1286     TiffFrameDecode_Block_GetEnumerator
1287 };
1288
1289 HRESULT TiffDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
1290 {
1291     HRESULT ret;
1292     TiffDecoder *This;
1293
1294     TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);
1295
1296     *ppv = NULL;
1297
1298     if (pUnkOuter) return CLASS_E_NOAGGREGATION;
1299
1300     if (!load_libtiff())
1301     {
1302         ERR("Failed reading TIFF because unable to load %s\n",SONAME_LIBTIFF);
1303         return E_FAIL;
1304     }
1305
1306     This = HeapAlloc(GetProcessHeap(), 0, sizeof(TiffDecoder));
1307     if (!This) return E_OUTOFMEMORY;
1308
1309     This->IWICBitmapDecoder_iface.lpVtbl = &TiffDecoder_Vtbl;
1310     This->ref = 1;
1311     This->stream = NULL;
1312     InitializeCriticalSection(&This->lock);
1313     This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": TiffDecoder.lock");
1314     This->tiff = NULL;
1315     This->initialized = FALSE;
1316
1317     ret = IWICBitmapDecoder_QueryInterface(&This->IWICBitmapDecoder_iface, iid, ppv);
1318     IWICBitmapDecoder_Release(&This->IWICBitmapDecoder_iface);
1319
1320     return ret;
1321 }
1322
1323 struct tiff_encode_format {
1324     const WICPixelFormatGUID *guid;
1325     int photometric;
1326     int bps;
1327     int samples;
1328     int bpp;
1329     int extra_sample;
1330     int extra_sample_type;
1331     int reverse_bgr;
1332 };
1333
1334 static const struct tiff_encode_format formats[] = {
1335     {&GUID_WICPixelFormat24bppBGR, 2, 8, 3, 24, 0, 0, 1},
1336     {&GUID_WICPixelFormat24bppRGB, 2, 8, 3, 24, 0, 0, 0},
1337     {&GUID_WICPixelFormatBlackWhite, 1, 1, 1, 1, 0, 0, 0},
1338     {&GUID_WICPixelFormat4bppGray, 1, 4, 1, 4, 0, 0, 0},
1339     {&GUID_WICPixelFormat8bppGray, 1, 8, 1, 8, 0, 0, 0},
1340     {&GUID_WICPixelFormat32bppBGRA, 2, 8, 4, 32, 1, 2, 1},
1341     {&GUID_WICPixelFormat32bppPBGRA, 2, 8, 4, 32, 1, 1, 1},
1342     {&GUID_WICPixelFormat48bppRGB, 2, 16, 3, 48, 0, 0, 0},
1343     {&GUID_WICPixelFormat64bppRGBA, 2, 16, 4, 64, 1, 2, 0},
1344     {&GUID_WICPixelFormat64bppPRGBA, 2, 16, 4, 64, 1, 1, 0},
1345     {0}
1346 };
1347
1348 typedef struct TiffEncoder {
1349     IWICBitmapEncoder IWICBitmapEncoder_iface;
1350     LONG ref;
1351     IStream *stream;
1352     CRITICAL_SECTION lock; /* Must be held when tiff is used or fields below are set */
1353     TIFF *tiff;
1354     BOOL initialized;
1355     BOOL committed;
1356     ULONG num_frames;
1357     ULONG num_frames_committed;
1358 } TiffEncoder;
1359
1360 static inline TiffEncoder *impl_from_IWICBitmapEncoder(IWICBitmapEncoder *iface)
1361 {
1362     return CONTAINING_RECORD(iface, TiffEncoder, IWICBitmapEncoder_iface);
1363 }
1364
1365 typedef struct TiffFrameEncode {
1366     IWICBitmapFrameEncode IWICBitmapFrameEncode_iface;
1367     LONG ref;
1368     TiffEncoder *parent;
1369     /* fields below are protected by parent->lock */
1370     BOOL initialized;
1371     BOOL info_written;
1372     BOOL committed;
1373     const struct tiff_encode_format *format;
1374     UINT width, height;
1375     double xres, yres;
1376     UINT lines_written;
1377 } TiffFrameEncode;
1378
1379 static inline TiffFrameEncode *impl_from_IWICBitmapFrameEncode(IWICBitmapFrameEncode *iface)
1380 {
1381     return CONTAINING_RECORD(iface, TiffFrameEncode, IWICBitmapFrameEncode_iface);
1382 }
1383
1384 static HRESULT WINAPI TiffFrameEncode_QueryInterface(IWICBitmapFrameEncode *iface, REFIID iid,
1385     void **ppv)
1386 {
1387     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1388     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
1389
1390     if (!ppv) return E_INVALIDARG;
1391
1392     if (IsEqualIID(&IID_IUnknown, iid) ||
1393         IsEqualIID(&IID_IWICBitmapFrameEncode, iid))
1394     {
1395         *ppv = &This->IWICBitmapFrameEncode_iface;
1396     }
1397     else
1398     {
1399         *ppv = NULL;
1400         return E_NOINTERFACE;
1401     }
1402
1403     IUnknown_AddRef((IUnknown*)*ppv);
1404     return S_OK;
1405 }
1406
1407 static ULONG WINAPI TiffFrameEncode_AddRef(IWICBitmapFrameEncode *iface)
1408 {
1409     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1410     ULONG ref = InterlockedIncrement(&This->ref);
1411
1412     TRACE("(%p) refcount=%u\n", iface, ref);
1413
1414     return ref;
1415 }
1416
1417 static ULONG WINAPI TiffFrameEncode_Release(IWICBitmapFrameEncode *iface)
1418 {
1419     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1420     ULONG ref = InterlockedDecrement(&This->ref);
1421
1422     TRACE("(%p) refcount=%u\n", iface, ref);
1423
1424     if (ref == 0)
1425     {
1426         IWICBitmapEncoder_Release(&This->parent->IWICBitmapEncoder_iface);
1427         HeapFree(GetProcessHeap(), 0, This);
1428     }
1429
1430     return ref;
1431 }
1432
1433 static HRESULT WINAPI TiffFrameEncode_Initialize(IWICBitmapFrameEncode *iface,
1434     IPropertyBag2 *pIEncoderOptions)
1435 {
1436     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1437     TRACE("(%p,%p)\n", iface, pIEncoderOptions);
1438
1439     EnterCriticalSection(&This->parent->lock);
1440
1441     if (This->initialized)
1442     {
1443         LeaveCriticalSection(&This->parent->lock);
1444         return WINCODEC_ERR_WRONGSTATE;
1445     }
1446
1447     This->initialized = TRUE;
1448
1449     LeaveCriticalSection(&This->parent->lock);
1450
1451     return S_OK;
1452 }
1453
1454 static HRESULT WINAPI TiffFrameEncode_SetSize(IWICBitmapFrameEncode *iface,
1455     UINT uiWidth, UINT uiHeight)
1456 {
1457     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1458     TRACE("(%p,%u,%u)\n", iface, uiWidth, uiHeight);
1459
1460     EnterCriticalSection(&This->parent->lock);
1461
1462     if (!This->initialized || This->info_written)
1463     {
1464         LeaveCriticalSection(&This->parent->lock);
1465         return WINCODEC_ERR_WRONGSTATE;
1466     }
1467
1468     This->width = uiWidth;
1469     This->height = uiHeight;
1470
1471     LeaveCriticalSection(&This->parent->lock);
1472
1473     return S_OK;
1474 }
1475
1476 static HRESULT WINAPI TiffFrameEncode_SetResolution(IWICBitmapFrameEncode *iface,
1477     double dpiX, double dpiY)
1478 {
1479     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1480     TRACE("(%p,%0.2f,%0.2f)\n", iface, dpiX, dpiY);
1481
1482     EnterCriticalSection(&This->parent->lock);
1483
1484     if (!This->initialized || This->info_written)
1485     {
1486         LeaveCriticalSection(&This->parent->lock);
1487         return WINCODEC_ERR_WRONGSTATE;
1488     }
1489
1490     This->xres = dpiX;
1491     This->yres = dpiY;
1492
1493     LeaveCriticalSection(&This->parent->lock);
1494
1495     return S_OK;
1496 }
1497
1498 static HRESULT WINAPI TiffFrameEncode_SetPixelFormat(IWICBitmapFrameEncode *iface,
1499     WICPixelFormatGUID *pPixelFormat)
1500 {
1501     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1502     int i;
1503
1504     TRACE("(%p,%s)\n", iface, debugstr_guid(pPixelFormat));
1505
1506     EnterCriticalSection(&This->parent->lock);
1507
1508     if (!This->initialized || This->info_written)
1509     {
1510         LeaveCriticalSection(&This->parent->lock);
1511         return WINCODEC_ERR_WRONGSTATE;
1512     }
1513
1514     for (i=0; formats[i].guid; i++)
1515     {
1516         if (memcmp(formats[i].guid, pPixelFormat, sizeof(GUID)) == 0)
1517             break;
1518     }
1519
1520     if (!formats[i].guid) i = 0;
1521
1522     This->format = &formats[i];
1523     memcpy(pPixelFormat, This->format->guid, sizeof(GUID));
1524
1525     LeaveCriticalSection(&This->parent->lock);
1526
1527     return S_OK;
1528 }
1529
1530 static HRESULT WINAPI TiffFrameEncode_SetColorContexts(IWICBitmapFrameEncode *iface,
1531     UINT cCount, IWICColorContext **ppIColorContext)
1532 {
1533     FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
1534     return E_NOTIMPL;
1535 }
1536
1537 static HRESULT WINAPI TiffFrameEncode_SetPalette(IWICBitmapFrameEncode *iface,
1538     IWICPalette *pIPalette)
1539 {
1540     FIXME("(%p,%p): stub\n", iface, pIPalette);
1541     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1542 }
1543
1544 static HRESULT WINAPI TiffFrameEncode_SetThumbnail(IWICBitmapFrameEncode *iface,
1545     IWICBitmapSource *pIThumbnail)
1546 {
1547     FIXME("(%p,%p): stub\n", iface, pIThumbnail);
1548     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1549 }
1550
1551 static HRESULT WINAPI TiffFrameEncode_WritePixels(IWICBitmapFrameEncode *iface,
1552     UINT lineCount, UINT cbStride, UINT cbBufferSize, BYTE *pbPixels)
1553 {
1554     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1555     BYTE *row_data, *swapped_data = NULL;
1556     UINT i, j, line_size;
1557
1558     TRACE("(%p,%u,%u,%u,%p)\n", iface, lineCount, cbStride, cbBufferSize, pbPixels);
1559
1560     EnterCriticalSection(&This->parent->lock);
1561
1562     if (!This->initialized || !This->width || !This->height || !This->format)
1563     {
1564         LeaveCriticalSection(&This->parent->lock);
1565         return WINCODEC_ERR_WRONGSTATE;
1566     }
1567
1568     if (lineCount == 0 || lineCount + This->lines_written > This->height)
1569     {
1570         LeaveCriticalSection(&This->parent->lock);
1571         return E_INVALIDARG;
1572     }
1573
1574     line_size = ((This->width * This->format->bpp)+7)/8;
1575
1576     if (This->format->reverse_bgr)
1577     {
1578         swapped_data = HeapAlloc(GetProcessHeap(), 0, line_size);
1579         if (!swapped_data)
1580         {
1581             LeaveCriticalSection(&This->parent->lock);
1582             return E_OUTOFMEMORY;
1583         }
1584     }
1585
1586     if (!This->info_written)
1587     {
1588         pTIFFSetField(This->parent->tiff, TIFFTAG_PHOTOMETRIC, (uint16)This->format->photometric);
1589         pTIFFSetField(This->parent->tiff, TIFFTAG_PLANARCONFIG, (uint16)1);
1590         pTIFFSetField(This->parent->tiff, TIFFTAG_BITSPERSAMPLE, (uint16)This->format->bps);
1591         pTIFFSetField(This->parent->tiff, TIFFTAG_SAMPLESPERPIXEL, (uint16)This->format->samples);
1592
1593         if (This->format->extra_sample)
1594         {
1595             uint16 extra_samples;
1596             extra_samples = This->format->extra_sample_type;
1597
1598             pTIFFSetField(This->parent->tiff, TIFFTAG_EXTRASAMPLES, (uint16)1, &extra_samples);
1599         }
1600
1601         pTIFFSetField(This->parent->tiff, TIFFTAG_IMAGEWIDTH, (uint32)This->width);
1602         pTIFFSetField(This->parent->tiff, TIFFTAG_IMAGELENGTH, (uint32)This->height);
1603
1604         if (This->xres != 0.0 && This->yres != 0.0)
1605         {
1606             pTIFFSetField(This->parent->tiff, TIFFTAG_RESOLUTIONUNIT, (uint16)2); /* Inch */
1607             pTIFFSetField(This->parent->tiff, TIFFTAG_XRESOLUTION, (float)This->xres);
1608             pTIFFSetField(This->parent->tiff, TIFFTAG_YRESOLUTION, (float)This->yres);
1609         }
1610
1611         This->info_written = TRUE;
1612     }
1613
1614     for (i=0; i<lineCount; i++)
1615     {
1616         row_data = pbPixels + i * cbStride;
1617
1618         if (This->format->reverse_bgr && This->format->bps == 8)
1619         {
1620             memcpy(swapped_data, row_data, line_size);
1621             for (j=0; j<line_size; j += This->format->samples)
1622             {
1623                 BYTE temp;
1624                 temp = swapped_data[j];
1625                 swapped_data[j] = swapped_data[j+2];
1626                 swapped_data[j+2] = temp;
1627             }
1628             row_data = swapped_data;
1629         }
1630
1631         pTIFFWriteScanline(This->parent->tiff, (tdata_t)row_data, i+This->lines_written, 0);
1632     }
1633
1634     This->lines_written += lineCount;
1635
1636     LeaveCriticalSection(&This->parent->lock);
1637
1638     HeapFree(GetProcessHeap(), 0, swapped_data);
1639
1640     return S_OK;
1641 }
1642
1643 static HRESULT WINAPI TiffFrameEncode_WriteSource(IWICBitmapFrameEncode *iface,
1644     IWICBitmapSource *pIBitmapSource, WICRect *prc)
1645 {
1646     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1647     HRESULT hr;
1648     WICRect rc;
1649     WICPixelFormatGUID guid;
1650     UINT stride;
1651     BYTE *pixeldata;
1652
1653     TRACE("(%p,%p,%p)\n", iface, pIBitmapSource, prc);
1654
1655     if (!This->initialized || !This->width || !This->height)
1656         return WINCODEC_ERR_WRONGSTATE;
1657
1658     if (!This->format)
1659     {
1660         hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
1661         if (FAILED(hr)) return hr;
1662         hr = IWICBitmapFrameEncode_SetPixelFormat(iface, &guid);
1663         if (FAILED(hr)) return hr;
1664     }
1665
1666     hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
1667     if (FAILED(hr)) return hr;
1668     if (memcmp(&guid, This->format->guid, sizeof(GUID)) != 0)
1669     {
1670         /* FIXME: should use WICConvertBitmapSource to convert */
1671         ERR("format %s unsupported\n", debugstr_guid(&guid));
1672         return E_FAIL;
1673     }
1674
1675     if (This->xres == 0.0 || This->yres == 0.0)
1676     {
1677         double xres, yres;
1678         hr = IWICBitmapSource_GetResolution(pIBitmapSource, &xres, &yres);
1679         if (FAILED(hr)) return hr;
1680         hr = IWICBitmapFrameEncode_SetResolution(iface, xres, yres);
1681         if (FAILED(hr)) return hr;
1682     }
1683
1684     if (!prc)
1685     {
1686         UINT width, height;
1687         hr = IWICBitmapSource_GetSize(pIBitmapSource, &width, &height);
1688         if (FAILED(hr)) return hr;
1689         rc.X = 0;
1690         rc.Y = 0;
1691         rc.Width = width;
1692         rc.Height = height;
1693         prc = &rc;
1694     }
1695
1696     if (prc->Width != This->width) return E_INVALIDARG;
1697
1698     stride = (This->format->bpp * This->width + 7)/8;
1699
1700     pixeldata = HeapAlloc(GetProcessHeap(), 0, stride * prc->Height);
1701     if (!pixeldata) return E_OUTOFMEMORY;
1702
1703     hr = IWICBitmapSource_CopyPixels(pIBitmapSource, prc, stride,
1704         stride*prc->Height, pixeldata);
1705
1706     if (SUCCEEDED(hr))
1707     {
1708         hr = IWICBitmapFrameEncode_WritePixels(iface, prc->Height, stride,
1709             stride*prc->Height, pixeldata);
1710     }
1711
1712     HeapFree(GetProcessHeap(), 0, pixeldata);
1713
1714     return S_OK;
1715 }
1716
1717 static HRESULT WINAPI TiffFrameEncode_Commit(IWICBitmapFrameEncode *iface)
1718 {
1719     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1720
1721     TRACE("(%p)\n", iface);
1722
1723     EnterCriticalSection(&This->parent->lock);
1724
1725     if (!This->info_written || This->lines_written != This->height || This->committed)
1726     {
1727         LeaveCriticalSection(&This->parent->lock);
1728         return WINCODEC_ERR_WRONGSTATE;
1729     }
1730
1731     /* libtiff will commit the data when creating a new frame or closing the file */
1732
1733     This->committed = TRUE;
1734     This->parent->num_frames_committed++;
1735
1736     LeaveCriticalSection(&This->parent->lock);
1737
1738     return S_OK;
1739 }
1740
1741 static HRESULT WINAPI TiffFrameEncode_GetMetadataQueryWriter(IWICBitmapFrameEncode *iface,
1742     IWICMetadataQueryWriter **ppIMetadataQueryWriter)
1743 {
1744     FIXME("(%p, %p): stub\n", iface, ppIMetadataQueryWriter);
1745     return E_NOTIMPL;
1746 }
1747
1748 static const IWICBitmapFrameEncodeVtbl TiffFrameEncode_Vtbl = {
1749     TiffFrameEncode_QueryInterface,
1750     TiffFrameEncode_AddRef,
1751     TiffFrameEncode_Release,
1752     TiffFrameEncode_Initialize,
1753     TiffFrameEncode_SetSize,
1754     TiffFrameEncode_SetResolution,
1755     TiffFrameEncode_SetPixelFormat,
1756     TiffFrameEncode_SetColorContexts,
1757     TiffFrameEncode_SetPalette,
1758     TiffFrameEncode_SetThumbnail,
1759     TiffFrameEncode_WritePixels,
1760     TiffFrameEncode_WriteSource,
1761     TiffFrameEncode_Commit,
1762     TiffFrameEncode_GetMetadataQueryWriter
1763 };
1764
1765 static HRESULT WINAPI TiffEncoder_QueryInterface(IWICBitmapEncoder *iface, REFIID iid,
1766     void **ppv)
1767 {
1768     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1769     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
1770
1771     if (!ppv) return E_INVALIDARG;
1772
1773     if (IsEqualIID(&IID_IUnknown, iid) ||
1774         IsEqualIID(&IID_IWICBitmapEncoder, iid))
1775     {
1776         *ppv = &This->IWICBitmapEncoder_iface;
1777     }
1778     else
1779     {
1780         *ppv = NULL;
1781         return E_NOINTERFACE;
1782     }
1783
1784     IUnknown_AddRef((IUnknown*)*ppv);
1785     return S_OK;
1786 }
1787
1788 static ULONG WINAPI TiffEncoder_AddRef(IWICBitmapEncoder *iface)
1789 {
1790     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1791     ULONG ref = InterlockedIncrement(&This->ref);
1792
1793     TRACE("(%p) refcount=%u\n", iface, ref);
1794
1795     return ref;
1796 }
1797
1798 static ULONG WINAPI TiffEncoder_Release(IWICBitmapEncoder *iface)
1799 {
1800     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1801     ULONG ref = InterlockedDecrement(&This->ref);
1802
1803     TRACE("(%p) refcount=%u\n", iface, ref);
1804
1805     if (ref == 0)
1806     {
1807         if (This->tiff) pTIFFClose(This->tiff);
1808         if (This->stream) IStream_Release(This->stream);
1809         This->lock.DebugInfo->Spare[0] = 0;
1810         DeleteCriticalSection(&This->lock);
1811         HeapFree(GetProcessHeap(), 0, This);
1812     }
1813
1814     return ref;
1815 }
1816
1817 static HRESULT WINAPI TiffEncoder_Initialize(IWICBitmapEncoder *iface,
1818     IStream *pIStream, WICBitmapEncoderCacheOption cacheOption)
1819 {
1820     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1821     TIFF *tiff;
1822     HRESULT hr=S_OK;
1823
1824     TRACE("(%p,%p,%u)\n", iface, pIStream, cacheOption);
1825
1826     EnterCriticalSection(&This->lock);
1827
1828     if (This->initialized || This->committed)
1829     {
1830         hr = WINCODEC_ERR_WRONGSTATE;
1831         goto exit;
1832     }
1833
1834     tiff = tiff_open_stream(pIStream, "w");
1835
1836     if (!tiff)
1837     {
1838         hr = E_FAIL;
1839         goto exit;
1840     }
1841
1842     This->tiff = tiff;
1843     This->stream = pIStream;
1844     IStream_AddRef(pIStream);
1845     This->initialized = TRUE;
1846
1847 exit:
1848     LeaveCriticalSection(&This->lock);
1849     return hr;
1850 }
1851
1852 static HRESULT WINAPI TiffEncoder_GetContainerFormat(IWICBitmapEncoder *iface,
1853     GUID *pguidContainerFormat)
1854 {
1855     memcpy(pguidContainerFormat, &GUID_ContainerFormatTiff, sizeof(GUID));
1856     return S_OK;
1857 }
1858
1859 static HRESULT WINAPI TiffEncoder_GetEncoderInfo(IWICBitmapEncoder *iface,
1860     IWICBitmapEncoderInfo **ppIEncoderInfo)
1861 {
1862     FIXME("(%p,%p): stub\n", iface, ppIEncoderInfo);
1863     return E_NOTIMPL;
1864 }
1865
1866 static HRESULT WINAPI TiffEncoder_SetColorContexts(IWICBitmapEncoder *iface,
1867     UINT cCount, IWICColorContext **ppIColorContext)
1868 {
1869     FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
1870     return E_NOTIMPL;
1871 }
1872
1873 static HRESULT WINAPI TiffEncoder_SetPalette(IWICBitmapEncoder *iface, IWICPalette *pIPalette)
1874 {
1875     TRACE("(%p,%p)\n", iface, pIPalette);
1876     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1877 }
1878
1879 static HRESULT WINAPI TiffEncoder_SetThumbnail(IWICBitmapEncoder *iface, IWICBitmapSource *pIThumbnail)
1880 {
1881     TRACE("(%p,%p)\n", iface, pIThumbnail);
1882     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1883 }
1884
1885 static HRESULT WINAPI TiffEncoder_SetPreview(IWICBitmapEncoder *iface, IWICBitmapSource *pIPreview)
1886 {
1887     TRACE("(%p,%p)\n", iface, pIPreview);
1888     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1889 }
1890
1891 static HRESULT WINAPI TiffEncoder_CreateNewFrame(IWICBitmapEncoder *iface,
1892     IWICBitmapFrameEncode **ppIFrameEncode, IPropertyBag2 **ppIEncoderOptions)
1893 {
1894     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1895     TiffFrameEncode *result;
1896
1897     HRESULT hr=S_OK;
1898
1899     TRACE("(%p,%p,%p)\n", iface, ppIFrameEncode, ppIEncoderOptions);
1900
1901     EnterCriticalSection(&This->lock);
1902
1903     if (!This->initialized || This->committed)
1904     {
1905         hr = WINCODEC_ERR_WRONGSTATE;
1906     }
1907     else if (This->num_frames != This->num_frames_committed)
1908     {
1909         FIXME("New frame created before previous frame was committed\n");
1910         hr = E_FAIL;
1911     }
1912
1913     if (SUCCEEDED(hr))
1914     {
1915         PROPBAG2 opts[2]= {{0}};
1916         opts[0].pstrName = (LPOLESTR)wszTiffCompressionMethod;
1917         opts[0].vt = VT_UI1;
1918         opts[0].dwType = PROPBAG2_TYPE_DATA;
1919
1920         opts[1].pstrName = (LPOLESTR)wszCompressionQuality;
1921         opts[1].vt = VT_R4;
1922         opts[1].dwType = PROPBAG2_TYPE_DATA;
1923
1924         hr = CreatePropertyBag2(opts, 2, ppIEncoderOptions);
1925
1926         if (SUCCEEDED(hr))
1927         {
1928             VARIANT v;
1929             VariantInit(&v);
1930             V_VT(&v) = VT_UI1;
1931             V_UNION(&v, bVal) = WICTiffCompressionDontCare;
1932             hr = IPropertyBag2_Write(*ppIEncoderOptions, 1, opts, &v);
1933             VariantClear(&v);
1934             if (FAILED(hr))
1935             {
1936                 IPropertyBag2_Release(*ppIEncoderOptions);
1937                 *ppIEncoderOptions = NULL;
1938             }
1939         }
1940     }
1941
1942     if (SUCCEEDED(hr))
1943     {
1944         result = HeapAlloc(GetProcessHeap(), 0, sizeof(*result));
1945
1946         if (result)
1947         {
1948             result->IWICBitmapFrameEncode_iface.lpVtbl = &TiffFrameEncode_Vtbl;
1949             result->ref = 1;
1950             result->parent = This;
1951             result->initialized = FALSE;
1952             result->info_written = FALSE;
1953             result->committed = FALSE;
1954             result->format = NULL;
1955             result->width = 0;
1956             result->height = 0;
1957             result->xres = 0.0;
1958             result->yres = 0.0;
1959             result->lines_written = 0;
1960
1961             IWICBitmapEncoder_AddRef(iface);
1962             *ppIFrameEncode = &result->IWICBitmapFrameEncode_iface;
1963
1964             if (This->num_frames != 0)
1965                 pTIFFWriteDirectory(This->tiff);
1966
1967             This->num_frames++;
1968         }
1969         else
1970             hr = E_OUTOFMEMORY;
1971
1972         if (FAILED(hr))
1973         {
1974             IPropertyBag2_Release(*ppIEncoderOptions);
1975             *ppIEncoderOptions = NULL;
1976         }
1977     }
1978
1979     LeaveCriticalSection(&This->lock);
1980
1981     return hr;
1982 }
1983
1984 static HRESULT WINAPI TiffEncoder_Commit(IWICBitmapEncoder *iface)
1985 {
1986     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1987
1988     TRACE("(%p)\n", iface);
1989
1990     EnterCriticalSection(&This->lock);
1991
1992     if (!This->initialized || This->committed)
1993     {
1994         LeaveCriticalSection(&This->lock);
1995         return WINCODEC_ERR_WRONGSTATE;
1996     }
1997
1998     pTIFFClose(This->tiff);
1999     IStream_Release(This->stream);
2000     This->stream = NULL;
2001     This->tiff = NULL;
2002
2003     This->committed = TRUE;
2004
2005     LeaveCriticalSection(&This->lock);
2006
2007     return S_OK;
2008 }
2009
2010 static HRESULT WINAPI TiffEncoder_GetMetadataQueryWriter(IWICBitmapEncoder *iface,
2011     IWICMetadataQueryWriter **ppIMetadataQueryWriter)
2012 {
2013     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryWriter);
2014     return E_NOTIMPL;
2015 }
2016
2017 static const IWICBitmapEncoderVtbl TiffEncoder_Vtbl = {
2018     TiffEncoder_QueryInterface,
2019     TiffEncoder_AddRef,
2020     TiffEncoder_Release,
2021     TiffEncoder_Initialize,
2022     TiffEncoder_GetContainerFormat,
2023     TiffEncoder_GetEncoderInfo,
2024     TiffEncoder_SetColorContexts,
2025     TiffEncoder_SetPalette,
2026     TiffEncoder_SetThumbnail,
2027     TiffEncoder_SetPreview,
2028     TiffEncoder_CreateNewFrame,
2029     TiffEncoder_Commit,
2030     TiffEncoder_GetMetadataQueryWriter
2031 };
2032
2033 HRESULT TiffEncoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
2034 {
2035     TiffEncoder *This;
2036     HRESULT ret;
2037
2038     TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);
2039
2040     *ppv = NULL;
2041
2042     if (pUnkOuter) return CLASS_E_NOAGGREGATION;
2043
2044     if (!load_libtiff())
2045     {
2046         ERR("Failed writing TIFF because unable to load %s\n",SONAME_LIBTIFF);
2047         return E_FAIL;
2048     }
2049
2050     This = HeapAlloc(GetProcessHeap(), 0, sizeof(TiffEncoder));
2051     if (!This) return E_OUTOFMEMORY;
2052
2053     This->IWICBitmapEncoder_iface.lpVtbl = &TiffEncoder_Vtbl;
2054     This->ref = 1;
2055     This->stream = NULL;
2056     InitializeCriticalSection(&This->lock);
2057     This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": TiffEncoder.lock");
2058     This->tiff = NULL;
2059     This->initialized = FALSE;
2060     This->num_frames = 0;
2061     This->num_frames_committed = 0;
2062     This->committed = FALSE;
2063
2064     ret = IWICBitmapEncoder_QueryInterface(&This->IWICBitmapEncoder_iface, iid, ppv);
2065     IWICBitmapEncoder_Release(&This->IWICBitmapEncoder_iface);
2066
2067     return ret;
2068 }
2069
2070 #else /* !SONAME_LIBTIFF */
2071
2072 HRESULT TiffDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
2073 {
2074     ERR("Trying to load TIFF picture, but Wine was compiled without TIFF support.\n");
2075     return E_FAIL;
2076 }
2077
2078 HRESULT TiffEncoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
2079 {
2080     ERR("Trying to save TIFF picture, but Wine was compiled without TIFF support.\n");
2081     return E_FAIL;
2082 }
2083
2084 #endif