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