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