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