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