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