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