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