windowscodecs: Standardize the COM usage in tgaformat.c.
[wine] / dlls / windowscodecs / tgaformat.c
1 /*
2  * Copyright 2010 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 #include "wine/port.h"
21
22 #include <stdarg.h>
23
24 #define COBJMACROS
25
26 #include "windef.h"
27 #include "winbase.h"
28 #include "objbase.h"
29 #include "wincodec.h"
30
31 #include "wincodecs_private.h"
32
33 #include "wine/debug.h"
34 #include "wine/library.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(wincodecs);
37
38 #include "pshpack1.h"
39
40 typedef struct {
41     BYTE id_length;
42     BYTE colormap_type;
43     BYTE image_type;
44     /* Colormap Specification */
45     WORD colormap_firstentry;
46     WORD colormap_length;
47     BYTE colormap_entrysize;
48     /* Image Specification */
49     WORD xorigin;
50     WORD yorigin;
51     WORD width;
52     WORD height;
53     BYTE depth;
54     BYTE image_descriptor;
55 } tga_header;
56
57 #define IMAGETYPE_COLORMAPPED 1
58 #define IMAGETYPE_TRUECOLOR 2
59 #define IMAGETYPE_GRAYSCALE 3
60 #define IMAGETYPE_RLE 8
61
62 #define IMAGE_ATTRIBUTE_BITCOUNT_MASK 0xf
63 #define IMAGE_RIGHTTOLEFT 0x10
64 #define IMAGE_TOPTOBOTTOM 0x20
65
66 typedef struct {
67     DWORD extension_area_offset;
68     DWORD developer_directory_offset;
69     char magic[18];
70 } tga_footer;
71
72 static const BYTE tga_footer_magic[18] = "TRUEVISION-XFILE.";
73
74 typedef struct {
75     WORD size;
76     char author_name[41];
77     char author_comments[324];
78     WORD timestamp[6];
79     char job_name[41];
80     WORD job_timestamp[6];
81     char software_id[41];
82     WORD software_version;
83     char software_version_letter;
84     DWORD key_color;
85     WORD pixel_width;
86     WORD pixel_height;
87     WORD gamma_numerator;
88     WORD gamma_denominator;
89     DWORD color_correction_offset;
90     DWORD thumbnail_offset;
91     DWORD scanline_offset;
92     BYTE attributes_type;
93 } tga_extension_area;
94
95 #define ATTRIBUTE_NO_ALPHA 0
96 #define ATTRIBUTE_UNDEFINED 1
97 #define ATTRIBUTE_UNDEFINED_PRESERVE 2
98 #define ATTRIBUTE_ALPHA 3
99 #define ATTRIBUTE_PALPHA 4
100
101 #include "poppack.h"
102
103 typedef struct {
104     IWICBitmapDecoder IWICBitmapDecoder_iface;
105     IWICBitmapFrameDecode IWICBitmapFrameDecode_iface;
106     LONG ref;
107     BOOL initialized;
108     IStream *stream;
109     tga_header header;
110     tga_extension_area extension_area;
111     BYTE *imagebits;
112     BYTE *origin;
113     int stride;
114     ULONG id_offset;
115     ULONG colormap_length;
116     ULONG colormap_offset;
117     ULONG image_offset;
118     ULONG extension_area_offset;
119     ULONG developer_directory_offset;
120     CRITICAL_SECTION lock;
121 } TgaDecoder;
122
123 static inline TgaDecoder *impl_from_IWICBitmapDecoder(IWICBitmapDecoder *iface)
124 {
125     return CONTAINING_RECORD(iface, TgaDecoder, IWICBitmapDecoder_iface);
126 }
127
128 static inline TgaDecoder *impl_from_IWICBitmapFrameDecode(IWICBitmapFrameDecode *iface)
129 {
130     return CONTAINING_RECORD(iface, TgaDecoder, IWICBitmapFrameDecode_iface);
131 }
132
133 static HRESULT WINAPI TgaDecoder_QueryInterface(IWICBitmapDecoder *iface, REFIID iid,
134     void **ppv)
135 {
136     TgaDecoder *This = impl_from_IWICBitmapDecoder(iface);
137     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
138
139     if (!ppv) return E_INVALIDARG;
140
141     if (IsEqualIID(&IID_IUnknown, iid) || IsEqualIID(&IID_IWICBitmapDecoder, iid))
142     {
143         *ppv = This;
144     }
145     else
146     {
147         *ppv = NULL;
148         return E_NOINTERFACE;
149     }
150
151     IUnknown_AddRef((IUnknown*)*ppv);
152     return S_OK;
153 }
154
155 static ULONG WINAPI TgaDecoder_AddRef(IWICBitmapDecoder *iface)
156 {
157     TgaDecoder *This = impl_from_IWICBitmapDecoder(iface);
158     ULONG ref = InterlockedIncrement(&This->ref);
159
160     TRACE("(%p) refcount=%u\n", iface, ref);
161
162     return ref;
163 }
164
165 static ULONG WINAPI TgaDecoder_Release(IWICBitmapDecoder *iface)
166 {
167     TgaDecoder *This = impl_from_IWICBitmapDecoder(iface);
168     ULONG ref = InterlockedDecrement(&This->ref);
169
170     TRACE("(%p) refcount=%u\n", iface, ref);
171
172     if (ref == 0)
173     {
174         This->lock.DebugInfo->Spare[0] = 0;
175         DeleteCriticalSection(&This->lock);
176         if (This->stream)
177             IStream_Release(This->stream);
178         HeapFree(GetProcessHeap(), 0, This->imagebits);
179         HeapFree(GetProcessHeap(), 0, This);
180     }
181
182     return ref;
183 }
184
185 static HRESULT WINAPI TgaDecoder_QueryCapability(IWICBitmapDecoder *iface, IStream *pIStream,
186     DWORD *pdwCapability)
187 {
188     FIXME("(%p,%p,%p): stub\n", iface, pIStream, pdwCapability);
189     return E_NOTIMPL;
190 }
191
192 static HRESULT WINAPI TgaDecoder_Initialize(IWICBitmapDecoder *iface, IStream *pIStream,
193     WICDecodeOptions cacheOptions)
194 {
195     TgaDecoder *This = impl_from_IWICBitmapDecoder(iface);
196     HRESULT hr=S_OK;
197     DWORD bytesread;
198     LARGE_INTEGER seek;
199     tga_footer footer;
200     int attribute_bitcount;
201     int mapped_depth=0;
202
203     TRACE("(%p,%p,%u)\n", iface, pIStream, cacheOptions);
204
205     EnterCriticalSection(&This->lock);
206
207     if (This->initialized)
208     {
209         hr = WINCODEC_ERR_WRONGSTATE;
210         goto end;
211     }
212
213     seek.QuadPart = 0;
214     hr = IStream_Seek(pIStream, seek, STREAM_SEEK_SET, NULL);
215     if (FAILED(hr)) goto end;
216
217     hr = IStream_Read(pIStream, &This->header, sizeof(tga_header), &bytesread);
218     if (SUCCEEDED(hr) && bytesread != sizeof(tga_header))
219     {
220         TRACE("got only %u bytes\n", bytesread);
221         hr = E_FAIL;
222     }
223     if (FAILED(hr)) goto end;
224
225     TRACE("imagetype=%u, colormap type=%u, depth=%u, image descriptor=0x%x\n",
226         This->header.image_type, This->header.colormap_type,
227         This->header.depth, This->header.image_descriptor);
228
229     /* Sanity checking. Since TGA has no clear identifying markers, we need
230      * to be careful to not load a non-TGA image. */
231     switch (This->header.image_type)
232     {
233     case IMAGETYPE_COLORMAPPED:
234     case IMAGETYPE_COLORMAPPED|IMAGETYPE_RLE:
235         if (This->header.colormap_type != 1)
236             hr = E_FAIL;
237         mapped_depth = This->header.colormap_entrysize;
238         break;
239     case IMAGETYPE_TRUECOLOR:
240     case IMAGETYPE_TRUECOLOR|IMAGETYPE_RLE:
241         if (This->header.colormap_type != 0 && This->header.colormap_type != 1)
242             hr = E_FAIL;
243         mapped_depth = This->header.depth;
244         break;
245     case IMAGETYPE_GRAYSCALE:
246     case IMAGETYPE_GRAYSCALE|IMAGETYPE_RLE:
247         if (This->header.colormap_type != 0)
248             hr = E_FAIL;
249         mapped_depth = 0;
250         break;
251     default:
252         hr = E_FAIL;
253     }
254
255     if (This->header.depth != 8 && This->header.depth != 16 &&
256         This->header.depth != 24 && This->header.depth != 32)
257         hr = E_FAIL;
258
259     if ((This->header.image_descriptor & 0xc0) != 0)
260         hr = E_FAIL;
261
262     attribute_bitcount = This->header.image_descriptor & IMAGE_ATTRIBUTE_BITCOUNT_MASK;
263
264     if (attribute_bitcount &&
265         !((mapped_depth == 32 && attribute_bitcount == 8) ||
266           (mapped_depth == 16 && attribute_bitcount == 1)))
267         hr = E_FAIL;
268
269     if (FAILED(hr))
270     {
271         WARN("bad tga header\n");
272         goto end;
273     }
274
275     /* Locate data in the file based on the header. */
276     This->id_offset = sizeof(tga_header);
277     This->colormap_offset = This->id_offset + This->header.id_length;
278     if (This->header.colormap_type == 1)
279         This->colormap_length = ((This->header.colormap_entrysize+7)/8) * This->header.colormap_length;
280     else
281         This->colormap_length = 0;
282     This->image_offset = This->colormap_offset + This->colormap_length;
283
284     /* Read footer if there is one */
285     seek.QuadPart = -sizeof(tga_footer);
286     hr = IStream_Seek(pIStream, seek, STREAM_SEEK_END, NULL);
287     if (FAILED(hr)) goto end;
288
289     hr = IStream_Read(pIStream, &footer, sizeof(tga_footer), &bytesread);
290     if (SUCCEEDED(hr) && bytesread != sizeof(tga_footer))
291     {
292         TRACE("got only %u footer bytes\n", bytesread);
293         hr = E_FAIL;
294     }
295     if (FAILED(hr)) goto end;
296
297     if (memcmp(footer.magic, tga_footer_magic, sizeof(tga_footer_magic)) == 0)
298     {
299         This->extension_area_offset = footer.extension_area_offset;
300         This->developer_directory_offset = footer.developer_directory_offset;
301     }
302     else
303     {
304         This->extension_area_offset = 0;
305         This->developer_directory_offset = 0;
306     }
307
308     if (This->extension_area_offset)
309     {
310         seek.QuadPart = This->extension_area_offset;
311         hr = IStream_Seek(pIStream, seek, STREAM_SEEK_SET, NULL);
312         if (FAILED(hr)) goto end;
313
314         hr = IStream_Read(pIStream, &This->extension_area, sizeof(tga_extension_area), &bytesread);
315         if (SUCCEEDED(hr) && bytesread != sizeof(tga_extension_area))
316         {
317             TRACE("got only %u extension area bytes\n", bytesread);
318             hr = E_FAIL;
319         }
320         if (SUCCEEDED(hr) && This->extension_area.size < 495)
321         {
322             TRACE("extension area is only %u bytes long\n", This->extension_area.size);
323             hr = E_FAIL;
324         }
325         if (FAILED(hr)) goto end;
326     }
327
328     IStream_AddRef(pIStream);
329     This->stream = pIStream;
330     This->initialized = TRUE;
331
332 end:
333     LeaveCriticalSection(&This->lock);
334     return hr;
335 }
336
337 static HRESULT WINAPI TgaDecoder_GetContainerFormat(IWICBitmapDecoder *iface,
338     GUID *pguidContainerFormat)
339 {
340     memcpy(pguidContainerFormat, &GUID_WineContainerFormatTga, sizeof(GUID));
341     return S_OK;
342 }
343
344 static HRESULT WINAPI TgaDecoder_GetDecoderInfo(IWICBitmapDecoder *iface,
345     IWICBitmapDecoderInfo **ppIDecoderInfo)
346 {
347     FIXME("(%p,%p): stub\n", iface, ppIDecoderInfo);
348     return E_NOTIMPL;
349 }
350
351 static HRESULT WINAPI TgaDecoder_CopyPalette(IWICBitmapDecoder *iface,
352     IWICPalette *pIPalette)
353 {
354     FIXME("(%p,%p): stub\n", iface, pIPalette);
355     return E_NOTIMPL;
356 }
357
358 static HRESULT WINAPI TgaDecoder_GetMetadataQueryReader(IWICBitmapDecoder *iface,
359     IWICMetadataQueryReader **ppIMetadataQueryReader)
360 {
361     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
362     return E_NOTIMPL;
363 }
364
365 static HRESULT WINAPI TgaDecoder_GetPreview(IWICBitmapDecoder *iface,
366     IWICBitmapSource **ppIBitmapSource)
367 {
368     FIXME("(%p,%p): stub\n", iface, ppIBitmapSource);
369     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
370 }
371
372 static HRESULT WINAPI TgaDecoder_GetColorContexts(IWICBitmapDecoder *iface,
373     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
374 {
375     FIXME("(%p,%u,%p,%p): stub\n", iface, cCount, ppIColorContexts, pcActualCount);
376     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
377 }
378
379 static HRESULT WINAPI TgaDecoder_GetThumbnail(IWICBitmapDecoder *iface,
380     IWICBitmapSource **ppIThumbnail)
381 {
382     FIXME("(%p,%p): stub\n", iface, ppIThumbnail);
383     return WINCODEC_ERR_CODECNOTHUMBNAIL;
384 }
385
386 static HRESULT WINAPI TgaDecoder_GetFrameCount(IWICBitmapDecoder *iface,
387     UINT *pCount)
388 {
389     *pCount = 1;
390     return S_OK;
391 }
392
393 static HRESULT WINAPI TgaDecoder_GetFrame(IWICBitmapDecoder *iface,
394     UINT index, IWICBitmapFrameDecode **ppIBitmapFrame)
395 {
396     TgaDecoder *This = impl_from_IWICBitmapDecoder(iface);
397     TRACE("(%p,%p)\n", iface, ppIBitmapFrame);
398
399     if (!This->initialized) return WINCODEC_ERR_NOTINITIALIZED;
400
401     if (index != 0) return E_INVALIDARG;
402
403     IWICBitmapDecoder_AddRef(iface);
404     *ppIBitmapFrame = &This->IWICBitmapFrameDecode_iface;
405
406     return S_OK;
407 }
408
409 static const IWICBitmapDecoderVtbl TgaDecoder_Vtbl = {
410     TgaDecoder_QueryInterface,
411     TgaDecoder_AddRef,
412     TgaDecoder_Release,
413     TgaDecoder_QueryCapability,
414     TgaDecoder_Initialize,
415     TgaDecoder_GetContainerFormat,
416     TgaDecoder_GetDecoderInfo,
417     TgaDecoder_CopyPalette,
418     TgaDecoder_GetMetadataQueryReader,
419     TgaDecoder_GetPreview,
420     TgaDecoder_GetColorContexts,
421     TgaDecoder_GetThumbnail,
422     TgaDecoder_GetFrameCount,
423     TgaDecoder_GetFrame
424 };
425
426 static HRESULT WINAPI TgaDecoder_Frame_QueryInterface(IWICBitmapFrameDecode *iface, REFIID iid,
427     void **ppv)
428 {
429     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
430
431     if (!ppv) return E_INVALIDARG;
432
433     if (IsEqualIID(&IID_IUnknown, iid) ||
434         IsEqualIID(&IID_IWICBitmapSource, iid) ||
435         IsEqualIID(&IID_IWICBitmapFrameDecode, iid))
436     {
437         *ppv = iface;
438     }
439     else
440     {
441         *ppv = NULL;
442         return E_NOINTERFACE;
443     }
444
445     IUnknown_AddRef((IUnknown*)*ppv);
446     return S_OK;
447 }
448
449 static ULONG WINAPI TgaDecoder_Frame_AddRef(IWICBitmapFrameDecode *iface)
450 {
451     TgaDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
452     return IUnknown_AddRef((IUnknown*)This);
453 }
454
455 static ULONG WINAPI TgaDecoder_Frame_Release(IWICBitmapFrameDecode *iface)
456 {
457     TgaDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
458     return IUnknown_Release((IUnknown*)This);
459 }
460
461 static HRESULT WINAPI TgaDecoder_Frame_GetSize(IWICBitmapFrameDecode *iface,
462     UINT *puiWidth, UINT *puiHeight)
463 {
464     TgaDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
465
466     *puiWidth = This->header.width;
467     *puiHeight = This->header.height;
468
469     TRACE("(%p)->(%u,%u)\n", iface, *puiWidth, *puiHeight);
470
471     return S_OK;
472 }
473
474 static HRESULT WINAPI TgaDecoder_Frame_GetPixelFormat(IWICBitmapFrameDecode *iface,
475     WICPixelFormatGUID *pPixelFormat)
476 {
477     TgaDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
478     int attribute_bitcount;
479     byte attribute_type;
480
481     TRACE("(%p,%p)\n", iface, pPixelFormat);
482
483     attribute_bitcount = This->header.image_descriptor & IMAGE_ATTRIBUTE_BITCOUNT_MASK;
484
485     if (attribute_bitcount && This->extension_area_offset)
486         attribute_type = This->extension_area.attributes_type;
487     else if (attribute_bitcount)
488         attribute_type = ATTRIBUTE_ALPHA;
489     else
490         attribute_type = ATTRIBUTE_NO_ALPHA;
491
492     switch (This->header.image_type & ~IMAGETYPE_RLE)
493     {
494     case IMAGETYPE_COLORMAPPED:
495         switch (This->header.depth)
496         {
497         case 8:
498             memcpy(pPixelFormat, &GUID_WICPixelFormat8bppIndexed, sizeof(GUID));
499             break;
500         default:
501             FIXME("Unhandled indexed color depth %u\n", This->header.depth);
502             return E_NOTIMPL;
503         }
504         break;
505     case IMAGETYPE_TRUECOLOR:
506         switch (This->header.depth)
507         {
508         case 16:
509             switch (attribute_type)
510             {
511             case ATTRIBUTE_NO_ALPHA:
512             case ATTRIBUTE_UNDEFINED:
513             case ATTRIBUTE_UNDEFINED_PRESERVE:
514                 memcpy(pPixelFormat, &GUID_WICPixelFormat16bppBGR555, sizeof(GUID));
515                 break;
516             case ATTRIBUTE_ALPHA:
517             case ATTRIBUTE_PALPHA:
518                 memcpy(pPixelFormat, &GUID_WICPixelFormat16bppBGRA5551, sizeof(GUID));
519                 break;
520             default:
521                 FIXME("Unhandled 16-bit attribute type %u\n", attribute_type);
522                 return E_NOTIMPL;
523             }
524             break;
525         case 24:
526             memcpy(pPixelFormat, &GUID_WICPixelFormat24bppBGR, sizeof(GUID));
527             break;
528         case 32:
529             switch (attribute_type)
530             {
531             case ATTRIBUTE_NO_ALPHA:
532             case ATTRIBUTE_UNDEFINED:
533             case ATTRIBUTE_UNDEFINED_PRESERVE:
534                 memcpy(pPixelFormat, &GUID_WICPixelFormat32bppBGR, sizeof(GUID));
535                 break;
536             case ATTRIBUTE_ALPHA:
537                 memcpy(pPixelFormat, &GUID_WICPixelFormat32bppBGRA, sizeof(GUID));
538                 break;
539             case ATTRIBUTE_PALPHA:
540                 memcpy(pPixelFormat, &GUID_WICPixelFormat32bppPBGRA, sizeof(GUID));
541                 break;
542             default:
543                 FIXME("Unhandled 32-bit attribute type %u\n", attribute_type);
544                 return E_NOTIMPL;
545             }
546             break;
547         default:
548             FIXME("Unhandled truecolor depth %u\n", This->header.depth);
549             return E_NOTIMPL;
550         }
551         break;
552     case IMAGETYPE_GRAYSCALE:
553         switch (This->header.depth)
554         {
555         case 8:
556             memcpy(pPixelFormat, &GUID_WICPixelFormat8bppGray, sizeof(GUID));
557             break;
558         case 16:
559             memcpy(pPixelFormat, &GUID_WICPixelFormat16bppGray, sizeof(GUID));
560             break;
561         default:
562             FIXME("Unhandled grayscale depth %u\n", This->header.depth);
563             return E_NOTIMPL;
564         }
565         break;
566     default:
567         ERR("Unknown image type %u\n", This->header.image_type);
568         return E_FAIL;
569     }
570
571     return S_OK;
572 }
573
574 static HRESULT WINAPI TgaDecoder_Frame_GetResolution(IWICBitmapFrameDecode *iface,
575     double *pDpiX, double *pDpiY)
576 {
577     FIXME("(%p,%p,%p): stub\n", iface, pDpiX, pDpiY);
578     return E_NOTIMPL;
579 }
580
581 static HRESULT WINAPI TgaDecoder_Frame_CopyPalette(IWICBitmapFrameDecode *iface,
582     IWICPalette *pIPalette)
583 {
584     TgaDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
585     HRESULT hr=S_OK;
586     WICColor colors[256], *color;
587     BYTE *colormap_data;
588     WORD *wcolormap_data;
589     DWORD *dwcolormap_data;
590     LARGE_INTEGER seek;
591     ULONG bytesread;
592     int depth, attribute_bitcount, attribute_type;
593     int i;
594
595     TRACE("(%p,%p)\n", iface, pIPalette);
596
597     if (!This->colormap_length)
598     {
599         WARN("no colormap present in this file\n");
600         return WINCODEC_ERR_PALETTEUNAVAILABLE;
601     }
602
603     if (This->header.colormap_firstentry + This->header.colormap_length > 256)
604     {
605         FIXME("cannot read colormap with %i entries starting at %i\n",
606             This->header.colormap_firstentry + This->header.colormap_length,
607             This->header.colormap_firstentry);
608         return E_FAIL;
609     }
610
611     colormap_data = HeapAlloc(GetProcessHeap(), 0, This->colormap_length);
612     if (!colormap_data) return E_OUTOFMEMORY;
613
614     wcolormap_data = (WORD*)colormap_data;
615     dwcolormap_data = (DWORD*)colormap_data;
616
617     EnterCriticalSection(&This->lock);
618
619     seek.QuadPart = This->colormap_offset;
620     hr = IStream_Seek(This->stream, seek, STREAM_SEEK_SET, NULL);
621
622     if (SUCCEEDED(hr))
623     {
624         hr = IStream_Read(This->stream, colormap_data, This->colormap_length, &bytesread);
625         if (SUCCEEDED(hr) && bytesread != This->colormap_length)
626         {
627             WARN("expected %i bytes in colormap, got %i\n", This->colormap_length, bytesread);
628             hr = E_FAIL;
629         }
630     }
631
632     LeaveCriticalSection(&This->lock);
633
634     if (SUCCEEDED(hr))
635     {
636         attribute_bitcount = This->header.image_descriptor & IMAGE_ATTRIBUTE_BITCOUNT_MASK;
637
638         if (attribute_bitcount && This->extension_area_offset)
639             attribute_type = This->extension_area.attributes_type;
640         else if (attribute_bitcount)
641             attribute_type = ATTRIBUTE_ALPHA;
642         else
643             attribute_type = ATTRIBUTE_NO_ALPHA;
644
645         depth = This->header.colormap_entrysize;
646         if (depth == 15)
647         {
648             depth = 16;
649             attribute_type = ATTRIBUTE_NO_ALPHA;
650         }
651
652         memset(colors, 0, sizeof(colors));
653
654         color = &colors[This->header.colormap_firstentry];
655
656         /* Colormap entries can be in any truecolor format, and we have to convert them. */
657         switch (depth)
658         {
659         case 16:
660             switch (attribute_type)
661             {
662             case ATTRIBUTE_NO_ALPHA:
663             case ATTRIBUTE_UNDEFINED:
664             case ATTRIBUTE_UNDEFINED_PRESERVE:
665                 for (i=0; i<This->header.colormap_length; i++)
666                 {
667                     WORD srcval = wcolormap_data[i];
668                     *color++=0xff000000 | /* constant 255 alpha */
669                              ((srcval << 9) & 0xf80000) | /* r */
670                              ((srcval << 4) & 0x070000) | /* r - 3 bits */
671                              ((srcval << 6) & 0x00f800) | /* g */
672                              ((srcval << 1) & 0x000700) | /* g - 3 bits */
673                              ((srcval << 3) & 0x0000f8) | /* b */
674                              ((srcval >> 2) & 0x000007);  /* b - 3 bits */
675                 }
676                 break;
677             case ATTRIBUTE_ALPHA:
678             case ATTRIBUTE_PALPHA:
679                 for (i=0; i<This->header.colormap_length; i++)
680                 {
681                     WORD srcval = wcolormap_data[i];
682                     *color++=((srcval & 0x8000) ? 0xff000000 : 0) | /* alpha */
683                              ((srcval << 9) & 0xf80000) | /* r */
684                              ((srcval << 4) & 0x070000) | /* r - 3 bits */
685                              ((srcval << 6) & 0x00f800) | /* g */
686                              ((srcval << 1) & 0x000700) | /* g - 3 bits */
687                              ((srcval << 3) & 0x0000f8) | /* b */
688                              ((srcval >> 2) & 0x000007);  /* b - 3 bits */
689                 }
690                 break;
691             default:
692                 FIXME("Unhandled 16-bit attribute type %u\n", attribute_type);
693                 hr = E_NOTIMPL;
694             }
695             break;
696         case 24:
697             for (i=0; i<This->header.colormap_length; i++)
698             {
699                 *color++=0xff000000 | /* alpha */
700                          colormap_data[i*3+2] | /* red */
701                          colormap_data[i*3+1] | /* green */
702                          colormap_data[i*3]; /* blue */
703             }
704             break;
705         case 32:
706             switch (attribute_type)
707             {
708             case ATTRIBUTE_NO_ALPHA:
709             case ATTRIBUTE_UNDEFINED:
710             case ATTRIBUTE_UNDEFINED_PRESERVE:
711                 for (i=0; i<This->header.colormap_length; i++)
712                     *color++=dwcolormap_data[i]|0xff000000;
713                 break;
714             case ATTRIBUTE_ALPHA:
715                 for (i=0; i<This->header.colormap_length; i++)
716                     *color++=dwcolormap_data[i];
717                 break;
718             case ATTRIBUTE_PALPHA:
719                 /* FIXME: Unpremultiply alpha */
720             default:
721                 FIXME("Unhandled 16-bit attribute type %u\n", attribute_type);
722                 hr = E_NOTIMPL;
723             }
724             break;
725         default:
726             FIXME("Unhandled truecolor depth %u\n", This->header.depth);
727             hr = E_NOTIMPL;
728         }
729     }
730
731     HeapFree(GetProcessHeap(), 0, colormap_data);
732
733     if (SUCCEEDED(hr))
734         hr = IWICPalette_InitializeCustom(pIPalette, colors, 256);
735
736     return hr;
737 }
738
739 static HRESULT TgaDecoder_ReadRLE(TgaDecoder *This, BYTE *imagebits, int datasize)
740 {
741     int i=0, j, bytesperpixel;
742     ULONG bytesread;
743     HRESULT hr=S_OK;
744
745     bytesperpixel = This->header.depth / 8;
746
747     while (i<datasize)
748     {
749         BYTE rc;
750         int count, size;
751         BYTE pixeldata[4];
752
753         hr = IStream_Read(This->stream, &rc, 1, &bytesread);
754         if (bytesread != 1) hr = E_FAIL;
755         if (FAILED(hr)) break;
756
757         count = (rc&0x7f)+1;
758         size = count * bytesperpixel;
759
760         if (size + i > datasize)
761         {
762             WARN("RLE packet too large\n");
763             hr = E_FAIL;
764             break;
765         }
766
767         if (rc&0x80)
768         {
769             /* Run-length packet */
770             hr = IStream_Read(This->stream, pixeldata, bytesperpixel, &bytesread);
771             if (bytesread != bytesperpixel) hr = E_FAIL;
772             if (FAILED(hr)) break;
773
774             if (bytesperpixel == 1)
775                 memset(&imagebits[i], pixeldata[0], count);
776             else
777             {
778                 for (j=0; j<count; j++)
779                     memcpy(&imagebits[i+j*bytesperpixel], pixeldata, bytesperpixel);
780             }
781         }
782         else
783         {
784             /* Raw packet */
785             hr = IStream_Read(This->stream, &imagebits[i], size, &bytesread);
786             if (bytesread != size) hr = E_FAIL;
787             if (FAILED(hr)) break;
788         }
789
790         i += size;
791     }
792
793     return hr;
794 }
795
796 static HRESULT TgaDecoder_ReadImage(TgaDecoder *This)
797 {
798     HRESULT hr=S_OK;
799     int datasize;
800     LARGE_INTEGER seek;
801     ULONG bytesread;
802
803     if (This->imagebits)
804         return S_OK;
805
806     EnterCriticalSection(&This->lock);
807
808     if (!This->imagebits)
809     {
810         if (This->header.image_descriptor & IMAGE_RIGHTTOLEFT)
811         {
812             FIXME("Right to left image reading not implemented\n");
813             hr = E_NOTIMPL;
814         }
815
816         if (SUCCEEDED(hr))
817         {
818             datasize = This->header.width * This->header.height * (This->header.depth / 8);
819             This->imagebits = HeapAlloc(GetProcessHeap(), 0, datasize);
820             if (!This->imagebits) hr = E_OUTOFMEMORY;
821         }
822
823         if (SUCCEEDED(hr))
824         {
825             seek.QuadPart = This->image_offset;
826             hr = IStream_Seek(This->stream, seek, STREAM_SEEK_SET, NULL);
827         }
828
829         if (SUCCEEDED(hr))
830         {
831             if (This->header.image_type & IMAGETYPE_RLE)
832             {
833                 hr = TgaDecoder_ReadRLE(This, This->imagebits, datasize);
834             }
835             else
836             {
837                 hr = IStream_Read(This->stream, This->imagebits, datasize, &bytesread);
838                 if (SUCCEEDED(hr) && bytesread != datasize)
839                     hr = E_FAIL;
840             }
841         }
842
843         if (SUCCEEDED(hr))
844         {
845             if (This->header.image_descriptor & IMAGE_TOPTOBOTTOM)
846             {
847                 This->origin = This->imagebits;
848                 This->stride = This->header.width * (This->header.depth / 8);
849             }
850             else
851             {
852                 This->stride = -This->header.width * (This->header.depth / 8);
853                 This->origin = This->imagebits + This->header.width * (This->header.height - 1) * (This->header.depth / 8);
854             }
855         }
856         else
857         {
858             HeapFree(GetProcessHeap(), 0, This->imagebits);
859             This->imagebits = NULL;
860         }
861     }
862
863     LeaveCriticalSection(&This->lock);
864
865     return hr;
866 }
867
868 static HRESULT WINAPI TgaDecoder_Frame_CopyPixels(IWICBitmapFrameDecode *iface,
869     const WICRect *prc, UINT cbStride, UINT cbBufferSize, BYTE *pbBuffer)
870 {
871     TgaDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
872     HRESULT hr;
873
874     TRACE("(%p,%p,%u,%u,%p)\n", iface, prc, cbStride, cbBufferSize, pbBuffer);
875
876     hr = TgaDecoder_ReadImage(This);
877
878     if (SUCCEEDED(hr))
879     {
880         hr = copy_pixels(This->header.depth, This->origin,
881             This->header.width, This->header.height, This->stride,
882             prc, cbStride, cbBufferSize, pbBuffer);
883     }
884
885     return hr;
886 }
887
888 static HRESULT WINAPI TgaDecoder_Frame_GetMetadataQueryReader(IWICBitmapFrameDecode *iface,
889     IWICMetadataQueryReader **ppIMetadataQueryReader)
890 {
891     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
892     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
893 }
894
895 static HRESULT WINAPI TgaDecoder_Frame_GetColorContexts(IWICBitmapFrameDecode *iface,
896     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
897 {
898     FIXME("(%p,%u,%p,%p): stub\n", iface, cCount, ppIColorContexts, pcActualCount);
899     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
900 }
901
902 static HRESULT WINAPI TgaDecoder_Frame_GetThumbnail(IWICBitmapFrameDecode *iface,
903     IWICBitmapSource **ppIThumbnail)
904 {
905     FIXME("(%p,%p): stub\n", iface, ppIThumbnail);
906     return WINCODEC_ERR_CODECNOTHUMBNAIL;
907 }
908
909 static const IWICBitmapFrameDecodeVtbl TgaDecoder_Frame_Vtbl = {
910     TgaDecoder_Frame_QueryInterface,
911     TgaDecoder_Frame_AddRef,
912     TgaDecoder_Frame_Release,
913     TgaDecoder_Frame_GetSize,
914     TgaDecoder_Frame_GetPixelFormat,
915     TgaDecoder_Frame_GetResolution,
916     TgaDecoder_Frame_CopyPalette,
917     TgaDecoder_Frame_CopyPixels,
918     TgaDecoder_Frame_GetMetadataQueryReader,
919     TgaDecoder_Frame_GetColorContexts,
920     TgaDecoder_Frame_GetThumbnail
921 };
922
923 HRESULT TgaDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
924 {
925     TgaDecoder *This;
926     HRESULT ret;
927
928     TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);
929
930     *ppv = NULL;
931
932     if (pUnkOuter) return CLASS_E_NOAGGREGATION;
933
934     This = HeapAlloc(GetProcessHeap(), 0, sizeof(TgaDecoder));
935     if (!This) return E_OUTOFMEMORY;
936
937     This->IWICBitmapDecoder_iface.lpVtbl = &TgaDecoder_Vtbl;
938     This->IWICBitmapFrameDecode_iface.lpVtbl = &TgaDecoder_Frame_Vtbl;
939     This->ref = 1;
940     This->initialized = FALSE;
941     This->stream = NULL;
942     This->imagebits = NULL;
943     InitializeCriticalSection(&This->lock);
944     This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": TgaDecoder.lock");
945
946     ret = IUnknown_QueryInterface((IUnknown*)This, iid, ppv);
947     IUnknown_Release((IUnknown*)This);
948
949     return ret;
950 }