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