windowscodecs: Add a stub implementation of IWICBitmapFlipRotator.
[wine] / dlls / windowscodecs / bmpdecode.c
1 /*
2  * Copyright 2009 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
21 #include <stdarg.h>
22
23 #define COBJMACROS
24
25 #include "windef.h"
26 #include "winbase.h"
27 #include "winreg.h"
28 #include "wingdi.h"
29 #include "objbase.h"
30 #include "wincodec.h"
31
32 #include "wincodecs_private.h"
33
34 #include "wine/debug.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(wincodecs);
37
38 typedef struct {
39     DWORD bc2Size;
40     DWORD bc2Width;
41     DWORD bc2Height;
42     WORD  bc2Planes;
43     WORD  bc2BitCount;
44     DWORD bc2Compression;
45     DWORD bc2SizeImage;
46     DWORD bc2XRes;
47     DWORD bc2YRes;
48     DWORD bc2ClrUsed;
49     DWORD bc2ClrImportant;
50     /* same as BITMAPINFOHEADER until this point */
51     WORD  bc2ResUnit;
52     WORD  bc2Reserved;
53     WORD  bc2Orientation;
54     WORD  bc2Halftoning;
55     DWORD bc2HalftoneSize1;
56     DWORD bc2HalftoneSize2;
57     DWORD bc2ColorSpace;
58     DWORD bc2AppData;
59 } BITMAPCOREHEADER2;
60
61 struct BmpDecoder;
62 typedef HRESULT (*ReadDataFunc)(struct BmpDecoder* This);
63
64 typedef struct BmpDecoder {
65     const IWICBitmapDecoderVtbl *lpVtbl;
66     const IWICBitmapFrameDecodeVtbl *lpFrameVtbl;
67     LONG ref;
68     BOOL initialized;
69     IStream *stream;
70     BITMAPFILEHEADER bfh;
71     BITMAPV5HEADER bih;
72     const WICPixelFormatGUID *pixelformat;
73     int bitsperpixel;
74     ReadDataFunc read_data_func;
75     INT stride;
76     BYTE *imagedata;
77     BYTE *imagedatastart;
78     CRITICAL_SECTION lock; /* must be held when initialized/imagedata is set or stream is accessed */
79 } BmpDecoder;
80
81 static inline BmpDecoder *impl_from_frame(IWICBitmapFrameDecode *iface)
82 {
83     return CONTAINING_RECORD(iface, BmpDecoder, lpFrameVtbl);
84 }
85
86 static HRESULT WINAPI BmpFrameDecode_QueryInterface(IWICBitmapFrameDecode *iface, REFIID iid,
87     void **ppv)
88 {
89     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
90
91     if (!ppv) return E_INVALIDARG;
92
93     if (IsEqualIID(&IID_IUnknown, iid) ||
94         IsEqualIID(&IID_IWICBitmapSource, iid) ||
95         IsEqualIID(&IID_IWICBitmapFrameDecode, iid))
96     {
97         *ppv = iface;
98     }
99     else
100     {
101         *ppv = NULL;
102         return E_NOINTERFACE;
103     }
104
105     IUnknown_AddRef((IUnknown*)*ppv);
106     return S_OK;
107 }
108
109 static ULONG WINAPI BmpFrameDecode_AddRef(IWICBitmapFrameDecode *iface)
110 {
111     BmpDecoder *This = impl_from_frame(iface);
112
113     return IUnknown_AddRef((IUnknown*)This);
114 }
115
116 static ULONG WINAPI BmpFrameDecode_Release(IWICBitmapFrameDecode *iface)
117 {
118     BmpDecoder *This = impl_from_frame(iface);
119
120     return IUnknown_Release((IUnknown*)This);
121 }
122
123 static HRESULT WINAPI BmpFrameDecode_GetSize(IWICBitmapFrameDecode *iface,
124     UINT *puiWidth, UINT *puiHeight)
125 {
126     BmpDecoder *This = impl_from_frame(iface);
127     TRACE("(%p,%p,%p)\n", iface, puiWidth, puiHeight);
128
129     if (This->bih.bV5Size == sizeof(BITMAPCOREHEADER))
130     {
131         BITMAPCOREHEADER *bch = (BITMAPCOREHEADER*)&This->bih;
132         *puiWidth = bch->bcWidth;
133         *puiHeight = bch->bcHeight;
134     }
135     else
136     {
137         *puiWidth = This->bih.bV5Width;
138         *puiHeight = abs(This->bih.bV5Height);
139     }
140     return S_OK;
141 }
142
143 static HRESULT WINAPI BmpFrameDecode_GetPixelFormat(IWICBitmapFrameDecode *iface,
144     WICPixelFormatGUID *pPixelFormat)
145 {
146     BmpDecoder *This = impl_from_frame(iface);
147     TRACE("(%p,%p)\n", iface, pPixelFormat);
148
149     memcpy(pPixelFormat, This->pixelformat, sizeof(GUID));
150
151     return S_OK;
152 }
153
154 static HRESULT BmpHeader_GetResolution(BITMAPV5HEADER *bih, double *pDpiX, double *pDpiY)
155 {
156     switch (bih->bV5Size)
157     {
158     case sizeof(BITMAPCOREHEADER):
159         *pDpiX = 96.0;
160         *pDpiY = 96.0;
161         return S_OK;
162     case sizeof(BITMAPCOREHEADER2):
163     case sizeof(BITMAPINFOHEADER):
164     case sizeof(BITMAPV4HEADER):
165     case sizeof(BITMAPV5HEADER):
166         *pDpiX = bih->bV5XPelsPerMeter * 0.0254;
167         *pDpiY = bih->bV5YPelsPerMeter * 0.0254;
168         return S_OK;
169     default:
170         return E_FAIL;
171     }
172 }
173
174 static HRESULT WINAPI BmpFrameDecode_GetResolution(IWICBitmapFrameDecode *iface,
175     double *pDpiX, double *pDpiY)
176 {
177     BmpDecoder *This = impl_from_frame(iface);
178     TRACE("(%p,%p,%p)\n", iface, pDpiX, pDpiY);
179
180     return BmpHeader_GetResolution(&This->bih, pDpiX, pDpiY);
181 }
182
183 static HRESULT WINAPI BmpFrameDecode_CopyPalette(IWICBitmapFrameDecode *iface,
184     IWICPalette *pIPalette)
185 {
186     HRESULT hr;
187     BmpDecoder *This = impl_from_frame(iface);
188     int count;
189     WICColor *wiccolors=NULL;
190     RGBTRIPLE *bgrcolors=NULL;
191
192     TRACE("(%p,%p)\n", iface, pIPalette);
193
194     EnterCriticalSection(&This->lock);
195
196     if (This->bih.bV5Size == sizeof(BITMAPCOREHEADER))
197     {
198         BITMAPCOREHEADER *bch = (BITMAPCOREHEADER*)&This->bih;
199         if (bch->bcBitCount <= 8)
200         {
201             /* 2**n colors in BGR format after the header */
202             ULONG tablesize, bytesread;
203             LARGE_INTEGER offset;
204             int i;
205
206             count = 1 << bch->bcBitCount;
207             wiccolors = HeapAlloc(GetProcessHeap(), 0, sizeof(WICColor) * count);
208             tablesize = sizeof(RGBTRIPLE) * count;
209             bgrcolors = HeapAlloc(GetProcessHeap(), 0, tablesize);
210             if (!wiccolors || !bgrcolors)
211             {
212                 hr = E_OUTOFMEMORY;
213                 goto end;
214             }
215
216             offset.QuadPart = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER);
217             hr = IStream_Seek(This->stream, offset, STREAM_SEEK_SET, NULL);
218             if (FAILED(hr)) goto end;
219
220             hr = IStream_Read(This->stream, bgrcolors, tablesize, &bytesread);
221             if (FAILED(hr)) goto end;
222             if (bytesread != tablesize) {
223                 hr = E_FAIL;
224                 goto end;
225             }
226
227             for (i=0; i<count; i++)
228             {
229                 wiccolors[i] = 0xff000000|
230                                (bgrcolors[i].rgbtRed<<16)|
231                                (bgrcolors[i].rgbtGreen<<8)|
232                                bgrcolors[i].rgbtBlue;
233             }
234         }
235         else
236         {
237             hr = WINCODEC_ERR_PALETTEUNAVAILABLE;
238             goto end;
239         }
240     }
241     else
242     {
243         if (This->bih.bV5BitCount <= 8)
244         {
245             ULONG tablesize, bytesread;
246             LARGE_INTEGER offset;
247             int i;
248
249             if (This->bih.bV5ClrUsed == 0)
250                 count = 1 << This->bih.bV5BitCount;
251             else
252                 count = This->bih.bV5ClrUsed;
253
254             tablesize = sizeof(WICColor) * count;
255             wiccolors = HeapAlloc(GetProcessHeap(), 0, tablesize);
256             if (!wiccolors)
257             {
258                 hr = E_OUTOFMEMORY;
259                 goto end;
260             }
261
262             offset.QuadPart = sizeof(BITMAPFILEHEADER) + This->bih.bV5Size;
263             hr = IStream_Seek(This->stream, offset, STREAM_SEEK_SET, NULL);
264             if (FAILED(hr)) goto end;
265
266             hr = IStream_Read(This->stream, wiccolors, tablesize, &bytesread);
267             if (FAILED(hr)) goto end;
268             if (bytesread != tablesize) {
269                 hr = E_FAIL;
270                 goto end;
271             }
272
273             /* convert from BGR to BGRA by setting alpha to 100% */
274             for (i=0; i<count; i++)
275                 wiccolors[i] |= 0xff000000;
276         }
277         else
278         {
279             hr = WINCODEC_ERR_PALETTEUNAVAILABLE;
280             goto end;
281         }
282     }
283
284 end:
285
286     LeaveCriticalSection(&This->lock);
287
288     if (SUCCEEDED(hr))
289         hr = IWICPalette_InitializeCustom(pIPalette, wiccolors, count);
290
291     HeapFree(GetProcessHeap(), 0, wiccolors);
292     HeapFree(GetProcessHeap(), 0, bgrcolors);
293     return hr;
294 }
295
296 static HRESULT WINAPI BmpFrameDecode_CopyPixels(IWICBitmapFrameDecode *iface,
297     const WICRect *prc, UINT cbStride, UINT cbBufferSize, BYTE *pbBuffer)
298 {
299     BmpDecoder *This = impl_from_frame(iface);
300     HRESULT hr=S_OK;
301     UINT width, height;
302     TRACE("(%p,%p,%u,%u,%p)\n", iface, prc, cbStride, cbBufferSize, pbBuffer);
303
304     EnterCriticalSection(&This->lock);
305     if (!This->imagedata)
306     {
307         hr = This->read_data_func(This);
308     }
309     LeaveCriticalSection(&This->lock);
310     if (FAILED(hr)) return hr;
311
312     hr = BmpFrameDecode_GetSize(iface, &width, &height);
313     if (FAILED(hr)) return hr;
314
315     return copy_pixels(This->bitsperpixel, This->imagedatastart,
316         width, height, This->stride,
317         prc, cbStride, cbBufferSize, pbBuffer);
318 }
319
320 static HRESULT WINAPI BmpFrameDecode_GetMetadataQueryReader(IWICBitmapFrameDecode *iface,
321     IWICMetadataQueryReader **ppIMetadataQueryReader)
322 {
323     TRACE("(%p,%p)\n", iface, ppIMetadataQueryReader);
324     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
325 }
326
327 static HRESULT WINAPI BmpFrameDecode_GetColorContexts(IWICBitmapFrameDecode *iface,
328     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
329 {
330     TRACE("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);
331     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
332 }
333
334 static HRESULT WINAPI BmpFrameDecode_GetThumbnail(IWICBitmapFrameDecode *iface,
335     IWICBitmapSource **ppIThumbnail)
336 {
337     TRACE("(%p,%p)\n", iface, ppIThumbnail);
338     return WINCODEC_ERR_CODECNOTHUMBNAIL;
339 }
340
341 static HRESULT BmpFrameDecode_ReadUncompressed(BmpDecoder* This)
342 {
343     UINT bytesperrow;
344     UINT width, height;
345     UINT datasize;
346     int bottomup;
347     HRESULT hr;
348     LARGE_INTEGER offbits;
349     ULONG bytesread;
350
351     if (This->bih.bV5Size == sizeof(BITMAPCOREHEADER))
352     {
353         BITMAPCOREHEADER *bch = (BITMAPCOREHEADER*)&This->bih;
354         width = bch->bcWidth;
355         height = bch->bcHeight;
356         bottomup = 1;
357     }
358     else
359     {
360         width = This->bih.bV5Width;
361         height = abs(This->bih.bV5Height);
362         bottomup = (This->bih.bV5Height > 0);
363     }
364
365     /* row sizes in BMP files must be divisible by 4 bytes */
366     bytesperrow = (((width * This->bitsperpixel)+31)/32)*4;
367     datasize = bytesperrow * height;
368
369     This->imagedata = HeapAlloc(GetProcessHeap(), 0, datasize);
370     if (!This->imagedata) return E_OUTOFMEMORY;
371
372     offbits.QuadPart = This->bfh.bfOffBits;
373     hr = IStream_Seek(This->stream, offbits, STREAM_SEEK_SET, NULL);
374     if (FAILED(hr)) goto fail;
375
376     hr = IStream_Read(This->stream, This->imagedata, datasize, &bytesread);
377     if (FAILED(hr) || bytesread != datasize) goto fail;
378
379     if (bottomup)
380     {
381         This->imagedatastart = This->imagedata + (height-1) * bytesperrow;
382         This->stride = -bytesperrow;
383     }
384     else
385     {
386         This->imagedatastart = This->imagedata;
387         This->stride = bytesperrow;
388     }
389     return S_OK;
390
391 fail:
392     HeapFree(GetProcessHeap(), 0, This->imagedata);
393     This->imagedata = NULL;
394     if (SUCCEEDED(hr)) hr = E_FAIL;
395     return hr;
396 }
397
398 static HRESULT BmpFrameDecode_ReadRLE8(BmpDecoder* This)
399 {
400     UINT bytesperrow;
401     UINT width, height;
402     BYTE *rledata, *cursor, *rledataend;
403     UINT rlesize, datasize, palettesize;
404     DWORD palette[256];
405     UINT x, y;
406     DWORD *bgrdata;
407     HRESULT hr;
408     LARGE_INTEGER offbits;
409     ULONG bytesread;
410
411     width = This->bih.bV5Width;
412     height = abs(This->bih.bV5Height);
413     bytesperrow = width * 4;
414     datasize = bytesperrow * height;
415     rlesize = This->bih.bV5SizeImage;
416     if (This->bih.bV5ClrUsed && This->bih.bV5ClrUsed < 256)
417         palettesize = 4 * This->bih.bV5ClrUsed;
418     else
419         palettesize = 4 * 256;
420
421     rledata = HeapAlloc(GetProcessHeap(), 0, rlesize);
422     This->imagedata = HeapAlloc(GetProcessHeap(), 0, datasize);
423     if (!This->imagedata || !rledata)
424     {
425         hr = E_OUTOFMEMORY;
426         goto fail;
427     }
428
429     /* read palette */
430     offbits.QuadPart = sizeof(BITMAPFILEHEADER) + This->bih.bV5Size;
431     hr = IStream_Seek(This->stream, offbits, STREAM_SEEK_SET, NULL);
432     if (FAILED(hr)) goto fail;
433
434     hr = IStream_Read(This->stream, palette, palettesize, &bytesread);
435     if (FAILED(hr) || bytesread != palettesize) goto fail;
436
437     /* read RLE data */
438     offbits.QuadPart = This->bfh.bfOffBits;
439     hr = IStream_Seek(This->stream, offbits, STREAM_SEEK_SET, NULL);
440     if (FAILED(hr)) goto fail;
441
442     hr = IStream_Read(This->stream, rledata, rlesize, &bytesread);
443     if (FAILED(hr) || bytesread != rlesize) goto fail;
444
445     /* decode RLE */
446     bgrdata = (DWORD*)This->imagedata;
447     x = 0;
448     y = 0;
449     rledataend = rledata + rlesize;
450     cursor = rledata;
451     while (cursor < rledataend && y < height)
452     {
453         BYTE length = *cursor++;
454         if (length == 0)
455         {
456             /* escape code */
457             BYTE escape = *cursor++;
458             switch(escape)
459             {
460             case 0: /* end of line */
461                 x = 0;
462                 y++;
463                 break;
464             case 1: /* end of bitmap */
465                 goto end;
466             case 2: /* delta */
467                 if (cursor < rledataend)
468                 {
469                     x += *cursor++;
470                     y += *cursor++;
471                 }
472                 break;
473             default: /* absolute mode */
474                 length = escape;
475                 while (cursor < rledataend && length-- && x < width)
476                     bgrdata[y*width + x++] = palette[*cursor++];
477                 if (escape & 1) cursor++; /* skip pad byte */
478             }
479         }
480         else
481         {
482             DWORD color = palette[*cursor++];
483             while (length-- && x < width)
484                 bgrdata[y*width + x++] = color;
485         }
486     }
487
488 end:
489     HeapFree(GetProcessHeap(), 0, rledata);
490
491     This->imagedatastart = This->imagedata + (height-1) * bytesperrow;
492     This->stride = -bytesperrow;
493
494     return S_OK;
495
496 fail:
497     HeapFree(GetProcessHeap(), 0, rledata);
498     HeapFree(GetProcessHeap(), 0, This->imagedata);
499     This->imagedata = NULL;
500     if (SUCCEEDED(hr)) hr = E_FAIL;
501     return hr;
502 }
503
504 static HRESULT BmpFrameDecode_ReadRLE4(BmpDecoder* This)
505 {
506     UINT bytesperrow;
507     UINT width, height;
508     BYTE *rledata, *cursor, *rledataend;
509     UINT rlesize, datasize, palettesize;
510     DWORD palette[16];
511     UINT x, y;
512     DWORD *bgrdata;
513     HRESULT hr;
514     LARGE_INTEGER offbits;
515     ULONG bytesread;
516
517     width = This->bih.bV5Width;
518     height = abs(This->bih.bV5Height);
519     bytesperrow = width * 4;
520     datasize = bytesperrow * height;
521     rlesize = This->bih.bV5SizeImage;
522     if (This->bih.bV5ClrUsed && This->bih.bV5ClrUsed < 16)
523         palettesize = 4 * This->bih.bV5ClrUsed;
524     else
525         palettesize = 4 * 16;
526
527     rledata = HeapAlloc(GetProcessHeap(), 0, rlesize);
528     This->imagedata = HeapAlloc(GetProcessHeap(), 0, datasize);
529     if (!This->imagedata || !rledata)
530     {
531         hr = E_OUTOFMEMORY;
532         goto fail;
533     }
534
535     /* read palette */
536     offbits.QuadPart = sizeof(BITMAPFILEHEADER) + This->bih.bV5Size;
537     hr = IStream_Seek(This->stream, offbits, STREAM_SEEK_SET, NULL);
538     if (FAILED(hr)) goto fail;
539
540     hr = IStream_Read(This->stream, palette, palettesize, &bytesread);
541     if (FAILED(hr) || bytesread != palettesize) goto fail;
542
543     /* read RLE data */
544     offbits.QuadPart = This->bfh.bfOffBits;
545     hr = IStream_Seek(This->stream, offbits, STREAM_SEEK_SET, NULL);
546     if (FAILED(hr)) goto fail;
547
548     hr = IStream_Read(This->stream, rledata, rlesize, &bytesread);
549     if (FAILED(hr) || bytesread != rlesize) goto fail;
550
551     /* decode RLE */
552     bgrdata = (DWORD*)This->imagedata;
553     x = 0;
554     y = 0;
555     rledataend = rledata + rlesize;
556     cursor = rledata;
557     while (cursor < rledataend && y < height)
558     {
559         BYTE length = *cursor++;
560         if (length == 0)
561         {
562             /* escape code */
563             BYTE escape = *cursor++;
564             switch(escape)
565             {
566             case 0: /* end of line */
567                 x = 0;
568                 y++;
569                 break;
570             case 1: /* end of bitmap */
571                 goto end;
572             case 2: /* delta */
573                 if (cursor < rledataend)
574                 {
575                     x += *cursor++;
576                     y += *cursor++;
577                 }
578                 break;
579             default: /* absolute mode */
580                 length = escape;
581                 while (cursor < rledataend && length-- && x < width)
582                 {
583                     BYTE colors = *cursor++;
584                     bgrdata[y*width + x++] = palette[colors>>4];
585                     if (length-- && x < width)
586                         bgrdata[y*width + x++] = palette[colors&0xf];
587                     else
588                         break;
589                 }
590                 if ((cursor - rledata) & 1) cursor++; /* skip pad byte */
591             }
592         }
593         else
594         {
595             BYTE colors = *cursor++;
596             DWORD color1 = palette[colors>>4];
597             DWORD color2 = palette[colors&0xf];
598             while (length-- && x < width)
599             {
600                 bgrdata[y*width + x++] = color1;
601                 if (length-- && x < width)
602                     bgrdata[y*width + x++] = color2;
603                 else
604                     break;
605             }
606         }
607     }
608
609 end:
610     HeapFree(GetProcessHeap(), 0, rledata);
611
612     This->imagedatastart = This->imagedata + (height-1) * bytesperrow;
613     This->stride = -bytesperrow;
614
615     return S_OK;
616
617 fail:
618     HeapFree(GetProcessHeap(), 0, rledata);
619     HeapFree(GetProcessHeap(), 0, This->imagedata);
620     This->imagedata = NULL;
621     if (SUCCEEDED(hr)) hr = E_FAIL;
622     return hr;
623 }
624
625 static HRESULT BmpFrameDecode_ReadUnsupported(BmpDecoder* This)
626 {
627     return E_FAIL;
628 }
629
630 struct bitfields_format {
631     WORD bitcount; /* 0 for end of list */
632     DWORD redmask;
633     DWORD greenmask;
634     DWORD bluemask;
635     DWORD alphamask;
636     const WICPixelFormatGUID *pixelformat;
637     ReadDataFunc read_data_func;
638 };
639
640 static const struct bitfields_format bitfields_formats[] = {
641     {16,0x7c00,0x3e0,0x1f,0,&GUID_WICPixelFormat16bppBGR555,BmpFrameDecode_ReadUncompressed},
642     {16,0xf800,0x7e0,0x1f,0,&GUID_WICPixelFormat16bppBGR565,BmpFrameDecode_ReadUncompressed},
643     {32,0xff0000,0xff00,0xff,0,&GUID_WICPixelFormat32bppBGR,BmpFrameDecode_ReadUncompressed},
644     {32,0xff0000,0xff00,0xff,0xff000000,&GUID_WICPixelFormat32bppBGRA,BmpFrameDecode_ReadUncompressed},
645     {0}
646 };
647
648 static const IWICBitmapFrameDecodeVtbl BmpDecoder_FrameVtbl = {
649     BmpFrameDecode_QueryInterface,
650     BmpFrameDecode_AddRef,
651     BmpFrameDecode_Release,
652     BmpFrameDecode_GetSize,
653     BmpFrameDecode_GetPixelFormat,
654     BmpFrameDecode_GetResolution,
655     BmpFrameDecode_CopyPalette,
656     BmpFrameDecode_CopyPixels,
657     BmpFrameDecode_GetMetadataQueryReader,
658     BmpFrameDecode_GetColorContexts,
659     BmpFrameDecode_GetThumbnail
660 };
661
662 static HRESULT BmpDecoder_ReadHeaders(BmpDecoder* This, IStream *stream)
663 {
664     HRESULT hr;
665     ULONG bytestoread, bytesread;
666     LARGE_INTEGER seek;
667
668     if (This->initialized) return WINCODEC_ERR_WRONGSTATE;
669
670     seek.QuadPart = 0;
671     hr = IStream_Seek(stream, seek, STREAM_SEEK_SET, NULL);
672     if (FAILED(hr)) return hr;
673
674     hr = IStream_Read(stream, &This->bfh, sizeof(BITMAPFILEHEADER), &bytesread);
675     if (FAILED(hr)) return hr;
676     if (bytesread != sizeof(BITMAPFILEHEADER) ||
677         This->bfh.bfType != 0x4d42 /* "BM" */) return E_FAIL;
678
679     hr = IStream_Read(stream, &This->bih.bV5Size, sizeof(DWORD), &bytesread);
680     if (FAILED(hr)) return hr;
681     if (bytesread != sizeof(DWORD) ||
682         (This->bih.bV5Size != sizeof(BITMAPCOREHEADER) &&
683          This->bih.bV5Size != sizeof(BITMAPCOREHEADER2) &&
684          This->bih.bV5Size != sizeof(BITMAPINFOHEADER) &&
685          This->bih.bV5Size != sizeof(BITMAPV4HEADER) &&
686          This->bih.bV5Size != sizeof(BITMAPV5HEADER))) return E_FAIL;
687
688     bytestoread = This->bih.bV5Size-sizeof(DWORD);
689     hr = IStream_Read(stream, &This->bih.bV5Width, bytestoread, &bytesread);
690     if (FAILED(hr)) return hr;
691     if (bytestoread != bytesread) return E_FAIL;
692
693     /* if this is a BITMAPINFOHEADER with BI_BITFIELDS compression, we need to
694         read the extra fields */
695     if (This->bih.bV5Size == sizeof(BITMAPINFOHEADER) &&
696         This->bih.bV5Compression == BI_BITFIELDS)
697     {
698         hr = IStream_Read(stream, &This->bih.bV5RedMask, 12, &bytesread);
699         if (FAILED(hr)) return hr;
700         if (bytesread != 12) return E_FAIL;
701         This->bih.bV5AlphaMask = 0;
702     }
703
704     /* decide what kind of bitmap this is and how/if we can read it */
705     if (This->bih.bV5Size == sizeof(BITMAPCOREHEADER))
706     {
707         BITMAPCOREHEADER *bch = (BITMAPCOREHEADER*)&This->bih;
708         TRACE("BITMAPCOREHEADER with depth=%i\n", bch->bcBitCount);
709         This->bitsperpixel = bch->bcBitCount;
710         This->read_data_func = BmpFrameDecode_ReadUncompressed;
711         switch(bch->bcBitCount)
712         {
713         case 1:
714             This->pixelformat = &GUID_WICPixelFormat1bppIndexed;
715             break;
716         case 2:
717             This->pixelformat = &GUID_WICPixelFormat2bppIndexed;
718             break;
719         case 4:
720             This->pixelformat = &GUID_WICPixelFormat4bppIndexed;
721             break;
722         case 8:
723             This->pixelformat = &GUID_WICPixelFormat8bppIndexed;
724             break;
725         case 24:
726             This->pixelformat = &GUID_WICPixelFormat24bppBGR;
727             break;
728         default:
729             This->pixelformat = &GUID_WICPixelFormatUndefined;
730             WARN("unsupported bit depth %i for BITMAPCOREHEADER\n", bch->bcBitCount);
731             break;
732         }
733     }
734     else /* struct is compatible with BITMAPINFOHEADER */
735     {
736         TRACE("bitmap header=%i compression=%i depth=%i\n", This->bih.bV5Size, This->bih.bV5Compression, This->bih.bV5BitCount);
737         switch(This->bih.bV5Compression)
738         {
739         case BI_RGB:
740             This->bitsperpixel = This->bih.bV5BitCount;
741             This->read_data_func = BmpFrameDecode_ReadUncompressed;
742             switch(This->bih.bV5BitCount)
743             {
744             case 1:
745                 This->pixelformat = &GUID_WICPixelFormat1bppIndexed;
746                 break;
747             case 2:
748                 This->pixelformat = &GUID_WICPixelFormat2bppIndexed;
749                 break;
750             case 4:
751                 This->pixelformat = &GUID_WICPixelFormat4bppIndexed;
752                 break;
753             case 8:
754                 This->pixelformat = &GUID_WICPixelFormat8bppIndexed;
755                 break;
756             case 16:
757                 This->pixelformat = &GUID_WICPixelFormat16bppBGR555;
758                 break;
759             case 24:
760                 This->pixelformat = &GUID_WICPixelFormat24bppBGR;
761                 break;
762             case 32:
763                 This->pixelformat = &GUID_WICPixelFormat32bppBGR;
764                 break;
765             default:
766                 This->pixelformat = &GUID_WICPixelFormatUndefined;
767                 FIXME("unsupported bit depth %i for uncompressed RGB\n", This->bih.bV5BitCount);
768             }
769             break;
770         case BI_RLE8:
771             This->bitsperpixel = 32;
772             This->read_data_func = BmpFrameDecode_ReadRLE8;
773             This->pixelformat = &GUID_WICPixelFormat32bppBGR;
774             break;
775         case BI_RLE4:
776             This->bitsperpixel = 32;
777             This->read_data_func = BmpFrameDecode_ReadRLE4;
778             This->pixelformat = &GUID_WICPixelFormat32bppBGR;
779             break;
780         case BI_BITFIELDS:
781         {
782             const struct bitfields_format *format;
783             if (This->bih.bV5Size == sizeof(BITMAPCOREHEADER2))
784             {
785                 /* BCH2 doesn't support bitfields; this is Huffman 1D compression */
786                 This->bitsperpixel = 0;
787                 This->read_data_func = BmpFrameDecode_ReadUnsupported;
788                 This->pixelformat = &GUID_WICPixelFormatUndefined;
789                 FIXME("Huffman 1D compression is unsupported\n");
790                 break;
791             }
792             This->bitsperpixel = This->bih.bV5BitCount;
793             for (format = bitfields_formats; format->bitcount; format++)
794             {
795                 if ((format->bitcount == This->bih.bV5BitCount) &&
796                     (format->redmask == This->bih.bV5RedMask) &&
797                     (format->greenmask == This->bih.bV5GreenMask) &&
798                     (format->bluemask == This->bih.bV5BlueMask) &&
799                     (format->alphamask == This->bih.bV5AlphaMask))
800                 {
801                     This->read_data_func = format->read_data_func;
802                     This->pixelformat = format->pixelformat;
803                     break;
804                 }
805             }
806             if (!format->bitcount)
807             {
808                 This->read_data_func = BmpFrameDecode_ReadUncompressed;
809                 This->pixelformat = &GUID_WICPixelFormatUndefined;
810                 FIXME("unsupported bitfields type depth=%i red=%x green=%x blue=%x alpha=%x\n",
811                     This->bih.bV5BitCount, This->bih.bV5RedMask, This->bih.bV5GreenMask, This->bih.bV5BlueMask, This->bih.bV5AlphaMask);
812             }
813             break;
814         }
815         default:
816             This->bitsperpixel = 0;
817             This->read_data_func = BmpFrameDecode_ReadUnsupported;
818             This->pixelformat = &GUID_WICPixelFormatUndefined;
819             FIXME("unsupported bitmap type header=%i compression=%i depth=%i\n", This->bih.bV5Size, This->bih.bV5Compression, This->bih.bV5BitCount);
820             break;
821         }
822     }
823
824     This->initialized = TRUE;
825
826     return S_OK;
827 }
828
829 static HRESULT WINAPI BmpDecoder_QueryInterface(IWICBitmapDecoder *iface, REFIID iid,
830     void **ppv)
831 {
832     BmpDecoder *This = (BmpDecoder*)iface;
833     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
834
835     if (!ppv) return E_INVALIDARG;
836
837     if (IsEqualIID(&IID_IUnknown, iid) || IsEqualIID(&IID_IWICBitmapDecoder, iid))
838     {
839         *ppv = This;
840     }
841     else
842     {
843         *ppv = NULL;
844         return E_NOINTERFACE;
845     }
846
847     IUnknown_AddRef((IUnknown*)*ppv);
848     return S_OK;
849 }
850
851 static ULONG WINAPI BmpDecoder_AddRef(IWICBitmapDecoder *iface)
852 {
853     BmpDecoder *This = (BmpDecoder*)iface;
854     ULONG ref = InterlockedIncrement(&This->ref);
855
856     TRACE("(%p) refcount=%u\n", iface, ref);
857
858     return ref;
859 }
860
861 static ULONG WINAPI BmpDecoder_Release(IWICBitmapDecoder *iface)
862 {
863     BmpDecoder *This = (BmpDecoder*)iface;
864     ULONG ref = InterlockedDecrement(&This->ref);
865
866     TRACE("(%p) refcount=%u\n", iface, ref);
867
868     if (ref == 0)
869     {
870         if (This->stream) IStream_Release(This->stream);
871         HeapFree(GetProcessHeap(), 0, This->imagedata);
872         This->lock.DebugInfo->Spare[0] = 0;
873         DeleteCriticalSection(&This->lock);
874         HeapFree(GetProcessHeap(), 0, This);
875     }
876
877     return ref;
878 }
879
880 static HRESULT WINAPI BmpDecoder_QueryCapability(IWICBitmapDecoder *iface, IStream *pIStream,
881     DWORD *pdwCapability)
882 {
883     HRESULT hr;
884     BmpDecoder *This = (BmpDecoder*)iface;
885
886     EnterCriticalSection(&This->lock);
887     hr = BmpDecoder_ReadHeaders(This, pIStream);
888     LeaveCriticalSection(&This->lock);
889     if (FAILED(hr)) return hr;
890
891     if (This->read_data_func == BmpFrameDecode_ReadUnsupported)
892         *pdwCapability = 0;
893     else
894         *pdwCapability = WICBitmapDecoderCapabilityCanDecodeAllImages;
895
896     return S_OK;
897 }
898
899 static HRESULT WINAPI BmpDecoder_Initialize(IWICBitmapDecoder *iface, IStream *pIStream,
900     WICDecodeOptions cacheOptions)
901 {
902     HRESULT hr;
903     BmpDecoder *This = (BmpDecoder*)iface;
904
905     EnterCriticalSection(&This->lock);
906     hr = BmpDecoder_ReadHeaders(This, pIStream);
907
908     if (SUCCEEDED(hr))
909     {
910         This->stream = pIStream;
911         IStream_AddRef(pIStream);
912     }
913     LeaveCriticalSection(&This->lock);
914
915     return hr;
916 }
917
918 static HRESULT WINAPI BmpDecoder_GetContainerFormat(IWICBitmapDecoder *iface,
919     GUID *pguidContainerFormat)
920 {
921     memcpy(pguidContainerFormat, &GUID_ContainerFormatBmp, sizeof(GUID));
922     return S_OK;
923 }
924
925 static HRESULT WINAPI BmpDecoder_GetDecoderInfo(IWICBitmapDecoder *iface,
926     IWICBitmapDecoderInfo **ppIDecoderInfo)
927 {
928     HRESULT hr;
929     IWICComponentInfo *compinfo;
930
931     TRACE("(%p,%p)\n", iface, ppIDecoderInfo);
932
933     hr = CreateComponentInfo(&CLSID_WICBmpDecoder, &compinfo);
934     if (FAILED(hr)) return hr;
935
936     hr = IWICComponentInfo_QueryInterface(compinfo, &IID_IWICBitmapDecoderInfo,
937         (void**)ppIDecoderInfo);
938
939     IWICComponentInfo_Release(compinfo);
940
941     return hr;
942 }
943
944 static HRESULT WINAPI BmpDecoder_CopyPalette(IWICBitmapDecoder *iface,
945     IWICPalette *pIPalette)
946 {
947     TRACE("(%p,%p)\n", iface, pIPalette);
948
949     return WINCODEC_ERR_PALETTEUNAVAILABLE;
950 }
951
952 static HRESULT WINAPI BmpDecoder_GetMetadataQueryReader(IWICBitmapDecoder *iface,
953     IWICMetadataQueryReader **ppIMetadataQueryReader)
954 {
955     TRACE("(%p,%p)\n", iface, ppIMetadataQueryReader);
956     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
957 }
958
959 static HRESULT WINAPI BmpDecoder_GetPreview(IWICBitmapDecoder *iface,
960     IWICBitmapSource **ppIBitmapSource)
961 {
962     TRACE("(%p,%p)\n", iface, ppIBitmapSource);
963     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
964 }
965
966 static HRESULT WINAPI BmpDecoder_GetColorContexts(IWICBitmapDecoder *iface,
967     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
968 {
969     TRACE("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);
970     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
971 }
972
973 static HRESULT WINAPI BmpDecoder_GetThumbnail(IWICBitmapDecoder *iface,
974     IWICBitmapSource **ppIThumbnail)
975 {
976     TRACE("(%p,%p)\n", iface, ppIThumbnail);
977     return WINCODEC_ERR_CODECNOTHUMBNAIL;
978 }
979
980 static HRESULT WINAPI BmpDecoder_GetFrameCount(IWICBitmapDecoder *iface,
981     UINT *pCount)
982 {
983     *pCount = 1;
984     return S_OK;
985 }
986
987 static HRESULT WINAPI BmpDecoder_GetFrame(IWICBitmapDecoder *iface,
988     UINT index, IWICBitmapFrameDecode **ppIBitmapFrame)
989 {
990     BmpDecoder *This = (BmpDecoder*)iface;
991
992     if (index != 0) return E_INVALIDARG;
993
994     if (!This->stream) return WINCODEC_ERR_WRONGSTATE;
995
996     *ppIBitmapFrame = (IWICBitmapFrameDecode*)&This->lpFrameVtbl;
997     IWICBitmapDecoder_AddRef(iface);
998
999     return S_OK;
1000 }
1001
1002 static const IWICBitmapDecoderVtbl BmpDecoder_Vtbl = {
1003     BmpDecoder_QueryInterface,
1004     BmpDecoder_AddRef,
1005     BmpDecoder_Release,
1006     BmpDecoder_QueryCapability,
1007     BmpDecoder_Initialize,
1008     BmpDecoder_GetContainerFormat,
1009     BmpDecoder_GetDecoderInfo,
1010     BmpDecoder_CopyPalette,
1011     BmpDecoder_GetMetadataQueryReader,
1012     BmpDecoder_GetPreview,
1013     BmpDecoder_GetColorContexts,
1014     BmpDecoder_GetThumbnail,
1015     BmpDecoder_GetFrameCount,
1016     BmpDecoder_GetFrame
1017 };
1018
1019 HRESULT BmpDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
1020 {
1021     BmpDecoder *This;
1022     HRESULT ret;
1023
1024     TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);
1025
1026     *ppv = NULL;
1027
1028     if (pUnkOuter) return CLASS_E_NOAGGREGATION;
1029
1030     This = HeapAlloc(GetProcessHeap(), 0, sizeof(BmpDecoder));
1031     if (!This) return E_OUTOFMEMORY;
1032
1033     This->lpVtbl = &BmpDecoder_Vtbl;
1034     This->lpFrameVtbl = &BmpDecoder_FrameVtbl;
1035     This->ref = 1;
1036     This->initialized = FALSE;
1037     This->stream = NULL;
1038     This->imagedata = NULL;
1039     InitializeCriticalSection(&This->lock);
1040     This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": BmpDecoder.lock");
1041
1042     ret = IUnknown_QueryInterface((IUnknown*)This, iid, ppv);
1043     IUnknown_Release((IUnknown*)This);
1044
1045     return ret;
1046 }