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