d3d9/tests: Add test for IDirect3DDevice9_Reset with BackBufferWidth/Height = 0.
[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 *pIStream,
554     DWORD *pdwCapability)
555 {
556     FIXME("(%p,%p,%p): stub\n", iface, pIStream, pdwCapability);
557     return E_NOTIMPL;
558 }
559
560 static HRESULT WINAPI TiffDecoder_Initialize(IWICBitmapDecoder *iface, IStream *pIStream,
561     WICDecodeOptions cacheOptions)
562 {
563     TiffDecoder *This = impl_from_IWICBitmapDecoder(iface);
564     TIFF *tiff;
565     HRESULT hr=S_OK;
566
567     TRACE("(%p,%p,%x): stub\n", iface, pIStream, cacheOptions);
568
569     EnterCriticalSection(&This->lock);
570
571     if (This->initialized)
572     {
573         hr = WINCODEC_ERR_WRONGSTATE;
574         goto exit;
575     }
576
577     tiff = tiff_open_stream(pIStream, "r");
578
579     if (!tiff)
580     {
581         hr = E_FAIL;
582         goto exit;
583     }
584
585     This->tiff = tiff;
586     This->stream = pIStream;
587     IStream_AddRef(pIStream);
588     This->initialized = TRUE;
589
590 exit:
591     LeaveCriticalSection(&This->lock);
592     return hr;
593 }
594
595 static HRESULT WINAPI TiffDecoder_GetContainerFormat(IWICBitmapDecoder *iface,
596     GUID *pguidContainerFormat)
597 {
598     if (!pguidContainerFormat) return E_INVALIDARG;
599
600     memcpy(pguidContainerFormat, &GUID_ContainerFormatTiff, sizeof(GUID));
601     return S_OK;
602 }
603
604 static HRESULT WINAPI TiffDecoder_GetDecoderInfo(IWICBitmapDecoder *iface,
605     IWICBitmapDecoderInfo **ppIDecoderInfo)
606 {
607     HRESULT hr;
608     IWICComponentInfo *compinfo;
609
610     TRACE("(%p,%p)\n", iface, ppIDecoderInfo);
611
612     hr = CreateComponentInfo(&CLSID_WICTiffDecoder, &compinfo);
613     if (FAILED(hr)) return hr;
614
615     hr = IWICComponentInfo_QueryInterface(compinfo, &IID_IWICBitmapDecoderInfo,
616         (void**)ppIDecoderInfo);
617
618     IWICComponentInfo_Release(compinfo);
619
620     return hr;
621 }
622
623 static HRESULT WINAPI TiffDecoder_CopyPalette(IWICBitmapDecoder *iface,
624     IWICPalette *pIPalette)
625 {
626     FIXME("(%p,%p): stub\n", iface, pIPalette);
627     return E_NOTIMPL;
628 }
629
630 static HRESULT WINAPI TiffDecoder_GetMetadataQueryReader(IWICBitmapDecoder *iface,
631     IWICMetadataQueryReader **ppIMetadataQueryReader)
632 {
633     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
634     return E_NOTIMPL;
635 }
636
637 static HRESULT WINAPI TiffDecoder_GetPreview(IWICBitmapDecoder *iface,
638     IWICBitmapSource **ppIBitmapSource)
639 {
640     TRACE("(%p,%p)\n", iface, ppIBitmapSource);
641
642     if (!ppIBitmapSource) return E_INVALIDARG;
643
644     *ppIBitmapSource = NULL;
645     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
646 }
647
648 static HRESULT WINAPI TiffDecoder_GetColorContexts(IWICBitmapDecoder *iface,
649     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
650 {
651     FIXME("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);
652     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
653 }
654
655 static HRESULT WINAPI TiffDecoder_GetThumbnail(IWICBitmapDecoder *iface,
656     IWICBitmapSource **ppIThumbnail)
657 {
658     TRACE("(%p,%p)\n", iface, ppIThumbnail);
659
660     if (!ppIThumbnail) return E_INVALIDARG;
661
662     *ppIThumbnail = NULL;
663     return WINCODEC_ERR_CODECNOTHUMBNAIL;
664 }
665
666 static HRESULT WINAPI TiffDecoder_GetFrameCount(IWICBitmapDecoder *iface,
667     UINT *pCount)
668 {
669     TiffDecoder *This = impl_from_IWICBitmapDecoder(iface);
670
671     if (!This->tiff)
672     {
673         WARN("(%p) <-- WINCODEC_ERR_WRONGSTATE\n", iface);
674         return WINCODEC_ERR_WRONGSTATE;
675     }
676
677     EnterCriticalSection(&This->lock);
678     *pCount = pTIFFNumberOfDirectories(This->tiff);
679     LeaveCriticalSection(&This->lock);
680
681     TRACE("(%p) <-- %i\n", iface, *pCount);
682
683     return S_OK;
684 }
685
686 static HRESULT WINAPI TiffDecoder_GetFrame(IWICBitmapDecoder *iface,
687     UINT index, IWICBitmapFrameDecode **ppIBitmapFrame)
688 {
689     TiffDecoder *This = impl_from_IWICBitmapDecoder(iface);
690     TiffFrameDecode *result;
691     int res;
692     tiff_decode_info decode_info;
693     HRESULT hr;
694
695     TRACE("(%p,%u,%p)\n", iface, index, ppIBitmapFrame);
696
697     if (!This->tiff)
698         return WINCODEC_ERR_WRONGSTATE;
699
700     EnterCriticalSection(&This->lock);
701     res = pTIFFSetDirectory(This->tiff, index);
702     if (!res) hr = E_INVALIDARG;
703     else hr = tiff_get_decode_info(This->tiff, &decode_info);
704     LeaveCriticalSection(&This->lock);
705
706     if (SUCCEEDED(hr))
707     {
708         result = HeapAlloc(GetProcessHeap(), 0, sizeof(TiffFrameDecode));
709
710         if (result)
711         {
712             result->IWICBitmapFrameDecode_iface.lpVtbl = &TiffFrameDecode_Vtbl;
713             result->IWICMetadataBlockReader_iface.lpVtbl = &TiffFrameDecode_BlockVtbl;
714             result->ref = 1;
715             result->parent = This;
716             result->index = index;
717             result->decode_info = decode_info;
718             result->cached_tile_x = -1;
719             result->cached_tile = HeapAlloc(GetProcessHeap(), 0, decode_info.tile_size);
720
721             if (result->cached_tile)
722                 *ppIBitmapFrame = &result->IWICBitmapFrameDecode_iface;
723             else
724             {
725                 hr = E_OUTOFMEMORY;
726                 HeapFree(GetProcessHeap(), 0, result);
727             }
728         }
729         else hr = E_OUTOFMEMORY;
730     }
731
732     if (FAILED(hr)) *ppIBitmapFrame = NULL;
733
734     return hr;
735 }
736
737 static const IWICBitmapDecoderVtbl TiffDecoder_Vtbl = {
738     TiffDecoder_QueryInterface,
739     TiffDecoder_AddRef,
740     TiffDecoder_Release,
741     TiffDecoder_QueryCapability,
742     TiffDecoder_Initialize,
743     TiffDecoder_GetContainerFormat,
744     TiffDecoder_GetDecoderInfo,
745     TiffDecoder_CopyPalette,
746     TiffDecoder_GetMetadataQueryReader,
747     TiffDecoder_GetPreview,
748     TiffDecoder_GetColorContexts,
749     TiffDecoder_GetThumbnail,
750     TiffDecoder_GetFrameCount,
751     TiffDecoder_GetFrame
752 };
753
754 static HRESULT WINAPI TiffFrameDecode_QueryInterface(IWICBitmapFrameDecode *iface, REFIID iid,
755     void **ppv)
756 {
757     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
758     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
759
760     if (!ppv) return E_INVALIDARG;
761
762     if (IsEqualIID(&IID_IUnknown, iid) ||
763         IsEqualIID(&IID_IWICBitmapSource, iid) ||
764         IsEqualIID(&IID_IWICBitmapFrameDecode, iid))
765     {
766         *ppv = &This->IWICBitmapFrameDecode_iface;
767     }
768     else if (IsEqualIID(&IID_IWICMetadataBlockReader, iid))
769     {
770         *ppv = &This->IWICMetadataBlockReader_iface;
771     }
772     else
773     {
774         *ppv = NULL;
775         return E_NOINTERFACE;
776     }
777
778     IUnknown_AddRef((IUnknown*)*ppv);
779     return S_OK;
780 }
781
782 static ULONG WINAPI TiffFrameDecode_AddRef(IWICBitmapFrameDecode *iface)
783 {
784     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
785     ULONG ref = InterlockedIncrement(&This->ref);
786
787     TRACE("(%p) refcount=%u\n", iface, ref);
788
789     return ref;
790 }
791
792 static ULONG WINAPI TiffFrameDecode_Release(IWICBitmapFrameDecode *iface)
793 {
794     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
795     ULONG ref = InterlockedDecrement(&This->ref);
796
797     TRACE("(%p) refcount=%u\n", iface, ref);
798
799     if (ref == 0)
800     {
801         HeapFree(GetProcessHeap(), 0, This->cached_tile);
802         HeapFree(GetProcessHeap(), 0, This);
803     }
804
805     return ref;
806 }
807
808 static HRESULT WINAPI TiffFrameDecode_GetSize(IWICBitmapFrameDecode *iface,
809     UINT *puiWidth, UINT *puiHeight)
810 {
811     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
812
813     *puiWidth = This->decode_info.width;
814     *puiHeight = This->decode_info.height;
815
816     TRACE("(%p) <-- %ux%u\n", iface, *puiWidth, *puiHeight);
817
818     return S_OK;
819 }
820
821 static HRESULT WINAPI TiffFrameDecode_GetPixelFormat(IWICBitmapFrameDecode *iface,
822     WICPixelFormatGUID *pPixelFormat)
823 {
824     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
825
826     memcpy(pPixelFormat, This->decode_info.format, sizeof(GUID));
827
828     TRACE("(%p) <-- %s\n", This, debugstr_guid(This->decode_info.format));
829
830     return S_OK;
831 }
832
833 static HRESULT WINAPI TiffFrameDecode_GetResolution(IWICBitmapFrameDecode *iface,
834     double *pDpiX, double *pDpiY)
835 {
836     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
837
838     switch (This->decode_info.resolution_unit)
839     {
840     default:
841         FIXME("unknown resolution unit %i\n", This->decode_info.resolution_unit);
842         /* fall through */
843     case 0: /* Not set */
844         *pDpiX = *pDpiY = 96.0;
845         break;
846     case 1: /* Relative measurements */
847         *pDpiX = 96.0;
848         *pDpiY = 96.0 * This->decode_info.yres / This->decode_info.xres;
849         break;
850     case 2: /* Inch */
851         *pDpiX = This->decode_info.xres;
852         *pDpiY = This->decode_info.yres;
853         break;
854     case 3: /* Centimeter */
855         *pDpiX = This->decode_info.xres / 2.54;
856         *pDpiY = This->decode_info.yres / 2.54;
857         break;
858     }
859
860     TRACE("(%p) <-- %f,%f unit=%i\n", iface, *pDpiX, *pDpiY, This->decode_info.resolution_unit);
861
862     return S_OK;
863 }
864
865 static HRESULT WINAPI TiffFrameDecode_CopyPalette(IWICBitmapFrameDecode *iface,
866     IWICPalette *pIPalette)
867 {
868     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
869     uint16 *red, *green, *blue;
870     WICColor colors[256];
871     int color_count, ret, i;
872
873     TRACE("(%p,%p)\n", iface, pIPalette);
874
875     color_count = 1<<This->decode_info.bps;
876
877     EnterCriticalSection(&This->parent->lock);
878     ret = pTIFFGetField(This->parent->tiff, TIFFTAG_COLORMAP, &red, &green, &blue);
879     LeaveCriticalSection(&This->parent->lock);
880
881     if (!ret)
882     {
883         WARN("Couldn't read color map\n");
884         return WINCODEC_ERR_PALETTEUNAVAILABLE;
885     }
886
887     for (i=0; i<color_count; i++)
888     {
889         colors[i] = 0xff000000 |
890             ((red[i]<<8) & 0xff0000) |
891             (green[i] & 0xff00) |
892             ((blue[i]>>8) & 0xff);
893     }
894
895     return IWICPalette_InitializeCustom(pIPalette, colors, color_count);
896 }
897
898 static HRESULT TiffFrameDecode_ReadTile(TiffFrameDecode *This, UINT tile_x, UINT tile_y)
899 {
900     HRESULT hr=S_OK;
901     tsize_t ret;
902     int swap_bytes;
903
904     swap_bytes = pTIFFIsByteSwapped(This->parent->tiff);
905
906     ret = pTIFFSetDirectory(This->parent->tiff, This->index);
907
908     if (ret == -1)
909         hr = E_FAIL;
910
911     if (hr == S_OK)
912     {
913         if (This->decode_info.tiled)
914         {
915             ret = pTIFFReadEncodedTile(This->parent->tiff, tile_x + tile_y * This->decode_info.tiles_across, This->cached_tile, This->decode_info.tile_size);
916         }
917         else
918         {
919             ret = pTIFFReadEncodedStrip(This->parent->tiff, tile_y, This->cached_tile, This->decode_info.tile_size);
920         }
921
922         if (ret == -1)
923             hr = E_FAIL;
924     }
925
926     if (hr == S_OK && This->decode_info.reverse_bgr)
927     {
928         if (This->decode_info.bps == 8)
929         {
930             UINT sample_count = This->decode_info.samples;
931
932             reverse_bgr8(sample_count, This->cached_tile, This->decode_info.tile_width,
933                 This->decode_info.tile_height, This->decode_info.tile_width * sample_count);
934         }
935     }
936
937     if (hr == S_OK && swap_bytes && This->decode_info.bps > 8)
938     {
939         UINT row, i, samples_per_row;
940         BYTE *sample, temp;
941
942         samples_per_row = This->decode_info.tile_width * This->decode_info.samples;
943
944         switch(This->decode_info.bps)
945         {
946         case 16:
947             for (row=0; row<This->decode_info.tile_height; row++)
948             {
949                 sample = This->cached_tile + row * This->decode_info.tile_stride;
950                 for (i=0; i<samples_per_row; i++)
951                 {
952                     temp = sample[1];
953                     sample[1] = sample[0];
954                     sample[0] = temp;
955                     sample += 2;
956                 }
957             }
958             break;
959         default:
960             ERR("unhandled bps for byte swap %u\n", This->decode_info.bps);
961             return E_FAIL;
962         }
963     }
964
965     if (hr == S_OK && This->decode_info.invert_grayscale)
966     {
967         BYTE *byte, *end;
968
969         if (This->decode_info.samples != 1)
970         {
971             ERR("cannot invert grayscale image with %u samples\n", This->decode_info.samples);
972             return E_FAIL;
973         }
974
975         end = This->cached_tile+This->decode_info.tile_size;
976
977         for (byte = This->cached_tile; byte != end; byte++)
978             *byte = ~(*byte);
979     }
980
981     if (hr == S_OK)
982     {
983         This->cached_tile_x = tile_x;
984         This->cached_tile_y = tile_y;
985     }
986
987     return hr;
988 }
989
990 static HRESULT WINAPI TiffFrameDecode_CopyPixels(IWICBitmapFrameDecode *iface,
991     const WICRect *prc, UINT cbStride, UINT cbBufferSize, BYTE *pbBuffer)
992 {
993     TiffFrameDecode *This = impl_from_IWICBitmapFrameDecode(iface);
994     UINT min_tile_x, max_tile_x, min_tile_y, max_tile_y;
995     UINT tile_x, tile_y;
996     WICRect rc;
997     HRESULT hr=S_OK;
998     BYTE *dst_tilepos;
999     UINT bytesperrow;
1000     WICRect rect;
1001
1002     TRACE("(%p,%p,%u,%u,%p)\n", iface, prc, cbStride, cbBufferSize, pbBuffer);
1003
1004     if (!prc)
1005     {
1006         rect.X = 0;
1007         rect.Y = 0;
1008         rect.Width = This->decode_info.width;
1009         rect.Height = This->decode_info.height;
1010         prc = &rect;
1011     }
1012     else
1013     {
1014         if (prc->X < 0 || prc->Y < 0 || prc->X+prc->Width > This->decode_info.width ||
1015             prc->Y+prc->Height > This->decode_info.height)
1016             return E_INVALIDARG;
1017     }
1018
1019     bytesperrow = ((This->decode_info.bpp * prc->Width)+7)/8;
1020
1021     if (cbStride < bytesperrow)
1022         return E_INVALIDARG;
1023
1024     if ((cbStride * prc->Height) > cbBufferSize)
1025         return E_INVALIDARG;
1026
1027     min_tile_x = prc->X / This->decode_info.tile_width;
1028     min_tile_y = prc->Y / This->decode_info.tile_height;
1029     max_tile_x = (prc->X+prc->Width-1) / This->decode_info.tile_width;
1030     max_tile_y = (prc->Y+prc->Height-1) / This->decode_info.tile_height;
1031
1032     EnterCriticalSection(&This->parent->lock);
1033
1034     for (tile_x=min_tile_x; tile_x <= max_tile_x; tile_x++)
1035     {
1036         for (tile_y=min_tile_y; tile_y <= max_tile_y; tile_y++)
1037         {
1038             if (tile_x != This->cached_tile_x || tile_y != This->cached_tile_y)
1039             {
1040                 hr = TiffFrameDecode_ReadTile(This, tile_x, tile_y);
1041             }
1042
1043             if (SUCCEEDED(hr))
1044             {
1045                 if (prc->X < tile_x * This->decode_info.tile_width)
1046                     rc.X = 0;
1047                 else
1048                     rc.X = prc->X - tile_x * This->decode_info.tile_width;
1049
1050                 if (prc->Y < tile_y * This->decode_info.tile_height)
1051                     rc.Y = 0;
1052                 else
1053                     rc.Y = prc->Y - tile_y * This->decode_info.tile_height;
1054
1055                 if (prc->X+prc->Width > (tile_x+1) * This->decode_info.tile_width)
1056                     rc.Width = This->decode_info.tile_width - rc.X;
1057                 else if (prc->X < tile_x * This->decode_info.tile_width)
1058                     rc.Width = prc->Width + prc->X - tile_x * This->decode_info.tile_width;
1059                 else
1060                     rc.Width = prc->Width;
1061
1062                 if (prc->Y+prc->Height > (tile_y+1) * This->decode_info.tile_height)
1063                     rc.Height = This->decode_info.tile_height - rc.Y;
1064                 else if (prc->Y < tile_y * This->decode_info.tile_height)
1065                     rc.Height = prc->Height + prc->Y - tile_y * This->decode_info.tile_height;
1066                 else
1067                     rc.Height = prc->Height;
1068
1069                 dst_tilepos = pbBuffer + (cbStride * ((rc.Y + tile_y * This->decode_info.tile_height) - prc->Y)) +
1070                     ((This->decode_info.bpp * ((rc.X + tile_x * This->decode_info.tile_width) - prc->X) + 7) / 8);
1071
1072                 hr = copy_pixels(This->decode_info.bpp, This->cached_tile,
1073                     This->decode_info.tile_width, This->decode_info.tile_height, This->decode_info.tile_stride,
1074                     &rc, cbStride, cbBufferSize, dst_tilepos);
1075             }
1076
1077             if (FAILED(hr))
1078             {
1079                 LeaveCriticalSection(&This->parent->lock);
1080                 TRACE("<-- 0x%x\n", hr);
1081                 return hr;
1082             }
1083         }
1084     }
1085
1086     LeaveCriticalSection(&This->parent->lock);
1087
1088     return S_OK;
1089 }
1090
1091 static HRESULT WINAPI TiffFrameDecode_GetMetadataQueryReader(IWICBitmapFrameDecode *iface,
1092     IWICMetadataQueryReader **ppIMetadataQueryReader)
1093 {
1094     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
1095     return E_NOTIMPL;
1096 }
1097
1098 static HRESULT WINAPI TiffFrameDecode_GetColorContexts(IWICBitmapFrameDecode *iface,
1099     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
1100 {
1101     FIXME("(%p,%u,%p,%p): stub\n", iface, cCount, ppIColorContexts, pcActualCount);
1102     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1103 }
1104
1105 static HRESULT WINAPI TiffFrameDecode_GetThumbnail(IWICBitmapFrameDecode *iface,
1106     IWICBitmapSource **ppIThumbnail)
1107 {
1108     TRACE("(%p,%p)\n", iface, ppIThumbnail);
1109
1110     if (!ppIThumbnail) return E_INVALIDARG;
1111
1112     *ppIThumbnail = NULL;
1113     return WINCODEC_ERR_CODECNOTHUMBNAIL;
1114 }
1115
1116 static const IWICBitmapFrameDecodeVtbl TiffFrameDecode_Vtbl = {
1117     TiffFrameDecode_QueryInterface,
1118     TiffFrameDecode_AddRef,
1119     TiffFrameDecode_Release,
1120     TiffFrameDecode_GetSize,
1121     TiffFrameDecode_GetPixelFormat,
1122     TiffFrameDecode_GetResolution,
1123     TiffFrameDecode_CopyPalette,
1124     TiffFrameDecode_CopyPixels,
1125     TiffFrameDecode_GetMetadataQueryReader,
1126     TiffFrameDecode_GetColorContexts,
1127     TiffFrameDecode_GetThumbnail
1128 };
1129
1130 static HRESULT WINAPI TiffFrameDecode_Block_QueryInterface(IWICMetadataBlockReader *iface,
1131     REFIID iid, void **ppv)
1132 {
1133     TiffFrameDecode *This = impl_from_IWICMetadataBlockReader(iface);
1134     return IWICBitmapFrameDecode_QueryInterface(&This->IWICBitmapFrameDecode_iface, iid, ppv);
1135 }
1136
1137 static ULONG WINAPI TiffFrameDecode_Block_AddRef(IWICMetadataBlockReader *iface)
1138 {
1139     TiffFrameDecode *This = impl_from_IWICMetadataBlockReader(iface);
1140     return IWICBitmapFrameDecode_AddRef(&This->IWICBitmapFrameDecode_iface);
1141 }
1142
1143 static ULONG WINAPI TiffFrameDecode_Block_Release(IWICMetadataBlockReader *iface)
1144 {
1145     TiffFrameDecode *This = impl_from_IWICMetadataBlockReader(iface);
1146     return IWICBitmapFrameDecode_Release(&This->IWICBitmapFrameDecode_iface);
1147 }
1148
1149 static HRESULT WINAPI TiffFrameDecode_Block_GetContainerFormat(IWICMetadataBlockReader *iface,
1150     GUID *guid)
1151 {
1152     TRACE("(%p,%p)\n", iface, guid);
1153
1154     if (!guid) return E_INVALIDARG;
1155
1156     *guid = GUID_ContainerFormatTiff;
1157     return S_OK;
1158 }
1159
1160 static HRESULT WINAPI TiffFrameDecode_Block_GetCount(IWICMetadataBlockReader *iface,
1161     UINT *count)
1162 {
1163     TRACE("%p,%p\n", iface, count);
1164
1165     if (!count) return E_INVALIDARG;
1166
1167     *count = 1;
1168     return S_OK;
1169 }
1170
1171 static HRESULT create_metadata_reader(TiffFrameDecode *This, IWICMetadataReader **reader)
1172 {
1173     HRESULT hr;
1174     LARGE_INTEGER dir_offset;
1175     IWICMetadataReader *metadata_reader;
1176     IWICPersistStream *persist;
1177
1178     /* FIXME: Use IWICComponentFactory_CreateMetadataReader once it's implemented */
1179
1180     hr = CoCreateInstance(&CLSID_WICIfdMetadataReader, NULL, CLSCTX_INPROC_SERVER,
1181                           &IID_IWICMetadataReader, (void **)&metadata_reader);
1182     if (FAILED(hr)) return hr;
1183
1184     hr = IWICMetadataReader_QueryInterface(metadata_reader, &IID_IWICPersistStream, (void **)&persist);
1185     if (FAILED(hr))
1186     {
1187         IWICMetadataReader_Release(metadata_reader);
1188         return hr;
1189     }
1190
1191     EnterCriticalSection(&This->parent->lock);
1192
1193     dir_offset.QuadPart = pTIFFCurrentDirOffset(This->parent->tiff);
1194     hr = IStream_Seek(This->parent->stream, dir_offset, STREAM_SEEK_SET, NULL);
1195     if (SUCCEEDED(hr))
1196     {
1197         BOOL byte_swapped = pTIFFIsByteSwapped(This->parent->tiff);
1198 #ifdef WORDS_BIGENDIAN
1199         DWORD persist_options = byte_swapped ? WICPersistOptionsLittleEndian : WICPersistOptionsBigEndian;
1200 #else
1201         DWORD persist_options = byte_swapped ? WICPersistOptionsBigEndian : WICPersistOptionsLittleEndian;
1202 #endif
1203         persist_options |= WICPersistOptionsNoCacheStream;
1204         hr = IWICPersistStream_LoadEx(persist, This->parent->stream, NULL, persist_options);
1205         if (FAILED(hr))
1206             ERR("IWICPersistStream_LoadEx error %#x\n", hr);
1207     }
1208
1209     LeaveCriticalSection(&This->parent->lock);
1210
1211     IWICPersistStream_Release(persist);
1212
1213     if (FAILED(hr))
1214     {
1215         IWICMetadataReader_Release(metadata_reader);
1216         return hr;
1217     }
1218
1219     *reader = metadata_reader;
1220     return S_OK;
1221 }
1222
1223 static HRESULT WINAPI TiffFrameDecode_Block_GetReaderByIndex(IWICMetadataBlockReader *iface,
1224     UINT index, IWICMetadataReader **reader)
1225 {
1226     TiffFrameDecode *This = impl_from_IWICMetadataBlockReader(iface);
1227
1228     TRACE("(%p,%u,%p)\n", iface, index, reader);
1229
1230     if (!reader || index != 0) return E_INVALIDARG;
1231
1232     return create_metadata_reader(This, reader);
1233 }
1234
1235 static HRESULT WINAPI TiffFrameDecode_Block_GetEnumerator(IWICMetadataBlockReader *iface,
1236     IEnumUnknown **enum_metadata)
1237 {
1238     FIXME("(%p,%p): stub\n", iface, enum_metadata);
1239     return E_NOTIMPL;
1240 }
1241
1242 static const IWICMetadataBlockReaderVtbl TiffFrameDecode_BlockVtbl =
1243 {
1244     TiffFrameDecode_Block_QueryInterface,
1245     TiffFrameDecode_Block_AddRef,
1246     TiffFrameDecode_Block_Release,
1247     TiffFrameDecode_Block_GetContainerFormat,
1248     TiffFrameDecode_Block_GetCount,
1249     TiffFrameDecode_Block_GetReaderByIndex,
1250     TiffFrameDecode_Block_GetEnumerator
1251 };
1252
1253 HRESULT TiffDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
1254 {
1255     HRESULT ret;
1256     TiffDecoder *This;
1257
1258     TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);
1259
1260     *ppv = NULL;
1261
1262     if (pUnkOuter) return CLASS_E_NOAGGREGATION;
1263
1264     if (!load_libtiff())
1265     {
1266         ERR("Failed reading TIFF because unable to load %s\n",SONAME_LIBTIFF);
1267         return E_FAIL;
1268     }
1269
1270     This = HeapAlloc(GetProcessHeap(), 0, sizeof(TiffDecoder));
1271     if (!This) return E_OUTOFMEMORY;
1272
1273     This->IWICBitmapDecoder_iface.lpVtbl = &TiffDecoder_Vtbl;
1274     This->ref = 1;
1275     This->stream = NULL;
1276     InitializeCriticalSection(&This->lock);
1277     This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": TiffDecoder.lock");
1278     This->tiff = NULL;
1279     This->initialized = FALSE;
1280
1281     ret = IWICBitmapDecoder_QueryInterface(&This->IWICBitmapDecoder_iface, iid, ppv);
1282     IWICBitmapDecoder_Release(&This->IWICBitmapDecoder_iface);
1283
1284     return ret;
1285 }
1286
1287 struct tiff_encode_format {
1288     const WICPixelFormatGUID *guid;
1289     int photometric;
1290     int bps;
1291     int samples;
1292     int bpp;
1293     int extra_sample;
1294     int extra_sample_type;
1295     int reverse_bgr;
1296 };
1297
1298 static const struct tiff_encode_format formats[] = {
1299     {&GUID_WICPixelFormat24bppBGR, 2, 8, 3, 24, 0, 0, 1},
1300     {&GUID_WICPixelFormatBlackWhite, 1, 1, 1, 1, 0, 0, 0},
1301     {&GUID_WICPixelFormat4bppGray, 1, 4, 1, 4, 0, 0, 0},
1302     {&GUID_WICPixelFormat8bppGray, 1, 8, 1, 8, 0, 0, 0},
1303     {&GUID_WICPixelFormat32bppBGRA, 2, 8, 4, 32, 1, 2, 1},
1304     {&GUID_WICPixelFormat32bppPBGRA, 2, 8, 4, 32, 1, 1, 1},
1305     {&GUID_WICPixelFormat48bppRGB, 2, 16, 3, 48, 0, 0, 0},
1306     {&GUID_WICPixelFormat64bppRGBA, 2, 16, 4, 64, 1, 2, 0},
1307     {&GUID_WICPixelFormat64bppPRGBA, 2, 16, 4, 64, 1, 1, 0},
1308     {0}
1309 };
1310
1311 typedef struct TiffEncoder {
1312     IWICBitmapEncoder IWICBitmapEncoder_iface;
1313     LONG ref;
1314     IStream *stream;
1315     CRITICAL_SECTION lock; /* Must be held when tiff is used or fields below are set */
1316     TIFF *tiff;
1317     BOOL initialized;
1318     BOOL committed;
1319     ULONG num_frames;
1320     ULONG num_frames_committed;
1321 } TiffEncoder;
1322
1323 static inline TiffEncoder *impl_from_IWICBitmapEncoder(IWICBitmapEncoder *iface)
1324 {
1325     return CONTAINING_RECORD(iface, TiffEncoder, IWICBitmapEncoder_iface);
1326 }
1327
1328 typedef struct TiffFrameEncode {
1329     IWICBitmapFrameEncode IWICBitmapFrameEncode_iface;
1330     LONG ref;
1331     TiffEncoder *parent;
1332     /* fields below are protected by parent->lock */
1333     BOOL initialized;
1334     BOOL info_written;
1335     BOOL committed;
1336     const struct tiff_encode_format *format;
1337     UINT width, height;
1338     double xres, yres;
1339     UINT lines_written;
1340 } TiffFrameEncode;
1341
1342 static inline TiffFrameEncode *impl_from_IWICBitmapFrameEncode(IWICBitmapFrameEncode *iface)
1343 {
1344     return CONTAINING_RECORD(iface, TiffFrameEncode, IWICBitmapFrameEncode_iface);
1345 }
1346
1347 static HRESULT WINAPI TiffFrameEncode_QueryInterface(IWICBitmapFrameEncode *iface, REFIID iid,
1348     void **ppv)
1349 {
1350     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1351     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
1352
1353     if (!ppv) return E_INVALIDARG;
1354
1355     if (IsEqualIID(&IID_IUnknown, iid) ||
1356         IsEqualIID(&IID_IWICBitmapFrameEncode, iid))
1357     {
1358         *ppv = &This->IWICBitmapFrameEncode_iface;
1359     }
1360     else
1361     {
1362         *ppv = NULL;
1363         return E_NOINTERFACE;
1364     }
1365
1366     IUnknown_AddRef((IUnknown*)*ppv);
1367     return S_OK;
1368 }
1369
1370 static ULONG WINAPI TiffFrameEncode_AddRef(IWICBitmapFrameEncode *iface)
1371 {
1372     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1373     ULONG ref = InterlockedIncrement(&This->ref);
1374
1375     TRACE("(%p) refcount=%u\n", iface, ref);
1376
1377     return ref;
1378 }
1379
1380 static ULONG WINAPI TiffFrameEncode_Release(IWICBitmapFrameEncode *iface)
1381 {
1382     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1383     ULONG ref = InterlockedDecrement(&This->ref);
1384
1385     TRACE("(%p) refcount=%u\n", iface, ref);
1386
1387     if (ref == 0)
1388     {
1389         IWICBitmapEncoder_Release(&This->parent->IWICBitmapEncoder_iface);
1390         HeapFree(GetProcessHeap(), 0, This);
1391     }
1392
1393     return ref;
1394 }
1395
1396 static HRESULT WINAPI TiffFrameEncode_Initialize(IWICBitmapFrameEncode *iface,
1397     IPropertyBag2 *pIEncoderOptions)
1398 {
1399     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1400     TRACE("(%p,%p)\n", iface, pIEncoderOptions);
1401
1402     EnterCriticalSection(&This->parent->lock);
1403
1404     if (This->initialized)
1405     {
1406         LeaveCriticalSection(&This->parent->lock);
1407         return WINCODEC_ERR_WRONGSTATE;
1408     }
1409
1410     This->initialized = TRUE;
1411
1412     LeaveCriticalSection(&This->parent->lock);
1413
1414     return S_OK;
1415 }
1416
1417 static HRESULT WINAPI TiffFrameEncode_SetSize(IWICBitmapFrameEncode *iface,
1418     UINT uiWidth, UINT uiHeight)
1419 {
1420     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1421     TRACE("(%p,%u,%u)\n", iface, uiWidth, uiHeight);
1422
1423     EnterCriticalSection(&This->parent->lock);
1424
1425     if (!This->initialized || This->info_written)
1426     {
1427         LeaveCriticalSection(&This->parent->lock);
1428         return WINCODEC_ERR_WRONGSTATE;
1429     }
1430
1431     This->width = uiWidth;
1432     This->height = uiHeight;
1433
1434     LeaveCriticalSection(&This->parent->lock);
1435
1436     return S_OK;
1437 }
1438
1439 static HRESULT WINAPI TiffFrameEncode_SetResolution(IWICBitmapFrameEncode *iface,
1440     double dpiX, double dpiY)
1441 {
1442     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1443     TRACE("(%p,%0.2f,%0.2f)\n", iface, dpiX, dpiY);
1444
1445     EnterCriticalSection(&This->parent->lock);
1446
1447     if (!This->initialized || This->info_written)
1448     {
1449         LeaveCriticalSection(&This->parent->lock);
1450         return WINCODEC_ERR_WRONGSTATE;
1451     }
1452
1453     This->xres = dpiX;
1454     This->yres = dpiY;
1455
1456     LeaveCriticalSection(&This->parent->lock);
1457
1458     return S_OK;
1459 }
1460
1461 static HRESULT WINAPI TiffFrameEncode_SetPixelFormat(IWICBitmapFrameEncode *iface,
1462     WICPixelFormatGUID *pPixelFormat)
1463 {
1464     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1465     int i;
1466
1467     TRACE("(%p,%s)\n", iface, debugstr_guid(pPixelFormat));
1468
1469     EnterCriticalSection(&This->parent->lock);
1470
1471     if (!This->initialized || This->info_written)
1472     {
1473         LeaveCriticalSection(&This->parent->lock);
1474         return WINCODEC_ERR_WRONGSTATE;
1475     }
1476
1477     for (i=0; formats[i].guid; i++)
1478     {
1479         if (memcmp(formats[i].guid, pPixelFormat, sizeof(GUID)) == 0)
1480             break;
1481     }
1482
1483     if (!formats[i].guid) i = 0;
1484
1485     This->format = &formats[i];
1486     memcpy(pPixelFormat, This->format->guid, sizeof(GUID));
1487
1488     LeaveCriticalSection(&This->parent->lock);
1489
1490     return S_OK;
1491 }
1492
1493 static HRESULT WINAPI TiffFrameEncode_SetColorContexts(IWICBitmapFrameEncode *iface,
1494     UINT cCount, IWICColorContext **ppIColorContext)
1495 {
1496     FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
1497     return E_NOTIMPL;
1498 }
1499
1500 static HRESULT WINAPI TiffFrameEncode_SetPalette(IWICBitmapFrameEncode *iface,
1501     IWICPalette *pIPalette)
1502 {
1503     FIXME("(%p,%p): stub\n", iface, pIPalette);
1504     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1505 }
1506
1507 static HRESULT WINAPI TiffFrameEncode_SetThumbnail(IWICBitmapFrameEncode *iface,
1508     IWICBitmapSource *pIThumbnail)
1509 {
1510     FIXME("(%p,%p): stub\n", iface, pIThumbnail);
1511     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1512 }
1513
1514 static HRESULT WINAPI TiffFrameEncode_WritePixels(IWICBitmapFrameEncode *iface,
1515     UINT lineCount, UINT cbStride, UINT cbBufferSize, BYTE *pbPixels)
1516 {
1517     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1518     BYTE *row_data, *swapped_data = NULL;
1519     UINT i, j, line_size;
1520
1521     TRACE("(%p,%u,%u,%u,%p)\n", iface, lineCount, cbStride, cbBufferSize, pbPixels);
1522
1523     EnterCriticalSection(&This->parent->lock);
1524
1525     if (!This->initialized || !This->width || !This->height || !This->format)
1526     {
1527         LeaveCriticalSection(&This->parent->lock);
1528         return WINCODEC_ERR_WRONGSTATE;
1529     }
1530
1531     if (lineCount == 0 || lineCount + This->lines_written > This->height)
1532     {
1533         LeaveCriticalSection(&This->parent->lock);
1534         return E_INVALIDARG;
1535     }
1536
1537     line_size = ((This->width * This->format->bpp)+7)/8;
1538
1539     if (This->format->reverse_bgr)
1540     {
1541         swapped_data = HeapAlloc(GetProcessHeap(), 0, line_size);
1542         if (!swapped_data)
1543         {
1544             LeaveCriticalSection(&This->parent->lock);
1545             return E_OUTOFMEMORY;
1546         }
1547     }
1548
1549     if (!This->info_written)
1550     {
1551         pTIFFSetField(This->parent->tiff, TIFFTAG_PHOTOMETRIC, (uint16)This->format->photometric);
1552         pTIFFSetField(This->parent->tiff, TIFFTAG_PLANARCONFIG, (uint16)1);
1553         pTIFFSetField(This->parent->tiff, TIFFTAG_BITSPERSAMPLE, (uint16)This->format->bps);
1554         pTIFFSetField(This->parent->tiff, TIFFTAG_SAMPLESPERPIXEL, (uint16)This->format->samples);
1555
1556         if (This->format->extra_sample)
1557         {
1558             uint16 extra_samples;
1559             extra_samples = This->format->extra_sample_type;
1560
1561             pTIFFSetField(This->parent->tiff, TIFFTAG_EXTRASAMPLES, (uint16)1, &extra_samples);
1562         }
1563
1564         pTIFFSetField(This->parent->tiff, TIFFTAG_IMAGEWIDTH, (uint32)This->width);
1565         pTIFFSetField(This->parent->tiff, TIFFTAG_IMAGELENGTH, (uint32)This->height);
1566
1567         if (This->xres != 0.0 && This->yres != 0.0)
1568         {
1569             pTIFFSetField(This->parent->tiff, TIFFTAG_RESOLUTIONUNIT, (uint16)2); /* Inch */
1570             pTIFFSetField(This->parent->tiff, TIFFTAG_XRESOLUTION, (float)This->xres);
1571             pTIFFSetField(This->parent->tiff, TIFFTAG_YRESOLUTION, (float)This->yres);
1572         }
1573
1574         This->info_written = TRUE;
1575     }
1576
1577     for (i=0; i<lineCount; i++)
1578     {
1579         row_data = pbPixels + i * cbStride;
1580
1581         if (This->format->reverse_bgr && This->format->bps == 8)
1582         {
1583             memcpy(swapped_data, row_data, line_size);
1584             for (j=0; j<line_size; j += This->format->samples)
1585             {
1586                 BYTE temp;
1587                 temp = swapped_data[j];
1588                 swapped_data[j] = swapped_data[j+2];
1589                 swapped_data[j+2] = temp;
1590             }
1591             row_data = swapped_data;
1592         }
1593
1594         pTIFFWriteScanline(This->parent->tiff, (tdata_t)row_data, i+This->lines_written, 0);
1595     }
1596
1597     This->lines_written += lineCount;
1598
1599     LeaveCriticalSection(&This->parent->lock);
1600
1601     HeapFree(GetProcessHeap(), 0, swapped_data);
1602
1603     return S_OK;
1604 }
1605
1606 static HRESULT WINAPI TiffFrameEncode_WriteSource(IWICBitmapFrameEncode *iface,
1607     IWICBitmapSource *pIBitmapSource, WICRect *prc)
1608 {
1609     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1610     HRESULT hr;
1611     WICRect rc;
1612     WICPixelFormatGUID guid;
1613     UINT stride;
1614     BYTE *pixeldata;
1615
1616     TRACE("(%p,%p,%p)\n", iface, pIBitmapSource, prc);
1617
1618     if (!This->initialized || !This->width || !This->height)
1619         return WINCODEC_ERR_WRONGSTATE;
1620
1621     if (!This->format)
1622     {
1623         hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
1624         if (FAILED(hr)) return hr;
1625         hr = IWICBitmapFrameEncode_SetPixelFormat(iface, &guid);
1626         if (FAILED(hr)) return hr;
1627     }
1628
1629     hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
1630     if (FAILED(hr)) return hr;
1631     if (memcmp(&guid, This->format->guid, sizeof(GUID)) != 0)
1632     {
1633         /* FIXME: should use WICConvertBitmapSource to convert */
1634         ERR("format %s unsupported\n", debugstr_guid(&guid));
1635         return E_FAIL;
1636     }
1637
1638     if (This->xres == 0.0 || This->yres == 0.0)
1639     {
1640         double xres, yres;
1641         hr = IWICBitmapSource_GetResolution(pIBitmapSource, &xres, &yres);
1642         if (FAILED(hr)) return hr;
1643         hr = IWICBitmapFrameEncode_SetResolution(iface, xres, yres);
1644         if (FAILED(hr)) return hr;
1645     }
1646
1647     if (!prc)
1648     {
1649         UINT width, height;
1650         hr = IWICBitmapSource_GetSize(pIBitmapSource, &width, &height);
1651         if (FAILED(hr)) return hr;
1652         rc.X = 0;
1653         rc.Y = 0;
1654         rc.Width = width;
1655         rc.Height = height;
1656         prc = &rc;
1657     }
1658
1659     if (prc->Width != This->width) return E_INVALIDARG;
1660
1661     stride = (This->format->bpp * This->width + 7)/8;
1662
1663     pixeldata = HeapAlloc(GetProcessHeap(), 0, stride * prc->Height);
1664     if (!pixeldata) return E_OUTOFMEMORY;
1665
1666     hr = IWICBitmapSource_CopyPixels(pIBitmapSource, prc, stride,
1667         stride*prc->Height, pixeldata);
1668
1669     if (SUCCEEDED(hr))
1670     {
1671         hr = IWICBitmapFrameEncode_WritePixels(iface, prc->Height, stride,
1672             stride*prc->Height, pixeldata);
1673     }
1674
1675     HeapFree(GetProcessHeap(), 0, pixeldata);
1676
1677     return S_OK;
1678 }
1679
1680 static HRESULT WINAPI TiffFrameEncode_Commit(IWICBitmapFrameEncode *iface)
1681 {
1682     TiffFrameEncode *This = impl_from_IWICBitmapFrameEncode(iface);
1683
1684     TRACE("(%p)\n", iface);
1685
1686     EnterCriticalSection(&This->parent->lock);
1687
1688     if (!This->info_written || This->lines_written != This->height || This->committed)
1689     {
1690         LeaveCriticalSection(&This->parent->lock);
1691         return WINCODEC_ERR_WRONGSTATE;
1692     }
1693
1694     /* libtiff will commit the data when creating a new frame or closing the file */
1695
1696     This->committed = TRUE;
1697     This->parent->num_frames_committed++;
1698
1699     LeaveCriticalSection(&This->parent->lock);
1700
1701     return S_OK;
1702 }
1703
1704 static HRESULT WINAPI TiffFrameEncode_GetMetadataQueryWriter(IWICBitmapFrameEncode *iface,
1705     IWICMetadataQueryWriter **ppIMetadataQueryWriter)
1706 {
1707     FIXME("(%p, %p): stub\n", iface, ppIMetadataQueryWriter);
1708     return E_NOTIMPL;
1709 }
1710
1711 static const IWICBitmapFrameEncodeVtbl TiffFrameEncode_Vtbl = {
1712     TiffFrameEncode_QueryInterface,
1713     TiffFrameEncode_AddRef,
1714     TiffFrameEncode_Release,
1715     TiffFrameEncode_Initialize,
1716     TiffFrameEncode_SetSize,
1717     TiffFrameEncode_SetResolution,
1718     TiffFrameEncode_SetPixelFormat,
1719     TiffFrameEncode_SetColorContexts,
1720     TiffFrameEncode_SetPalette,
1721     TiffFrameEncode_SetThumbnail,
1722     TiffFrameEncode_WritePixels,
1723     TiffFrameEncode_WriteSource,
1724     TiffFrameEncode_Commit,
1725     TiffFrameEncode_GetMetadataQueryWriter
1726 };
1727
1728 static HRESULT WINAPI TiffEncoder_QueryInterface(IWICBitmapEncoder *iface, REFIID iid,
1729     void **ppv)
1730 {
1731     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1732     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
1733
1734     if (!ppv) return E_INVALIDARG;
1735
1736     if (IsEqualIID(&IID_IUnknown, iid) ||
1737         IsEqualIID(&IID_IWICBitmapEncoder, iid))
1738     {
1739         *ppv = &This->IWICBitmapEncoder_iface;
1740     }
1741     else
1742     {
1743         *ppv = NULL;
1744         return E_NOINTERFACE;
1745     }
1746
1747     IUnknown_AddRef((IUnknown*)*ppv);
1748     return S_OK;
1749 }
1750
1751 static ULONG WINAPI TiffEncoder_AddRef(IWICBitmapEncoder *iface)
1752 {
1753     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1754     ULONG ref = InterlockedIncrement(&This->ref);
1755
1756     TRACE("(%p) refcount=%u\n", iface, ref);
1757
1758     return ref;
1759 }
1760
1761 static ULONG WINAPI TiffEncoder_Release(IWICBitmapEncoder *iface)
1762 {
1763     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1764     ULONG ref = InterlockedDecrement(&This->ref);
1765
1766     TRACE("(%p) refcount=%u\n", iface, ref);
1767
1768     if (ref == 0)
1769     {
1770         if (This->tiff) pTIFFClose(This->tiff);
1771         if (This->stream) IStream_Release(This->stream);
1772         This->lock.DebugInfo->Spare[0] = 0;
1773         DeleteCriticalSection(&This->lock);
1774         HeapFree(GetProcessHeap(), 0, This);
1775     }
1776
1777     return ref;
1778 }
1779
1780 static HRESULT WINAPI TiffEncoder_Initialize(IWICBitmapEncoder *iface,
1781     IStream *pIStream, WICBitmapEncoderCacheOption cacheOption)
1782 {
1783     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1784     TIFF *tiff;
1785     HRESULT hr=S_OK;
1786
1787     TRACE("(%p,%p,%u)\n", iface, pIStream, cacheOption);
1788
1789     EnterCriticalSection(&This->lock);
1790
1791     if (This->initialized || This->committed)
1792     {
1793         hr = WINCODEC_ERR_WRONGSTATE;
1794         goto exit;
1795     }
1796
1797     tiff = tiff_open_stream(pIStream, "w");
1798
1799     if (!tiff)
1800     {
1801         hr = E_FAIL;
1802         goto exit;
1803     }
1804
1805     This->tiff = tiff;
1806     This->stream = pIStream;
1807     IStream_AddRef(pIStream);
1808     This->initialized = TRUE;
1809
1810 exit:
1811     LeaveCriticalSection(&This->lock);
1812     return hr;
1813 }
1814
1815 static HRESULT WINAPI TiffEncoder_GetContainerFormat(IWICBitmapEncoder *iface,
1816     GUID *pguidContainerFormat)
1817 {
1818     memcpy(pguidContainerFormat, &GUID_ContainerFormatTiff, sizeof(GUID));
1819     return S_OK;
1820 }
1821
1822 static HRESULT WINAPI TiffEncoder_GetEncoderInfo(IWICBitmapEncoder *iface,
1823     IWICBitmapEncoderInfo **ppIEncoderInfo)
1824 {
1825     FIXME("(%p,%p): stub\n", iface, ppIEncoderInfo);
1826     return E_NOTIMPL;
1827 }
1828
1829 static HRESULT WINAPI TiffEncoder_SetColorContexts(IWICBitmapEncoder *iface,
1830     UINT cCount, IWICColorContext **ppIColorContext)
1831 {
1832     FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
1833     return E_NOTIMPL;
1834 }
1835
1836 static HRESULT WINAPI TiffEncoder_SetPalette(IWICBitmapEncoder *iface, IWICPalette *pIPalette)
1837 {
1838     TRACE("(%p,%p)\n", iface, pIPalette);
1839     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1840 }
1841
1842 static HRESULT WINAPI TiffEncoder_SetThumbnail(IWICBitmapEncoder *iface, IWICBitmapSource *pIThumbnail)
1843 {
1844     TRACE("(%p,%p)\n", iface, pIThumbnail);
1845     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1846 }
1847
1848 static HRESULT WINAPI TiffEncoder_SetPreview(IWICBitmapEncoder *iface, IWICBitmapSource *pIPreview)
1849 {
1850     TRACE("(%p,%p)\n", iface, pIPreview);
1851     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1852 }
1853
1854 static HRESULT WINAPI TiffEncoder_CreateNewFrame(IWICBitmapEncoder *iface,
1855     IWICBitmapFrameEncode **ppIFrameEncode, IPropertyBag2 **ppIEncoderOptions)
1856 {
1857     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1858     TiffFrameEncode *result;
1859
1860     HRESULT hr=S_OK;
1861
1862     TRACE("(%p,%p,%p)\n", iface, ppIFrameEncode, ppIEncoderOptions);
1863
1864     EnterCriticalSection(&This->lock);
1865
1866     if (!This->initialized || This->committed)
1867     {
1868         hr = WINCODEC_ERR_WRONGSTATE;
1869     }
1870     else if (This->num_frames != This->num_frames_committed)
1871     {
1872         FIXME("New frame created before previous frame was committed\n");
1873         hr = E_FAIL;
1874     }
1875
1876     if (SUCCEEDED(hr))
1877     {
1878         hr = CreatePropertyBag2(ppIEncoderOptions);
1879     }
1880
1881     if (SUCCEEDED(hr))
1882     {
1883         result = HeapAlloc(GetProcessHeap(), 0, sizeof(*result));
1884
1885         if (result)
1886         {
1887             result->IWICBitmapFrameEncode_iface.lpVtbl = &TiffFrameEncode_Vtbl;
1888             result->ref = 1;
1889             result->parent = This;
1890             result->initialized = FALSE;
1891             result->info_written = FALSE;
1892             result->committed = FALSE;
1893             result->format = NULL;
1894             result->width = 0;
1895             result->height = 0;
1896             result->xres = 0.0;
1897             result->yres = 0.0;
1898             result->lines_written = 0;
1899
1900             IWICBitmapEncoder_AddRef(iface);
1901             *ppIFrameEncode = &result->IWICBitmapFrameEncode_iface;
1902
1903             if (This->num_frames != 0)
1904                 pTIFFWriteDirectory(This->tiff);
1905
1906             This->num_frames++;
1907         }
1908         else
1909             hr = E_OUTOFMEMORY;
1910
1911         if (FAILED(hr))
1912         {
1913             IPropertyBag2_Release(*ppIEncoderOptions);
1914             *ppIEncoderOptions = NULL;
1915         }
1916     }
1917
1918     LeaveCriticalSection(&This->lock);
1919
1920     return hr;
1921 }
1922
1923 static HRESULT WINAPI TiffEncoder_Commit(IWICBitmapEncoder *iface)
1924 {
1925     TiffEncoder *This = impl_from_IWICBitmapEncoder(iface);
1926
1927     TRACE("(%p)\n", iface);
1928
1929     EnterCriticalSection(&This->lock);
1930
1931     if (!This->initialized || This->committed)
1932     {
1933         LeaveCriticalSection(&This->lock);
1934         return WINCODEC_ERR_WRONGSTATE;
1935     }
1936
1937     pTIFFClose(This->tiff);
1938     IStream_Release(This->stream);
1939     This->stream = NULL;
1940     This->tiff = NULL;
1941
1942     This->committed = TRUE;
1943
1944     LeaveCriticalSection(&This->lock);
1945
1946     return S_OK;
1947 }
1948
1949 static HRESULT WINAPI TiffEncoder_GetMetadataQueryWriter(IWICBitmapEncoder *iface,
1950     IWICMetadataQueryWriter **ppIMetadataQueryWriter)
1951 {
1952     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryWriter);
1953     return E_NOTIMPL;
1954 }
1955
1956 static const IWICBitmapEncoderVtbl TiffEncoder_Vtbl = {
1957     TiffEncoder_QueryInterface,
1958     TiffEncoder_AddRef,
1959     TiffEncoder_Release,
1960     TiffEncoder_Initialize,
1961     TiffEncoder_GetContainerFormat,
1962     TiffEncoder_GetEncoderInfo,
1963     TiffEncoder_SetColorContexts,
1964     TiffEncoder_SetPalette,
1965     TiffEncoder_SetThumbnail,
1966     TiffEncoder_SetPreview,
1967     TiffEncoder_CreateNewFrame,
1968     TiffEncoder_Commit,
1969     TiffEncoder_GetMetadataQueryWriter
1970 };
1971
1972 HRESULT TiffEncoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
1973 {
1974     TiffEncoder *This;
1975     HRESULT ret;
1976
1977     TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);
1978
1979     *ppv = NULL;
1980
1981     if (pUnkOuter) return CLASS_E_NOAGGREGATION;
1982
1983     if (!load_libtiff())
1984     {
1985         ERR("Failed writing TIFF because unable to load %s\n",SONAME_LIBTIFF);
1986         return E_FAIL;
1987     }
1988
1989     This = HeapAlloc(GetProcessHeap(), 0, sizeof(TiffEncoder));
1990     if (!This) return E_OUTOFMEMORY;
1991
1992     This->IWICBitmapEncoder_iface.lpVtbl = &TiffEncoder_Vtbl;
1993     This->ref = 1;
1994     This->stream = NULL;
1995     InitializeCriticalSection(&This->lock);
1996     This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": TiffEncoder.lock");
1997     This->tiff = NULL;
1998     This->initialized = FALSE;
1999     This->num_frames = 0;
2000     This->num_frames_committed = 0;
2001     This->committed = FALSE;
2002
2003     ret = IWICBitmapEncoder_QueryInterface(&This->IWICBitmapEncoder_iface, iid, ppv);
2004     IWICBitmapEncoder_Release(&This->IWICBitmapEncoder_iface);
2005
2006     return ret;
2007 }
2008
2009 #else /* !SONAME_LIBTIFF */
2010
2011 HRESULT TiffDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
2012 {
2013     ERR("Trying to load TIFF picture, but Wine was compiled without TIFF support.\n");
2014     return E_FAIL;
2015 }
2016
2017 HRESULT TiffEncoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
2018 {
2019     ERR("Trying to save TIFF picture, but Wine was compiled without TIFF support.\n");
2020     return E_FAIL;
2021 }
2022
2023 #endif