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