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