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