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