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