windowscodecs: Don't copy extra data from the end of a row.
[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_WICPixelFormat24bppRGB, 2, 8, 3, 24, 0, 0, 0},
1308     {&GUID_WICPixelFormatBlackWhite, 1, 1, 1, 1, 0, 0, 0},
1309     {&GUID_WICPixelFormat4bppGray, 1, 4, 1, 4, 0, 0, 0},
1310     {&GUID_WICPixelFormat8bppGray, 1, 8, 1, 8, 0, 0, 0},
1311     {&GUID_WICPixelFormat32bppBGRA, 2, 8, 4, 32, 1, 2, 1},
1312     {&GUID_WICPixelFormat32bppPBGRA, 2, 8, 4, 32, 1, 1, 1},
1313     {&GUID_WICPixelFormat48bppRGB, 2, 16, 3, 48, 0, 0, 0},
1314     {&GUID_WICPixelFormat64bppRGBA, 2, 16, 4, 64, 1, 2, 0},
1315     {&GUID_WICPixelFormat64bppPRGBA, 2, 16, 4, 64, 1, 1, 0},
1316     {0}
1317 };
1318
1319 typedef struct TiffEncoder {
1320     IWICBitmapEncoder IWICBitmapEncoder_iface;
1321     LONG ref;
1322     IStream *stream;
1323     CRITICAL_SECTION lock; /* Must be held when tiff is used or fields below are set */
1324     TIFF *tiff;
1325     BOOL initialized;
1326     BOOL committed;
1327     ULONG num_frames;
1328     ULONG num_frames_committed;
1329 } TiffEncoder;
1330
1331 static inline TiffEncoder *impl_from_IWICBitmapEncoder(IWICBitmapEncoder *iface)
1332 {
1333     return CONTAINING_RECORD(iface, TiffEncoder, IWICBitmapEncoder_iface);
1334 }
1335
1336 typedef struct TiffFrameEncode {
1337     IWICBitmapFrameEncode IWICBitmapFrameEncode_iface;
1338     LONG ref;
1339     TiffEncoder *parent;
1340     /* fields below are protected by parent->lock */
1341     BOOL initialized;
1342     BOOL info_written;
1343     BOOL committed;
1344     const struct tiff_encode_format *format;
1345     UINT width, height;
1346     double xres, yres;
1347     UINT lines_written;
1348 } TiffFrameEncode;
1349
1350 static inline TiffFrameEncode *impl_from_IWICBitmapFrameEncode(IWICBitmapFrameEncode *iface)
1351 {
1352     return CONTAINING_RECORD(iface, TiffFrameEncode, IWICBitmapFrameEncode_iface);
1353 }
1354
1355 static HRESULT WINAPI TiffFrameEncode_QueryInterface(IWICBitmapFrameEncode *iface, REFIID iid,
1356     void **ppv)
1357 {
1358     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1359     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
1360
1361     if (!ppv) return E_INVALIDARG;
1362
1363     if (IsEqualIID(&IID_IUnknown, iid) ||
1364         IsEqualIID(&IID_IWICBitmapFrameEncode, iid))
1365     {
1366         *ppv = &This->IWICBitmapFrameEncode_iface;
1367     }
1368     else
1369     {
1370         *ppv = NULL;
1371         return E_NOINTERFACE;
1372     }
1373
1374     IUnknown_AddRef((IUnknown*)*ppv);
1375     return S_OK;
1376 }
1377
1378 static ULONG WINAPI TiffFrameEncode_AddRef(IWICBitmapFrameEncode *iface)
1379 {
1380     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1381     ULONG ref = InterlockedIncrement(&This->ref);
1382
1383     TRACE("(%p) refcount=%u\n", iface, ref);
1384
1385     return ref;
1386 }
1387
1388 static ULONG WINAPI TiffFrameEncode_Release(IWICBitmapFrameEncode *iface)
1389 {
1390     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1391     ULONG ref = InterlockedDecrement(&This->ref);
1392
1393     TRACE("(%p) refcount=%u\n", iface, ref);
1394
1395     if (ref == 0)
1396     {
1397         IWICBitmapEncoder_Release(&This->parent->IWICBitmapEncoder_iface);
1398         HeapFree(GetProcessHeap(), 0, This);
1399     }
1400
1401     return ref;
1402 }
1403
1404 static HRESULT WINAPI TiffFrameEncode_Initialize(IWICBitmapFrameEncode *iface,
1405     IPropertyBag2 *pIEncoderOptions)
1406 {
1407     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1408     TRACE("(%p,%p)\n", iface, pIEncoderOptions);
1409
1410     EnterCriticalSection(&This->parent->lock);
1411
1412     if (This->initialized)
1413     {
1414         LeaveCriticalSection(&This->parent->lock);
1415         return WINCODEC_ERR_WRONGSTATE;
1416     }
1417
1418     This->initialized = TRUE;
1419
1420     LeaveCriticalSection(&This->parent->lock);
1421
1422     return S_OK;
1423 }
1424
1425 static HRESULT WINAPI TiffFrameEncode_SetSize(IWICBitmapFrameEncode *iface,
1426     UINT uiWidth, UINT uiHeight)
1427 {
1428     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1429     TRACE("(%p,%u,%u)\n", iface, uiWidth, uiHeight);
1430
1431     EnterCriticalSection(&This->parent->lock);
1432
1433     if (!This->initialized || This->info_written)
1434     {
1435         LeaveCriticalSection(&This->parent->lock);
1436         return WINCODEC_ERR_WRONGSTATE;
1437     }
1438
1439     This->width = uiWidth;
1440     This->height = uiHeight;
1441
1442     LeaveCriticalSection(&This->parent->lock);
1443
1444     return S_OK;
1445 }
1446
1447 static HRESULT WINAPI TiffFrameEncode_SetResolution(IWICBitmapFrameEncode *iface,
1448     double dpiX, double dpiY)
1449 {
1450     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1451     TRACE("(%p,%0.2f,%0.2f)\n", iface, dpiX, dpiY);
1452
1453     EnterCriticalSection(&This->parent->lock);
1454
1455     if (!This->initialized || This->info_written)
1456     {
1457         LeaveCriticalSection(&This->parent->lock);
1458         return WINCODEC_ERR_WRONGSTATE;
1459     }
1460
1461     This->xres = dpiX;
1462     This->yres = dpiY;
1463
1464     LeaveCriticalSection(&This->parent->lock);
1465
1466     return S_OK;
1467 }
1468
1469 static HRESULT WINAPI TiffFrameEncode_SetPixelFormat(IWICBitmapFrameEncode *iface,
1470     WICPixelFormatGUID *pPixelFormat)
1471 {
1472     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1473     int i;
1474
1475     TRACE("(%p,%s)\n", iface, debugstr_guid(pPixelFormat));
1476
1477     EnterCriticalSection(&This->parent->lock);
1478
1479     if (!This->initialized || This->info_written)
1480     {
1481         LeaveCriticalSection(&This->parent->lock);
1482         return WINCODEC_ERR_WRONGSTATE;
1483     }
1484
1485     for (i=0; formats[i].guid; i++)
1486     {
1487         if (memcmp(formats[i].guid, pPixelFormat, sizeof(GUID)) == 0)
1488             break;
1489     }
1490
1491     if (!formats[i].guid) i = 0;
1492
1493     This->format = &formats[i];
1494     memcpy(pPixelFormat, This->format->guid, sizeof(GUID));
1495
1496     LeaveCriticalSection(&This->parent->lock);
1497
1498     return S_OK;
1499 }
1500
1501 static HRESULT WINAPI TiffFrameEncode_SetColorContexts(IWICBitmapFrameEncode *iface,
1502     UINT cCount, IWICColorContext **ppIColorContext)
1503 {
1504     FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
1505     return E_NOTIMPL;
1506 }
1507
1508 static HRESULT WINAPI TiffFrameEncode_SetPalette(IWICBitmapFrameEncode *iface,
1509     IWICPalette *pIPalette)
1510 {
1511     FIXME("(%p,%p): stub\n", iface, pIPalette);
1512     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1513 }
1514
1515 static HRESULT WINAPI TiffFrameEncode_SetThumbnail(IWICBitmapFrameEncode *iface,
1516     IWICBitmapSource *pIThumbnail)
1517 {
1518     FIXME("(%p,%p): stub\n", iface, pIThumbnail);
1519     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1520 }
1521
1522 static HRESULT WINAPI TiffFrameEncode_WritePixels(IWICBitmapFrameEncode *iface,
1523     UINT lineCount, UINT cbStride, UINT cbBufferSize, BYTE *pbPixels)
1524 {
1525     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1526     BYTE *row_data, *swapped_data = NULL;
1527     UINT i, j, line_size;
1528
1529     TRACE("(%p,%u,%u,%u,%p)\n", iface, lineCount, cbStride, cbBufferSize, pbPixels);
1530
1531     EnterCriticalSection(&This->parent->lock);
1532
1533     if (!This->initialized || !This->width || !This->height || !This->format)
1534     {
1535         LeaveCriticalSection(&This->parent->lock);
1536         return WINCODEC_ERR_WRONGSTATE;
1537     }
1538
1539     if (lineCount == 0 || lineCount + This->lines_written > This->height)
1540     {
1541         LeaveCriticalSection(&This->parent->lock);
1542         return E_INVALIDARG;
1543     }
1544
1545     line_size = ((This->width * This->format->bpp)+7)/8;
1546
1547     if (This->format->reverse_bgr)
1548     {
1549         swapped_data = HeapAlloc(GetProcessHeap(), 0, line_size);
1550         if (!swapped_data)
1551         {
1552             LeaveCriticalSection(&This->parent->lock);
1553             return E_OUTOFMEMORY;
1554         }
1555     }
1556
1557     if (!This->info_written)
1558     {
1559         pTIFFSetField(This->parent->tiff, TIFFTAG_PHOTOMETRIC, (uint16)This->format->photometric);
1560         pTIFFSetField(This->parent->tiff, TIFFTAG_PLANARCONFIG, (uint16)1);
1561         pTIFFSetField(This->parent->tiff, TIFFTAG_BITSPERSAMPLE, (uint16)This->format->bps);
1562         pTIFFSetField(This->parent->tiff, TIFFTAG_SAMPLESPERPIXEL, (uint16)This->format->samples);
1563
1564         if (This->format->extra_sample)
1565         {
1566             uint16 extra_samples;
1567             extra_samples = This->format->extra_sample_type;
1568
1569             pTIFFSetField(This->parent->tiff, TIFFTAG_EXTRASAMPLES, (uint16)1, &extra_samples);
1570         }
1571
1572         pTIFFSetField(This->parent->tiff, TIFFTAG_IMAGEWIDTH, (uint32)This->width);
1573         pTIFFSetField(This->parent->tiff, TIFFTAG_IMAGELENGTH, (uint32)This->height);
1574
1575         if (This->xres != 0.0 && This->yres != 0.0)
1576         {
1577             pTIFFSetField(This->parent->tiff, TIFFTAG_RESOLUTIONUNIT, (uint16)2); /* Inch */
1578             pTIFFSetField(This->parent->tiff, TIFFTAG_XRESOLUTION, (float)This->xres);
1579             pTIFFSetField(This->parent->tiff, TIFFTAG_YRESOLUTION, (float)This->yres);
1580         }
1581
1582         This->info_written = TRUE;
1583     }
1584
1585     for (i=0; i<lineCount; i++)
1586     {
1587         row_data = pbPixels + i * cbStride;
1588
1589         if (This->format->reverse_bgr && This->format->bps == 8)
1590         {
1591             memcpy(swapped_data, row_data, line_size);
1592             for (j=0; j<line_size; j += This->format->samples)
1593             {
1594                 BYTE temp;
1595                 temp = swapped_data[j];
1596                 swapped_data[j] = swapped_data[j+2];
1597                 swapped_data[j+2] = temp;
1598             }
1599             row_data = swapped_data;
1600         }
1601
1602         pTIFFWriteScanline(This->parent->tiff, (tdata_t)row_data, i+This->lines_written, 0);
1603     }
1604
1605     This->lines_written += lineCount;
1606
1607     LeaveCriticalSection(&This->parent->lock);
1608
1609     HeapFree(GetProcessHeap(), 0, swapped_data);
1610
1611     return S_OK;
1612 }
1613
1614 static HRESULT WINAPI TiffFrameEncode_WriteSource(IWICBitmapFrameEncode *iface,
1615     IWICBitmapSource *pIBitmapSource, WICRect *prc)
1616 {
1617     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1618     HRESULT hr;
1619     WICRect rc;
1620     WICPixelFormatGUID guid;
1621     UINT stride;
1622     BYTE *pixeldata;
1623
1624     TRACE("(%p,%p,%p)\n", iface, pIBitmapSource, prc);
1625
1626     if (!This->initialized || !This->width || !This->height)
1627         return WINCODEC_ERR_WRONGSTATE;
1628
1629     if (!This->format)
1630     {
1631         hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
1632         if (FAILED(hr)) return hr;
1633         hr = IWICBitmapFrameEncode_SetPixelFormat(iface, &guid);
1634         if (FAILED(hr)) return hr;
1635     }
1636
1637     hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
1638     if (FAILED(hr)) return hr;
1639     if (memcmp(&guid, This->format->guid, sizeof(GUID)) != 0)
1640     {
1641         /* FIXME: should use WICConvertBitmapSource to convert */
1642         ERR("format %s unsupported\n", debugstr_guid(&guid));
1643         return E_FAIL;
1644     }
1645
1646     if (This->xres == 0.0 || This->yres == 0.0)
1647     {
1648         double xres, yres;
1649         hr = IWICBitmapSource_GetResolution(pIBitmapSource, &xres, &yres);
1650         if (FAILED(hr)) return hr;
1651         hr = IWICBitmapFrameEncode_SetResolution(iface, xres, yres);
1652         if (FAILED(hr)) return hr;
1653     }
1654
1655     if (!prc)
1656     {
1657         UINT width, height;
1658         hr = IWICBitmapSource_GetSize(pIBitmapSource, &width, &height);
1659         if (FAILED(hr)) return hr;
1660         rc.X = 0;
1661         rc.Y = 0;
1662         rc.Width = width;
1663         rc.Height = height;
1664         prc = &rc;
1665     }
1666
1667     if (prc->Width != This->width) return E_INVALIDARG;
1668
1669     stride = (This->format->bpp * This->width + 7)/8;
1670
1671     pixeldata = HeapAlloc(GetProcessHeap(), 0, stride * prc->Height);
1672     if (!pixeldata) return E_OUTOFMEMORY;
1673
1674     hr = IWICBitmapSource_CopyPixels(pIBitmapSource, prc, stride,
1675         stride*prc->Height, pixeldata);
1676
1677     if (SUCCEEDED(hr))
1678     {
1679         hr = IWICBitmapFrameEncode_WritePixels(iface, prc->Height, stride,
1680             stride*prc->Height, pixeldata);
1681     }
1682
1683     HeapFree(GetProcessHeap(), 0, pixeldata);
1684
1685     return S_OK;
1686 }
1687
1688 static HRESULT WINAPI TiffFrameEncode_Commit(IWICBitmapFrameEncode *iface)
1689 {
1690     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1691
1692     TRACE("(%p)\n", iface);
1693
1694     EnterCriticalSection(&This->parent->lock);
1695
1696     if (!This->info_written || This->lines_written != This->height || This->committed)
1697     {
1698         LeaveCriticalSection(&This->parent->lock);
1699         return WINCODEC_ERR_WRONGSTATE;
1700     }
1701
1702     /* libtiff will commit the data when creating a new frame or closing the file */
1703
1704     This->committed = TRUE;
1705     This->parent->num_frames_committed++;
1706
1707     LeaveCriticalSection(&This->parent->lock);
1708
1709     return S_OK;
1710 }
1711
1712 static HRESULT WINAPI TiffFrameEncode_GetMetadataQueryWriter(IWICBitmapFrameEncode *iface,
1713     IWICMetadataQueryWriter **ppIMetadataQueryWriter)
1714 {
1715     FIXME("(%p, %p): stub\n", iface, ppIMetadataQueryWriter);
1716     return E_NOTIMPL;
1717 }
1718
1719 static const IWICBitmapFrameEncodeVtbl TiffFrameEncode_Vtbl = {
1720     TiffFrameEncode_QueryInterface,
1721     TiffFrameEncode_AddRef,
1722     TiffFrameEncode_Release,
1723     TiffFrameEncode_Initialize,
1724     TiffFrameEncode_SetSize,
1725     TiffFrameEncode_SetResolution,
1726     TiffFrameEncode_SetPixelFormat,
1727     TiffFrameEncode_SetColorContexts,
1728     TiffFrameEncode_SetPalette,
1729     TiffFrameEncode_SetThumbnail,
1730     TiffFrameEncode_WritePixels,
1731     TiffFrameEncode_WriteSource,
1732     TiffFrameEncode_Commit,
1733     TiffFrameEncode_GetMetadataQueryWriter
1734 };
1735
1736 static HRESULT WINAPI TiffEncoder_QueryInterface(IWICBitmapEncoder *iface, REFIID iid,
1737     void **ppv)
1738 {
1739     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1740     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
1741
1742     if (!ppv) return E_INVALIDARG;
1743
1744     if (IsEqualIID(&IID_IUnknown, iid) ||
1745         IsEqualIID(&IID_IWICBitmapEncoder, iid))
1746     {
1747         *ppv = &This->IWICBitmapEncoder_iface;
1748     }
1749     else
1750     {
1751         *ppv = NULL;
1752         return E_NOINTERFACE;
1753     }
1754
1755     IUnknown_AddRef((IUnknown*)*ppv);
1756     return S_OK;
1757 }
1758
1759 static ULONG WINAPI TiffEncoder_AddRef(IWICBitmapEncoder *iface)
1760 {
1761     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1762     ULONG ref = InterlockedIncrement(&This->ref);
1763
1764     TRACE("(%p) refcount=%u\n", iface, ref);
1765
1766     return ref;
1767 }
1768
1769 static ULONG WINAPI TiffEncoder_Release(IWICBitmapEncoder *iface)
1770 {
1771     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1772     ULONG ref = InterlockedDecrement(&This->ref);
1773
1774     TRACE("(%p) refcount=%u\n", iface, ref);
1775
1776     if (ref == 0)
1777     {
1778         if (This->tiff) pTIFFClose(This->tiff);
1779         if (This->stream) IStream_Release(This->stream);
1780         This->lock.DebugInfo->Spare[0] = 0;
1781         DeleteCriticalSection(&This->lock);
1782         HeapFree(GetProcessHeap(), 0, This);
1783     }
1784
1785     return ref;
1786 }
1787
1788 static HRESULT WINAPI TiffEncoder_Initialize(IWICBitmapEncoder *iface,
1789     IStream *pIStream, WICBitmapEncoderCacheOption cacheOption)
1790 {
1791     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1792     TIFF *tiff;
1793     HRESULT hr=S_OK;
1794
1795     TRACE("(%p,%p,%u)\n", iface, pIStream, cacheOption);
1796
1797     EnterCriticalSection(&This->lock);
1798
1799     if (This->initialized || This->committed)
1800     {
1801         hr = WINCODEC_ERR_WRONGSTATE;
1802         goto exit;
1803     }
1804
1805     tiff = tiff_open_stream(pIStream, "w");
1806
1807     if (!tiff)
1808     {
1809         hr = E_FAIL;
1810         goto exit;
1811     }
1812
1813     This->tiff = tiff;
1814     This->stream = pIStream;
1815     IStream_AddRef(pIStream);
1816     This->initialized = TRUE;
1817
1818 exit:
1819     LeaveCriticalSection(&This->lock);
1820     return hr;
1821 }
1822
1823 static HRESULT WINAPI TiffEncoder_GetContainerFormat(IWICBitmapEncoder *iface,
1824     GUID *pguidContainerFormat)
1825 {
1826     memcpy(pguidContainerFormat, &GUID_ContainerFormatTiff, sizeof(GUID));
1827     return S_OK;
1828 }
1829
1830 static HRESULT WINAPI TiffEncoder_GetEncoderInfo(IWICBitmapEncoder *iface,
1831     IWICBitmapEncoderInfo **ppIEncoderInfo)
1832 {
1833     FIXME("(%p,%p): stub\n", iface, ppIEncoderInfo);
1834     return E_NOTIMPL;
1835 }
1836
1837 static HRESULT WINAPI TiffEncoder_SetColorContexts(IWICBitmapEncoder *iface,
1838     UINT cCount, IWICColorContext **ppIColorContext)
1839 {
1840     FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
1841     return E_NOTIMPL;
1842 }
1843
1844 static HRESULT WINAPI TiffEncoder_SetPalette(IWICBitmapEncoder *iface, IWICPalette *pIPalette)
1845 {
1846     TRACE("(%p,%p)\n", iface, pIPalette);
1847     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1848 }
1849
1850 static HRESULT WINAPI TiffEncoder_SetThumbnail(IWICBitmapEncoder *iface, IWICBitmapSource *pIThumbnail)
1851 {
1852     TRACE("(%p,%p)\n", iface, pIThumbnail);
1853     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1854 }
1855
1856 static HRESULT WINAPI TiffEncoder_SetPreview(IWICBitmapEncoder *iface, IWICBitmapSource *pIPreview)
1857 {
1858     TRACE("(%p,%p)\n", iface, pIPreview);
1859     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1860 }
1861
1862 static HRESULT WINAPI TiffEncoder_CreateNewFrame(IWICBitmapEncoder *iface,
1863     IWICBitmapFrameEncode **ppIFrameEncode, IPropertyBag2 **ppIEncoderOptions)
1864 {
1865     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1866     TiffFrameEncode *result;
1867
1868     HRESULT hr=S_OK;
1869
1870     TRACE("(%p,%p,%p)\n", iface, ppIFrameEncode, ppIEncoderOptions);
1871
1872     EnterCriticalSection(&This->lock);
1873
1874     if (!This->initialized || This->committed)
1875     {
1876         hr = WINCODEC_ERR_WRONGSTATE;
1877     }
1878     else if (This->num_frames != This->num_frames_committed)
1879     {
1880         FIXME("New frame created before previous frame was committed\n");
1881         hr = E_FAIL;
1882     }
1883
1884     if (SUCCEEDED(hr))
1885     {
1886         hr = CreatePropertyBag2(ppIEncoderOptions);
1887     }
1888
1889     if (SUCCEEDED(hr))
1890     {
1891         result = HeapAlloc(GetProcessHeap(), 0, sizeof(*result));
1892
1893         if (result)
1894         {
1895             result->IWICBitmapFrameEncode_iface.lpVtbl = &TiffFrameEncode_Vtbl;
1896             result->ref = 1;
1897             result->parent = This;
1898             result->initialized = FALSE;
1899             result->info_written = FALSE;
1900             result->committed = FALSE;
1901             result->format = NULL;
1902             result->width = 0;
1903             result->height = 0;
1904             result->xres = 0.0;
1905             result->yres = 0.0;
1906             result->lines_written = 0;
1907
1908             IWICBitmapEncoder_AddRef(iface);
1909             *ppIFrameEncode = &result->IWICBitmapFrameEncode_iface;
1910
1911             if (This->num_frames != 0)
1912                 pTIFFWriteDirectory(This->tiff);
1913
1914             This->num_frames++;
1915         }
1916         else
1917             hr = E_OUTOFMEMORY;
1918
1919         if (FAILED(hr))
1920         {
1921             IPropertyBag2_Release(*ppIEncoderOptions);
1922             *ppIEncoderOptions = NULL;
1923         }
1924     }
1925
1926     LeaveCriticalSection(&This->lock);
1927
1928     return hr;
1929 }
1930
1931 static HRESULT WINAPI TiffEncoder_Commit(IWICBitmapEncoder *iface)
1932 {
1933     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1934
1935     TRACE("(%p)\n", iface);
1936
1937     EnterCriticalSection(&This->lock);
1938
1939     if (!This->initialized || This->committed)
1940     {
1941         LeaveCriticalSection(&This->lock);
1942         return WINCODEC_ERR_WRONGSTATE;
1943     }
1944
1945     pTIFFClose(This->tiff);
1946     IStream_Release(This->stream);
1947     This->stream = NULL;
1948     This->tiff = NULL;
1949
1950     This->committed = TRUE;
1951
1952     LeaveCriticalSection(&This->lock);
1953
1954     return S_OK;
1955 }
1956
1957 static HRESULT WINAPI TiffEncoder_GetMetadataQueryWriter(IWICBitmapEncoder *iface,
1958     IWICMetadataQueryWriter **ppIMetadataQueryWriter)
1959 {
1960     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryWriter);
1961     return E_NOTIMPL;
1962 }
1963
1964 static const IWICBitmapEncoderVtbl TiffEncoder_Vtbl = {
1965     TiffEncoder_QueryInterface,
1966     TiffEncoder_AddRef,
1967     TiffEncoder_Release,
1968     TiffEncoder_Initialize,
1969     TiffEncoder_GetContainerFormat,
1970     TiffEncoder_GetEncoderInfo,
1971     TiffEncoder_SetColorContexts,
1972     TiffEncoder_SetPalette,
1973     TiffEncoder_SetThumbnail,
1974     TiffEncoder_SetPreview,
1975     TiffEncoder_CreateNewFrame,
1976     TiffEncoder_Commit,
1977     TiffEncoder_GetMetadataQueryWriter
1978 };
1979
1980 HRESULT TiffEncoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
1981 {
1982     TiffEncoder *This;
1983     HRESULT ret;
1984
1985     TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);
1986
1987     *ppv = NULL;
1988
1989     if (pUnkOuter) return CLASS_E_NOAGGREGATION;
1990
1991     if (!load_libtiff())
1992     {
1993         ERR("Failed writing TIFF because unable to load %s\n",SONAME_LIBTIFF);
1994         return E_FAIL;
1995     }
1996
1997     This = HeapAlloc(GetProcessHeap(), 0, sizeof(TiffEncoder));
1998     if (!This) return E_OUTOFMEMORY;
1999
2000     This->IWICBitmapEncoder_iface.lpVtbl = &TiffEncoder_Vtbl;
2001     This->ref = 1;
2002     This->stream = NULL;
2003     InitializeCriticalSection(&This->lock);
2004     This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": TiffEncoder.lock");
2005     This->tiff = NULL;
2006     This->initialized = FALSE;
2007     This->num_frames = 0;
2008     This->num_frames_committed = 0;
2009     This->committed = FALSE;
2010
2011     ret = IWICBitmapEncoder_QueryInterface(&This->IWICBitmapEncoder_iface, iid, ppv);
2012     IWICBitmapEncoder_Release(&This->IWICBitmapEncoder_iface);
2013
2014     return ret;
2015 }
2016
2017 #else /* !SONAME_LIBTIFF */
2018
2019 HRESULT TiffDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
2020 {
2021     ERR("Trying to load TIFF picture, but Wine was compiled without TIFF support.\n");
2022     return E_FAIL;
2023 }
2024
2025 HRESULT TiffEncoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
2026 {
2027     ERR("Trying to save TIFF picture, but Wine was compiled without TIFF support.\n");
2028     return E_FAIL;
2029 }
2030
2031 #endif