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