wined3d: Use the texture dimension helpers in surface_depth_blt().
[wine.git] / dlls / windowscodecs / pngformat.c
blob3eb4d0ecbdd3ea50a2f7f98e94a71b0c5fc2e208
1 /*
2 * Copyright 2009 Vincent Povirk for CodeWeavers
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.
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.
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
19 #include "config.h"
20 #include "wine/port.h"
22 #include <stdarg.h>
24 #ifdef HAVE_PNG_H
25 #include <png.h>
26 #endif
28 #define NONAMELESSUNION
29 #define COBJMACROS
31 #include "windef.h"
32 #include "winbase.h"
33 #include "objbase.h"
35 #include "wincodecs_private.h"
37 #include "wine/debug.h"
38 #include "wine/library.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(wincodecs);
42 static const WCHAR wszPngInterlaceOption[] = {'I','n','t','e','r','l','a','c','e','O','p','t','i','o','n',0};
44 static inline ULONG read_ulong_be(BYTE* data)
46 return data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3];
49 static HRESULT read_png_chunk(IStream *stream, BYTE *type, BYTE **data, ULONG *data_size)
51 BYTE header[8];
52 HRESULT hr;
53 ULONG bytesread;
55 hr = IStream_Read(stream, header, 8, &bytesread);
56 if (FAILED(hr) || bytesread < 8)
58 if (SUCCEEDED(hr))
59 hr = E_FAIL;
60 return hr;
63 *data_size = read_ulong_be(&header[0]);
65 memcpy(type, &header[4], 4);
67 if (data)
69 *data = HeapAlloc(GetProcessHeap(), 0, *data_size);
70 if (!*data)
71 return E_OUTOFMEMORY;
73 hr = IStream_Read(stream, *data, *data_size, &bytesread);
75 if (FAILED(hr) || bytesread < *data_size)
77 if (SUCCEEDED(hr))
78 hr = E_FAIL;
79 HeapFree(GetProcessHeap(), 0, *data);
80 *data = NULL;
81 return hr;
84 /* Windows ignores CRC of the chunk */
87 return S_OK;
90 static HRESULT LoadTextMetadata(IStream *stream, const GUID *preferred_vendor,
91 DWORD persist_options, MetadataItem **items, DWORD *item_count)
93 HRESULT hr;
94 BYTE type[4];
95 BYTE *data;
96 ULONG data_size;
97 ULONG name_len, value_len;
98 BYTE *name_end_ptr;
99 LPSTR name, value;
100 MetadataItem *result;
102 hr = read_png_chunk(stream, type, &data, &data_size);
103 if (FAILED(hr)) return hr;
105 name_end_ptr = memchr(data, 0, data_size);
107 name_len = name_end_ptr - data;
109 if (!name_end_ptr || name_len > 79)
111 HeapFree(GetProcessHeap(), 0, data);
112 return E_FAIL;
115 value_len = data_size - name_len - 1;
117 result = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MetadataItem));
118 name = HeapAlloc(GetProcessHeap(), 0, name_len + 1);
119 value = HeapAlloc(GetProcessHeap(), 0, value_len + 1);
120 if (!result || !name || !value)
122 HeapFree(GetProcessHeap(), 0, data);
123 HeapFree(GetProcessHeap(), 0, result);
124 HeapFree(GetProcessHeap(), 0, name);
125 HeapFree(GetProcessHeap(), 0, value);
126 return E_OUTOFMEMORY;
129 PropVariantInit(&result[0].schema);
130 PropVariantInit(&result[0].id);
131 PropVariantInit(&result[0].value);
133 memcpy(name, data, name_len + 1);
134 memcpy(value, name_end_ptr + 1, value_len);
135 value[value_len] = 0;
137 result[0].id.vt = VT_LPSTR;
138 result[0].id.u.pszVal = name;
139 result[0].value.vt = VT_LPSTR;
140 result[0].value.u.pszVal = value;
142 *items = result;
143 *item_count = 1;
145 HeapFree(GetProcessHeap(), 0, data);
147 return S_OK;
150 static const MetadataHandlerVtbl TextReader_Vtbl = {
152 &CLSID_WICPngTextMetadataReader,
153 LoadTextMetadata
156 HRESULT PngTextReader_CreateInstance(REFIID iid, void** ppv)
158 return MetadataReader_Create(&TextReader_Vtbl, iid, ppv);
161 static HRESULT LoadGamaMetadata(IStream *stream, const GUID *preferred_vendor,
162 DWORD persist_options, MetadataItem **items, DWORD *item_count)
164 HRESULT hr;
165 BYTE type[4];
166 BYTE *data;
167 ULONG data_size;
168 ULONG gamma;
169 static const WCHAR ImageGamma[] = {'I','m','a','g','e','G','a','m','m','a',0};
170 LPWSTR name;
171 MetadataItem *result;
173 hr = read_png_chunk(stream, type, &data, &data_size);
174 if (FAILED(hr)) return hr;
176 if (data_size < 4)
178 HeapFree(GetProcessHeap(), 0, data);
179 return E_FAIL;
182 gamma = read_ulong_be(data);
184 HeapFree(GetProcessHeap(), 0, data);
186 result = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MetadataItem));
187 name = HeapAlloc(GetProcessHeap(), 0, sizeof(ImageGamma));
188 if (!result || !name)
190 HeapFree(GetProcessHeap(), 0, result);
191 HeapFree(GetProcessHeap(), 0, name);
192 return E_OUTOFMEMORY;
195 PropVariantInit(&result[0].schema);
196 PropVariantInit(&result[0].id);
197 PropVariantInit(&result[0].value);
199 memcpy(name, ImageGamma, sizeof(ImageGamma));
201 result[0].id.vt = VT_LPWSTR;
202 result[0].id.u.pwszVal = name;
203 result[0].value.vt = VT_UI4;
204 result[0].value.u.ulVal = gamma;
206 *items = result;
207 *item_count = 1;
209 return S_OK;
212 static const MetadataHandlerVtbl GamaReader_Vtbl = {
214 &CLSID_WICPngGamaMetadataReader,
215 LoadGamaMetadata
218 HRESULT PngGamaReader_CreateInstance(REFIID iid, void** ppv)
220 return MetadataReader_Create(&GamaReader_Vtbl, iid, ppv);
223 #ifdef SONAME_LIBPNG
225 static void *libpng_handle;
226 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
227 MAKE_FUNCPTR(png_create_read_struct);
228 MAKE_FUNCPTR(png_create_info_struct);
229 MAKE_FUNCPTR(png_create_write_struct);
230 MAKE_FUNCPTR(png_destroy_read_struct);
231 MAKE_FUNCPTR(png_destroy_write_struct);
232 MAKE_FUNCPTR(png_error);
233 MAKE_FUNCPTR(png_get_bit_depth);
234 MAKE_FUNCPTR(png_get_color_type);
235 MAKE_FUNCPTR(png_get_error_ptr);
236 MAKE_FUNCPTR(png_get_iCCP);
237 MAKE_FUNCPTR(png_get_image_height);
238 MAKE_FUNCPTR(png_get_image_width);
239 MAKE_FUNCPTR(png_get_io_ptr);
240 MAKE_FUNCPTR(png_get_pHYs);
241 MAKE_FUNCPTR(png_get_PLTE);
242 MAKE_FUNCPTR(png_get_tRNS);
243 MAKE_FUNCPTR(png_set_bgr);
244 MAKE_FUNCPTR(png_set_crc_action);
245 MAKE_FUNCPTR(png_set_error_fn);
246 #ifdef HAVE_PNG_SET_EXPAND_GRAY_1_2_4_TO_8
247 MAKE_FUNCPTR(png_set_expand_gray_1_2_4_to_8);
248 #else
249 MAKE_FUNCPTR(png_set_gray_1_2_4_to_8);
250 #endif
251 MAKE_FUNCPTR(png_set_filler);
252 MAKE_FUNCPTR(png_set_gray_to_rgb);
253 MAKE_FUNCPTR(png_set_interlace_handling);
254 MAKE_FUNCPTR(png_set_IHDR);
255 MAKE_FUNCPTR(png_set_pHYs);
256 MAKE_FUNCPTR(png_set_read_fn);
257 MAKE_FUNCPTR(png_set_strip_16);
258 MAKE_FUNCPTR(png_set_tRNS_to_alpha);
259 MAKE_FUNCPTR(png_set_write_fn);
260 MAKE_FUNCPTR(png_read_end);
261 MAKE_FUNCPTR(png_read_image);
262 MAKE_FUNCPTR(png_read_info);
263 MAKE_FUNCPTR(png_write_end);
264 MAKE_FUNCPTR(png_write_info);
265 MAKE_FUNCPTR(png_write_rows);
266 #undef MAKE_FUNCPTR
268 static CRITICAL_SECTION init_png_cs;
269 static CRITICAL_SECTION_DEBUG init_png_cs_debug =
271 0, 0, &init_png_cs,
272 { &init_png_cs_debug.ProcessLocksList,
273 &init_png_cs_debug.ProcessLocksList },
274 0, 0, { (DWORD_PTR)(__FILE__ ": init_png_cs") }
276 static CRITICAL_SECTION init_png_cs = { &init_png_cs_debug, -1, 0, 0, 0, 0 };
278 static void *load_libpng(void)
280 void *result;
282 EnterCriticalSection(&init_png_cs);
284 if(!libpng_handle && (libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL) {
286 #define LOAD_FUNCPTR(f) \
287 if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
288 libpng_handle = NULL; \
289 LeaveCriticalSection(&init_png_cs); \
290 return NULL; \
292 LOAD_FUNCPTR(png_create_read_struct);
293 LOAD_FUNCPTR(png_create_info_struct);
294 LOAD_FUNCPTR(png_create_write_struct);
295 LOAD_FUNCPTR(png_destroy_read_struct);
296 LOAD_FUNCPTR(png_destroy_write_struct);
297 LOAD_FUNCPTR(png_error);
298 LOAD_FUNCPTR(png_get_bit_depth);
299 LOAD_FUNCPTR(png_get_color_type);
300 LOAD_FUNCPTR(png_get_error_ptr);
301 LOAD_FUNCPTR(png_get_iCCP);
302 LOAD_FUNCPTR(png_get_image_height);
303 LOAD_FUNCPTR(png_get_image_width);
304 LOAD_FUNCPTR(png_get_io_ptr);
305 LOAD_FUNCPTR(png_get_pHYs);
306 LOAD_FUNCPTR(png_get_PLTE);
307 LOAD_FUNCPTR(png_get_tRNS);
308 LOAD_FUNCPTR(png_set_bgr);
309 LOAD_FUNCPTR(png_set_crc_action);
310 LOAD_FUNCPTR(png_set_error_fn);
311 #ifdef HAVE_PNG_SET_EXPAND_GRAY_1_2_4_TO_8
312 LOAD_FUNCPTR(png_set_expand_gray_1_2_4_to_8);
313 #else
314 LOAD_FUNCPTR(png_set_gray_1_2_4_to_8);
315 #endif
316 LOAD_FUNCPTR(png_set_filler);
317 LOAD_FUNCPTR(png_set_gray_to_rgb);
318 LOAD_FUNCPTR(png_set_interlace_handling);
319 LOAD_FUNCPTR(png_set_IHDR);
320 LOAD_FUNCPTR(png_set_pHYs);
321 LOAD_FUNCPTR(png_set_read_fn);
322 LOAD_FUNCPTR(png_set_strip_16);
323 LOAD_FUNCPTR(png_set_tRNS_to_alpha);
324 LOAD_FUNCPTR(png_set_write_fn);
325 LOAD_FUNCPTR(png_read_end);
326 LOAD_FUNCPTR(png_read_image);
327 LOAD_FUNCPTR(png_read_info);
328 LOAD_FUNCPTR(png_write_end);
329 LOAD_FUNCPTR(png_write_info);
330 LOAD_FUNCPTR(png_write_rows);
332 #undef LOAD_FUNCPTR
335 result = libpng_handle;
337 LeaveCriticalSection(&init_png_cs);
339 return result;
342 static void user_error_fn(png_structp png_ptr, png_const_charp error_message)
344 jmp_buf *pjmpbuf;
346 /* This uses setjmp/longjmp just like the default. We can't use the
347 * default because there's no way to access the jmp buffer in the png_struct
348 * that works in 1.2 and 1.4 and allows us to dynamically load libpng. */
349 WARN("PNG error: %s\n", debugstr_a(error_message));
350 pjmpbuf = ppng_get_error_ptr(png_ptr);
351 longjmp(*pjmpbuf, 1);
354 static void user_warning_fn(png_structp png_ptr, png_const_charp warning_message)
356 WARN("PNG warning: %s\n", debugstr_a(warning_message));
359 typedef struct {
360 ULARGE_INTEGER ofs, len;
361 IWICMetadataReader* reader;
362 } metadata_block_info;
364 typedef struct {
365 IWICBitmapDecoder IWICBitmapDecoder_iface;
366 IWICBitmapFrameDecode IWICBitmapFrameDecode_iface;
367 IWICMetadataBlockReader IWICMetadataBlockReader_iface;
368 LONG ref;
369 IStream *stream;
370 png_structp png_ptr;
371 png_infop info_ptr;
372 png_infop end_info;
373 BOOL initialized;
374 int bpp;
375 int width, height;
376 UINT stride;
377 const WICPixelFormatGUID *format;
378 BYTE *image_bits;
379 CRITICAL_SECTION lock; /* must be held when png structures are accessed or initialized is set */
380 ULONG metadata_count;
381 metadata_block_info* metadata_blocks;
382 } PngDecoder;
384 static inline PngDecoder *impl_from_IWICBitmapDecoder(IWICBitmapDecoder *iface)
386 return CONTAINING_RECORD(iface, PngDecoder, IWICBitmapDecoder_iface);
389 static inline PngDecoder *impl_from_IWICBitmapFrameDecode(IWICBitmapFrameDecode *iface)
391 return CONTAINING_RECORD(iface, PngDecoder, IWICBitmapFrameDecode_iface);
394 static inline PngDecoder *impl_from_IWICMetadataBlockReader(IWICMetadataBlockReader *iface)
396 return CONTAINING_RECORD(iface, PngDecoder, IWICMetadataBlockReader_iface);
399 static const IWICBitmapFrameDecodeVtbl PngDecoder_FrameVtbl;
401 static HRESULT WINAPI PngDecoder_QueryInterface(IWICBitmapDecoder *iface, REFIID iid,
402 void **ppv)
404 PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
405 TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
407 if (!ppv) return E_INVALIDARG;
409 if (IsEqualIID(&IID_IUnknown, iid) || IsEqualIID(&IID_IWICBitmapDecoder, iid))
411 *ppv = &This->IWICBitmapDecoder_iface;
413 else
415 *ppv = NULL;
416 return E_NOINTERFACE;
419 IUnknown_AddRef((IUnknown*)*ppv);
420 return S_OK;
423 static ULONG WINAPI PngDecoder_AddRef(IWICBitmapDecoder *iface)
425 PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
426 ULONG ref = InterlockedIncrement(&This->ref);
428 TRACE("(%p) refcount=%u\n", iface, ref);
430 return ref;
433 static ULONG WINAPI PngDecoder_Release(IWICBitmapDecoder *iface)
435 PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
436 ULONG ref = InterlockedDecrement(&This->ref);
437 ULONG i;
439 TRACE("(%p) refcount=%u\n", iface, ref);
441 if (ref == 0)
443 if (This->stream)
444 IStream_Release(This->stream);
445 if (This->png_ptr)
446 ppng_destroy_read_struct(&This->png_ptr, &This->info_ptr, &This->end_info);
447 This->lock.DebugInfo->Spare[0] = 0;
448 DeleteCriticalSection(&This->lock);
449 HeapFree(GetProcessHeap(), 0, This->image_bits);
450 for (i=0; i<This->metadata_count; i++)
452 if (This->metadata_blocks[i].reader)
453 IWICMetadataReader_Release(This->metadata_blocks[i].reader);
455 HeapFree(GetProcessHeap(), 0, This->metadata_blocks);
456 HeapFree(GetProcessHeap(), 0, This);
459 return ref;
462 static HRESULT WINAPI PngDecoder_QueryCapability(IWICBitmapDecoder *iface, IStream *stream,
463 DWORD *capability)
465 HRESULT hr;
467 TRACE("(%p,%p,%p)\n", iface, stream, capability);
469 if (!stream || !capability) return E_INVALIDARG;
471 hr = IWICBitmapDecoder_Initialize(iface, stream, WICDecodeMetadataCacheOnDemand);
472 if (hr != S_OK) return hr;
474 *capability = WICBitmapDecoderCapabilityCanDecodeAllImages |
475 WICBitmapDecoderCapabilityCanDecodeSomeImages;
476 /* FIXME: WICBitmapDecoderCapabilityCanEnumerateMetadata */
477 return S_OK;
480 static void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
482 IStream *stream = ppng_get_io_ptr(png_ptr);
483 HRESULT hr;
484 ULONG bytesread;
486 hr = IStream_Read(stream, data, length, &bytesread);
487 if (FAILED(hr) || bytesread != length)
489 ppng_error(png_ptr, "failed reading data");
493 static HRESULT WINAPI PngDecoder_Initialize(IWICBitmapDecoder *iface, IStream *pIStream,
494 WICDecodeOptions cacheOptions)
496 PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
497 LARGE_INTEGER seek;
498 HRESULT hr=S_OK;
499 png_bytep *row_pointers=NULL;
500 UINT image_size;
501 UINT i;
502 int color_type, bit_depth;
503 png_bytep trans;
504 int num_trans;
505 png_uint_32 transparency;
506 png_color_16p trans_values;
507 jmp_buf jmpbuf;
508 BYTE chunk_type[4];
509 ULONG chunk_size;
510 ULARGE_INTEGER chunk_start;
511 ULONG metadata_blocks_size = 0;
513 TRACE("(%p,%p,%x)\n", iface, pIStream, cacheOptions);
515 EnterCriticalSection(&This->lock);
517 /* initialize libpng */
518 This->png_ptr = ppng_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
519 if (!This->png_ptr)
521 hr = E_FAIL;
522 goto end;
525 This->info_ptr = ppng_create_info_struct(This->png_ptr);
526 if (!This->info_ptr)
528 ppng_destroy_read_struct(&This->png_ptr, NULL, NULL);
529 This->png_ptr = NULL;
530 hr = E_FAIL;
531 goto end;
534 This->end_info = ppng_create_info_struct(This->png_ptr);
535 if (!This->end_info)
537 ppng_destroy_read_struct(&This->png_ptr, &This->info_ptr, NULL);
538 This->png_ptr = NULL;
539 hr = E_FAIL;
540 goto end;
543 /* set up setjmp/longjmp error handling */
544 if (setjmp(jmpbuf))
546 ppng_destroy_read_struct(&This->png_ptr, &This->info_ptr, &This->end_info);
547 HeapFree(GetProcessHeap(), 0, row_pointers);
548 This->png_ptr = NULL;
549 hr = E_FAIL;
550 goto end;
552 ppng_set_error_fn(This->png_ptr, jmpbuf, user_error_fn, user_warning_fn);
553 ppng_set_crc_action(This->png_ptr, PNG_CRC_QUIET_USE, PNG_CRC_QUIET_USE);
555 /* seek to the start of the stream */
556 seek.QuadPart = 0;
557 hr = IStream_Seek(pIStream, seek, STREAM_SEEK_SET, NULL);
558 if (FAILED(hr)) goto end;
560 /* set up custom i/o handling */
561 ppng_set_read_fn(This->png_ptr, pIStream, user_read_data);
563 /* read the header */
564 ppng_read_info(This->png_ptr, This->info_ptr);
566 /* choose a pixel format */
567 color_type = ppng_get_color_type(This->png_ptr, This->info_ptr);
568 bit_depth = ppng_get_bit_depth(This->png_ptr, This->info_ptr);
570 /* check for color-keyed alpha */
571 transparency = ppng_get_tRNS(This->png_ptr, This->info_ptr, &trans, &num_trans, &trans_values);
573 if (transparency && color_type != PNG_COLOR_TYPE_PALETTE)
575 /* expand to RGBA */
576 if (color_type == PNG_COLOR_TYPE_GRAY)
578 if (bit_depth < 8)
580 #ifdef HAVE_PNG_SET_EXPAND_GRAY_1_2_4_TO_8
581 ppng_set_expand_gray_1_2_4_to_8(This->png_ptr);
582 #else
583 ppng_set_gray_1_2_4_to_8(This->png_ptr);
584 #endif
585 bit_depth = 8;
587 ppng_set_gray_to_rgb(This->png_ptr);
589 ppng_set_tRNS_to_alpha(This->png_ptr);
590 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
593 switch (color_type)
595 case PNG_COLOR_TYPE_GRAY:
596 This->bpp = bit_depth;
597 switch (bit_depth)
599 case 1: This->format = &GUID_WICPixelFormatBlackWhite; break;
600 case 2: This->format = &GUID_WICPixelFormat2bppGray; break;
601 case 4: This->format = &GUID_WICPixelFormat4bppGray; break;
602 case 8: This->format = &GUID_WICPixelFormat8bppGray; break;
603 case 16: This->format = &GUID_WICPixelFormat16bppGray; break;
604 default:
605 ERR("invalid grayscale bit depth: %i\n", bit_depth);
606 hr = E_FAIL;
607 goto end;
609 break;
610 case PNG_COLOR_TYPE_GRAY_ALPHA:
611 /* WIC does not support grayscale alpha formats so use RGBA */
612 ppng_set_gray_to_rgb(This->png_ptr);
613 /* fall through */
614 case PNG_COLOR_TYPE_RGB_ALPHA:
615 This->bpp = bit_depth * 4;
616 switch (bit_depth)
618 case 8:
619 ppng_set_bgr(This->png_ptr);
620 This->format = &GUID_WICPixelFormat32bppBGRA;
621 break;
622 case 16: This->format = &GUID_WICPixelFormat64bppRGBA; break;
623 default:
624 ERR("invalid RGBA bit depth: %i\n", bit_depth);
625 hr = E_FAIL;
626 goto end;
628 break;
629 case PNG_COLOR_TYPE_PALETTE:
630 This->bpp = bit_depth;
631 switch (bit_depth)
633 case 1: This->format = &GUID_WICPixelFormat1bppIndexed; break;
634 case 2: This->format = &GUID_WICPixelFormat2bppIndexed; break;
635 case 4: This->format = &GUID_WICPixelFormat4bppIndexed; break;
636 case 8: This->format = &GUID_WICPixelFormat8bppIndexed; break;
637 default:
638 ERR("invalid indexed color bit depth: %i\n", bit_depth);
639 hr = E_FAIL;
640 goto end;
642 break;
643 case PNG_COLOR_TYPE_RGB:
644 This->bpp = bit_depth * 3;
645 switch (bit_depth)
647 case 8:
648 ppng_set_bgr(This->png_ptr);
649 This->format = &GUID_WICPixelFormat24bppBGR;
650 break;
651 case 16: This->format = &GUID_WICPixelFormat48bppRGB; break;
652 default:
653 ERR("invalid RGB color bit depth: %i\n", bit_depth);
654 hr = E_FAIL;
655 goto end;
657 break;
658 default:
659 ERR("invalid color type %i\n", color_type);
660 hr = E_FAIL;
661 goto end;
664 /* read the image data */
665 This->width = ppng_get_image_width(This->png_ptr, This->info_ptr);
666 This->height = ppng_get_image_height(This->png_ptr, This->info_ptr);
667 This->stride = (This->width * This->bpp + 7) / 8;
668 image_size = This->stride * This->height;
670 This->image_bits = HeapAlloc(GetProcessHeap(), 0, image_size);
671 if (!This->image_bits)
673 hr = E_OUTOFMEMORY;
674 goto end;
677 row_pointers = HeapAlloc(GetProcessHeap(), 0, sizeof(png_bytep)*This->height);
678 if (!row_pointers)
680 hr = E_OUTOFMEMORY;
681 goto end;
684 for (i=0; i<This->height; i++)
685 row_pointers[i] = This->image_bits + i * This->stride;
687 ppng_read_image(This->png_ptr, row_pointers);
689 HeapFree(GetProcessHeap(), 0, row_pointers);
690 row_pointers = NULL;
692 ppng_read_end(This->png_ptr, This->end_info);
694 /* Find the metadata chunks in the file. */
695 seek.QuadPart = 8;
696 hr = IStream_Seek(pIStream, seek, STREAM_SEEK_SET, &chunk_start);
697 if (FAILED(hr)) goto end;
701 hr = read_png_chunk(pIStream, chunk_type, NULL, &chunk_size);
702 if (FAILED(hr)) goto end;
704 if (chunk_type[0] >= 'a' && chunk_type[0] <= 'z' &&
705 memcmp(chunk_type, "tRNS", 4) && memcmp(chunk_type, "pHYs", 4))
707 /* This chunk is considered metadata. */
708 if (This->metadata_count == metadata_blocks_size)
710 metadata_block_info* new_metadata_blocks;
711 ULONG new_metadata_blocks_size;
713 new_metadata_blocks_size = 4 + metadata_blocks_size * 2;
714 new_metadata_blocks = HeapAlloc(GetProcessHeap(), 0,
715 new_metadata_blocks_size * sizeof(*new_metadata_blocks));
717 if (!new_metadata_blocks)
719 hr = E_OUTOFMEMORY;
720 goto end;
723 memcpy(new_metadata_blocks, This->metadata_blocks,
724 This->metadata_count * sizeof(*new_metadata_blocks));
726 HeapFree(GetProcessHeap(), 0, This->metadata_blocks);
727 This->metadata_blocks = new_metadata_blocks;
728 metadata_blocks_size = new_metadata_blocks_size;
731 This->metadata_blocks[This->metadata_count].ofs = chunk_start;
732 This->metadata_blocks[This->metadata_count].len.QuadPart = chunk_size + 12;
733 This->metadata_blocks[This->metadata_count].reader = NULL;
734 This->metadata_count++;
737 seek.QuadPart = chunk_start.QuadPart + chunk_size + 12; /* skip data and CRC */
738 hr = IStream_Seek(pIStream, seek, STREAM_SEEK_SET, &chunk_start);
739 if (FAILED(hr)) goto end;
740 } while (memcmp(chunk_type, "IEND", 4));
742 This->stream = pIStream;
743 IStream_AddRef(This->stream);
745 This->initialized = TRUE;
747 end:
748 LeaveCriticalSection(&This->lock);
750 return hr;
753 static HRESULT WINAPI PngDecoder_GetContainerFormat(IWICBitmapDecoder *iface,
754 GUID *pguidContainerFormat)
756 memcpy(pguidContainerFormat, &GUID_ContainerFormatPng, sizeof(GUID));
757 return S_OK;
760 static HRESULT WINAPI PngDecoder_GetDecoderInfo(IWICBitmapDecoder *iface,
761 IWICBitmapDecoderInfo **ppIDecoderInfo)
763 HRESULT hr;
764 IWICComponentInfo *compinfo;
766 TRACE("(%p,%p)\n", iface, ppIDecoderInfo);
768 hr = CreateComponentInfo(&CLSID_WICPngDecoder, &compinfo);
769 if (FAILED(hr)) return hr;
771 hr = IWICComponentInfo_QueryInterface(compinfo, &IID_IWICBitmapDecoderInfo,
772 (void**)ppIDecoderInfo);
774 IWICComponentInfo_Release(compinfo);
776 return hr;
779 static HRESULT WINAPI PngDecoder_CopyPalette(IWICBitmapDecoder *iface,
780 IWICPalette *pIPalette)
782 FIXME("(%p,%p): stub\n", iface, pIPalette);
783 return E_NOTIMPL;
786 static HRESULT WINAPI PngDecoder_GetMetadataQueryReader(IWICBitmapDecoder *iface,
787 IWICMetadataQueryReader **ppIMetadataQueryReader)
789 FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
790 return E_NOTIMPL;
793 static HRESULT WINAPI PngDecoder_GetPreview(IWICBitmapDecoder *iface,
794 IWICBitmapSource **ppIBitmapSource)
796 TRACE("(%p,%p)\n", iface, ppIBitmapSource);
798 if (!ppIBitmapSource) return E_INVALIDARG;
800 *ppIBitmapSource = NULL;
801 return WINCODEC_ERR_UNSUPPORTEDOPERATION;
804 static HRESULT WINAPI PngDecoder_GetColorContexts(IWICBitmapDecoder *iface,
805 UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
807 TRACE("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);
808 return WINCODEC_ERR_UNSUPPORTEDOPERATION;
811 static HRESULT WINAPI PngDecoder_GetThumbnail(IWICBitmapDecoder *iface,
812 IWICBitmapSource **ppIThumbnail)
814 TRACE("(%p,%p)\n", iface, ppIThumbnail);
816 if (!ppIThumbnail) return E_INVALIDARG;
818 *ppIThumbnail = NULL;
819 return WINCODEC_ERR_CODECNOTHUMBNAIL;
822 static HRESULT WINAPI PngDecoder_GetFrameCount(IWICBitmapDecoder *iface,
823 UINT *pCount)
825 if (!pCount) return E_INVALIDARG;
827 *pCount = 1;
828 return S_OK;
831 static HRESULT WINAPI PngDecoder_GetFrame(IWICBitmapDecoder *iface,
832 UINT index, IWICBitmapFrameDecode **ppIBitmapFrame)
834 PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
835 TRACE("(%p,%u,%p)\n", iface, index, ppIBitmapFrame);
837 if (!This->initialized) return WINCODEC_ERR_FRAMEMISSING;
839 if (index != 0) return E_INVALIDARG;
841 IWICBitmapDecoder_AddRef(iface);
843 *ppIBitmapFrame = &This->IWICBitmapFrameDecode_iface;
845 return S_OK;
848 static const IWICBitmapDecoderVtbl PngDecoder_Vtbl = {
849 PngDecoder_QueryInterface,
850 PngDecoder_AddRef,
851 PngDecoder_Release,
852 PngDecoder_QueryCapability,
853 PngDecoder_Initialize,
854 PngDecoder_GetContainerFormat,
855 PngDecoder_GetDecoderInfo,
856 PngDecoder_CopyPalette,
857 PngDecoder_GetMetadataQueryReader,
858 PngDecoder_GetPreview,
859 PngDecoder_GetColorContexts,
860 PngDecoder_GetThumbnail,
861 PngDecoder_GetFrameCount,
862 PngDecoder_GetFrame
865 static HRESULT WINAPI PngDecoder_Frame_QueryInterface(IWICBitmapFrameDecode *iface, REFIID iid,
866 void **ppv)
868 PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
869 if (!ppv) return E_INVALIDARG;
871 if (IsEqualIID(&IID_IUnknown, iid) ||
872 IsEqualIID(&IID_IWICBitmapSource, iid) ||
873 IsEqualIID(&IID_IWICBitmapFrameDecode, iid))
875 *ppv = &This->IWICBitmapFrameDecode_iface;
877 else if (IsEqualIID(&IID_IWICMetadataBlockReader, iid))
879 *ppv = &This->IWICMetadataBlockReader_iface;
881 else
883 *ppv = NULL;
884 return E_NOINTERFACE;
887 IUnknown_AddRef((IUnknown*)*ppv);
888 return S_OK;
891 static ULONG WINAPI PngDecoder_Frame_AddRef(IWICBitmapFrameDecode *iface)
893 PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
894 return IWICBitmapDecoder_AddRef(&This->IWICBitmapDecoder_iface);
897 static ULONG WINAPI PngDecoder_Frame_Release(IWICBitmapFrameDecode *iface)
899 PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
900 return IWICBitmapDecoder_Release(&This->IWICBitmapDecoder_iface);
903 static HRESULT WINAPI PngDecoder_Frame_GetSize(IWICBitmapFrameDecode *iface,
904 UINT *puiWidth, UINT *puiHeight)
906 PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
907 *puiWidth = This->width;
908 *puiHeight = This->height;
909 TRACE("(%p)->(%u,%u)\n", iface, *puiWidth, *puiHeight);
910 return S_OK;
913 static HRESULT WINAPI PngDecoder_Frame_GetPixelFormat(IWICBitmapFrameDecode *iface,
914 WICPixelFormatGUID *pPixelFormat)
916 PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
917 TRACE("(%p,%p)\n", iface, pPixelFormat);
919 memcpy(pPixelFormat, This->format, sizeof(GUID));
921 return S_OK;
924 static HRESULT WINAPI PngDecoder_Frame_GetResolution(IWICBitmapFrameDecode *iface,
925 double *pDpiX, double *pDpiY)
927 PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
928 png_uint_32 ret, xres, yres;
929 int unit_type;
931 EnterCriticalSection(&This->lock);
933 ret = ppng_get_pHYs(This->png_ptr, This->info_ptr, &xres, &yres, &unit_type);
935 if (ret && unit_type == PNG_RESOLUTION_METER)
937 *pDpiX = xres * 0.0254;
938 *pDpiY = yres * 0.0254;
940 else
942 WARN("no pHYs block present\n");
943 *pDpiX = *pDpiY = 96.0;
946 LeaveCriticalSection(&This->lock);
948 TRACE("(%p)->(%0.2f,%0.2f)\n", iface, *pDpiX, *pDpiY);
950 return S_OK;
953 static HRESULT WINAPI PngDecoder_Frame_CopyPalette(IWICBitmapFrameDecode *iface,
954 IWICPalette *pIPalette)
956 PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
957 png_uint_32 ret;
958 png_colorp png_palette;
959 int num_palette;
960 WICColor palette[256];
961 png_bytep trans_alpha;
962 int num_trans;
963 png_color_16p trans_values;
964 int i;
965 HRESULT hr=S_OK;
967 TRACE("(%p,%p)\n", iface, pIPalette);
969 EnterCriticalSection(&This->lock);
971 ret = ppng_get_PLTE(This->png_ptr, This->info_ptr, &png_palette, &num_palette);
972 if (!ret)
974 hr = WINCODEC_ERR_PALETTEUNAVAILABLE;
975 goto end;
978 if (num_palette > 256)
980 ERR("palette has %i colors?!\n", num_palette);
981 hr = E_FAIL;
982 goto end;
985 ret = ppng_get_tRNS(This->png_ptr, This->info_ptr, &trans_alpha, &num_trans, &trans_values);
986 if (!ret) num_trans = 0;
988 for (i=0; i<num_palette; i++)
990 BYTE alpha = (i < num_trans) ? trans_alpha[i] : 0xff;
991 palette[i] = (alpha << 24 |
992 png_palette[i].red << 16|
993 png_palette[i].green << 8|
994 png_palette[i].blue);
997 end:
999 LeaveCriticalSection(&This->lock);
1001 if (SUCCEEDED(hr))
1002 hr = IWICPalette_InitializeCustom(pIPalette, palette, num_palette);
1004 return hr;
1007 static HRESULT WINAPI PngDecoder_Frame_CopyPixels(IWICBitmapFrameDecode *iface,
1008 const WICRect *prc, UINT cbStride, UINT cbBufferSize, BYTE *pbBuffer)
1010 PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
1011 TRACE("(%p,%p,%u,%u,%p)\n", iface, prc, cbStride, cbBufferSize, pbBuffer);
1013 return copy_pixels(This->bpp, This->image_bits,
1014 This->width, This->height, This->stride,
1015 prc, cbStride, cbBufferSize, pbBuffer);
1018 static HRESULT WINAPI PngDecoder_Frame_GetMetadataQueryReader(IWICBitmapFrameDecode *iface,
1019 IWICMetadataQueryReader **ppIMetadataQueryReader)
1021 PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
1023 TRACE("(%p,%p)\n", iface, ppIMetadataQueryReader);
1025 if (!ppIMetadataQueryReader)
1026 return E_INVALIDARG;
1028 return MetadataQueryReader_CreateInstance(&This->IWICMetadataBlockReader_iface, ppIMetadataQueryReader);
1031 static HRESULT WINAPI PngDecoder_Frame_GetColorContexts(IWICBitmapFrameDecode *iface,
1032 UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
1034 PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
1035 png_charp name;
1036 BYTE *profile;
1037 png_uint_32 len;
1038 int compression_type;
1039 HRESULT hr;
1041 TRACE("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);
1043 if (!pcActualCount) return E_INVALIDARG;
1045 EnterCriticalSection(&This->lock);
1047 if (ppng_get_iCCP(This->png_ptr, This->info_ptr, &name, &compression_type, (void *)&profile, &len))
1049 if (cCount && ppIColorContexts)
1051 hr = IWICColorContext_InitializeFromMemory(*ppIColorContexts, profile, len);
1052 if (FAILED(hr))
1054 LeaveCriticalSection(&This->lock);
1055 return hr;
1058 *pcActualCount = 1;
1060 else
1061 *pcActualCount = 0;
1063 LeaveCriticalSection(&This->lock);
1065 return S_OK;
1068 static HRESULT WINAPI PngDecoder_Frame_GetThumbnail(IWICBitmapFrameDecode *iface,
1069 IWICBitmapSource **ppIThumbnail)
1071 TRACE("(%p,%p)\n", iface, ppIThumbnail);
1073 if (!ppIThumbnail) return E_INVALIDARG;
1075 *ppIThumbnail = NULL;
1076 return WINCODEC_ERR_CODECNOTHUMBNAIL;
1079 static const IWICBitmapFrameDecodeVtbl PngDecoder_FrameVtbl = {
1080 PngDecoder_Frame_QueryInterface,
1081 PngDecoder_Frame_AddRef,
1082 PngDecoder_Frame_Release,
1083 PngDecoder_Frame_GetSize,
1084 PngDecoder_Frame_GetPixelFormat,
1085 PngDecoder_Frame_GetResolution,
1086 PngDecoder_Frame_CopyPalette,
1087 PngDecoder_Frame_CopyPixels,
1088 PngDecoder_Frame_GetMetadataQueryReader,
1089 PngDecoder_Frame_GetColorContexts,
1090 PngDecoder_Frame_GetThumbnail
1093 static HRESULT WINAPI PngDecoder_Block_QueryInterface(IWICMetadataBlockReader *iface, REFIID iid,
1094 void **ppv)
1096 PngDecoder *This = impl_from_IWICMetadataBlockReader(iface);
1097 return IWICBitmapFrameDecode_QueryInterface(&This->IWICBitmapFrameDecode_iface, iid, ppv);
1100 static ULONG WINAPI PngDecoder_Block_AddRef(IWICMetadataBlockReader *iface)
1102 PngDecoder *This = impl_from_IWICMetadataBlockReader(iface);
1103 return IWICBitmapDecoder_AddRef(&This->IWICBitmapDecoder_iface);
1106 static ULONG WINAPI PngDecoder_Block_Release(IWICMetadataBlockReader *iface)
1108 PngDecoder *This = impl_from_IWICMetadataBlockReader(iface);
1109 return IWICBitmapDecoder_Release(&This->IWICBitmapDecoder_iface);
1112 static HRESULT WINAPI PngDecoder_Block_GetContainerFormat(IWICMetadataBlockReader *iface,
1113 GUID *pguidContainerFormat)
1115 if (!pguidContainerFormat) return E_INVALIDARG;
1116 memcpy(pguidContainerFormat, &GUID_ContainerFormatPng, sizeof(GUID));
1117 return S_OK;
1120 static HRESULT WINAPI PngDecoder_Block_GetCount(IWICMetadataBlockReader *iface,
1121 UINT *pcCount)
1123 PngDecoder *This = impl_from_IWICMetadataBlockReader(iface);
1125 TRACE("%p,%p\n", iface, pcCount);
1127 if (!pcCount) return E_INVALIDARG;
1129 *pcCount = This->metadata_count;
1131 return S_OK;
1134 static HRESULT WINAPI PngDecoder_Block_GetReaderByIndex(IWICMetadataBlockReader *iface,
1135 UINT nIndex, IWICMetadataReader **ppIMetadataReader)
1137 PngDecoder *This = impl_from_IWICMetadataBlockReader(iface);
1138 HRESULT hr;
1139 IWICComponentFactory* factory;
1140 IWICStream* stream;
1142 TRACE("%p,%d,%p\n", iface, nIndex, ppIMetadataReader);
1144 if (nIndex >= This->metadata_count || !ppIMetadataReader)
1145 return E_INVALIDARG;
1147 if (!This->metadata_blocks[nIndex].reader)
1149 hr = StreamImpl_Create(&stream);
1151 if (SUCCEEDED(hr))
1153 hr = IWICStream_InitializeFromIStreamRegion(stream, This->stream,
1154 This->metadata_blocks[nIndex].ofs, This->metadata_blocks[nIndex].len);
1156 if (SUCCEEDED(hr))
1157 hr = ComponentFactory_CreateInstance(&IID_IWICComponentFactory, (void**)&factory);
1159 if (SUCCEEDED(hr))
1161 hr = IWICComponentFactory_CreateMetadataReaderFromContainer(factory,
1162 &GUID_ContainerFormatPng, NULL, WICMetadataCreationAllowUnknown,
1163 (IStream*)stream, &This->metadata_blocks[nIndex].reader);
1165 IWICComponentFactory_Release(factory);
1168 IWICStream_Release(stream);
1171 if (FAILED(hr))
1173 *ppIMetadataReader = NULL;
1174 return hr;
1178 *ppIMetadataReader = This->metadata_blocks[nIndex].reader;
1179 IWICMetadataReader_AddRef(*ppIMetadataReader);
1181 return S_OK;
1184 static HRESULT WINAPI PngDecoder_Block_GetEnumerator(IWICMetadataBlockReader *iface,
1185 IEnumUnknown **ppIEnumMetadata)
1187 FIXME("%p,%p\n", iface, ppIEnumMetadata);
1188 return E_NOTIMPL;
1191 static const IWICMetadataBlockReaderVtbl PngDecoder_BlockVtbl = {
1192 PngDecoder_Block_QueryInterface,
1193 PngDecoder_Block_AddRef,
1194 PngDecoder_Block_Release,
1195 PngDecoder_Block_GetContainerFormat,
1196 PngDecoder_Block_GetCount,
1197 PngDecoder_Block_GetReaderByIndex,
1198 PngDecoder_Block_GetEnumerator,
1201 HRESULT PngDecoder_CreateInstance(REFIID iid, void** ppv)
1203 PngDecoder *This;
1204 HRESULT ret;
1206 TRACE("(%s,%p)\n", debugstr_guid(iid), ppv);
1208 *ppv = NULL;
1210 if (!load_libpng())
1212 ERR("Failed reading PNG because unable to find %s\n",SONAME_LIBPNG);
1213 return E_FAIL;
1216 This = HeapAlloc(GetProcessHeap(), 0, sizeof(PngDecoder));
1217 if (!This) return E_OUTOFMEMORY;
1219 This->IWICBitmapDecoder_iface.lpVtbl = &PngDecoder_Vtbl;
1220 This->IWICBitmapFrameDecode_iface.lpVtbl = &PngDecoder_FrameVtbl;
1221 This->IWICMetadataBlockReader_iface.lpVtbl = &PngDecoder_BlockVtbl;
1222 This->ref = 1;
1223 This->png_ptr = NULL;
1224 This->info_ptr = NULL;
1225 This->end_info = NULL;
1226 This->stream = NULL;
1227 This->initialized = FALSE;
1228 This->image_bits = NULL;
1229 InitializeCriticalSection(&This->lock);
1230 This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": PngDecoder.lock");
1231 This->metadata_count = 0;
1232 This->metadata_blocks = NULL;
1234 ret = IWICBitmapDecoder_QueryInterface(&This->IWICBitmapDecoder_iface, iid, ppv);
1235 IWICBitmapDecoder_Release(&This->IWICBitmapDecoder_iface);
1237 return ret;
1240 struct png_pixelformat {
1241 const WICPixelFormatGUID *guid;
1242 UINT bpp;
1243 int bit_depth;
1244 int color_type;
1245 BOOL remove_filler;
1246 BOOL swap_rgb;
1249 static const struct png_pixelformat formats[] = {
1250 {&GUID_WICPixelFormat24bppBGR, 24, 8, PNG_COLOR_TYPE_RGB, 0, 1},
1251 {&GUID_WICPixelFormatBlackWhite, 1, 1, PNG_COLOR_TYPE_GRAY, 0, 0},
1252 {&GUID_WICPixelFormat2bppGray, 2, 2, PNG_COLOR_TYPE_GRAY, 0, 0},
1253 {&GUID_WICPixelFormat4bppGray, 4, 4, PNG_COLOR_TYPE_GRAY, 0, 0},
1254 {&GUID_WICPixelFormat8bppGray, 8, 8, PNG_COLOR_TYPE_GRAY, 0, 0},
1255 {&GUID_WICPixelFormat16bppGray, 16, 16, PNG_COLOR_TYPE_GRAY, 0, 0},
1256 {&GUID_WICPixelFormat32bppBGR, 32, 8, PNG_COLOR_TYPE_RGB, 1, 1},
1257 {&GUID_WICPixelFormat32bppBGRA, 32, 8, PNG_COLOR_TYPE_RGB_ALPHA, 0, 1},
1258 {&GUID_WICPixelFormat48bppRGB, 48, 16, PNG_COLOR_TYPE_RGB, 0, 0},
1259 {&GUID_WICPixelFormat64bppRGBA, 64, 16, PNG_COLOR_TYPE_RGB_ALPHA, 0, 0},
1260 {NULL},
1263 typedef struct PngEncoder {
1264 IWICBitmapEncoder IWICBitmapEncoder_iface;
1265 IWICBitmapFrameEncode IWICBitmapFrameEncode_iface;
1266 LONG ref;
1267 IStream *stream;
1268 png_structp png_ptr;
1269 png_infop info_ptr;
1270 UINT frame_count;
1271 BOOL frame_initialized;
1272 const struct png_pixelformat *format;
1273 BOOL info_written;
1274 UINT width, height;
1275 double xres, yres;
1276 UINT lines_written;
1277 BOOL frame_committed;
1278 BOOL committed;
1279 CRITICAL_SECTION lock;
1280 BOOL interlace;
1281 BYTE *data;
1282 UINT stride;
1283 UINT passes;
1284 } PngEncoder;
1286 static inline PngEncoder *impl_from_IWICBitmapEncoder(IWICBitmapEncoder *iface)
1288 return CONTAINING_RECORD(iface, PngEncoder, IWICBitmapEncoder_iface);
1291 static inline PngEncoder *impl_from_IWICBitmapFrameEncode(IWICBitmapFrameEncode *iface)
1293 return CONTAINING_RECORD(iface, PngEncoder, IWICBitmapFrameEncode_iface);
1296 static HRESULT WINAPI PngFrameEncode_QueryInterface(IWICBitmapFrameEncode *iface, REFIID iid,
1297 void **ppv)
1299 PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1300 TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
1302 if (!ppv) return E_INVALIDARG;
1304 if (IsEqualIID(&IID_IUnknown, iid) ||
1305 IsEqualIID(&IID_IWICBitmapFrameEncode, iid))
1307 *ppv = &This->IWICBitmapFrameEncode_iface;
1309 else
1311 *ppv = NULL;
1312 return E_NOINTERFACE;
1315 IUnknown_AddRef((IUnknown*)*ppv);
1316 return S_OK;
1319 static ULONG WINAPI PngFrameEncode_AddRef(IWICBitmapFrameEncode *iface)
1321 PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1322 return IWICBitmapEncoder_AddRef(&This->IWICBitmapEncoder_iface);
1325 static ULONG WINAPI PngFrameEncode_Release(IWICBitmapFrameEncode *iface)
1327 PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1328 return IWICBitmapEncoder_Release(&This->IWICBitmapEncoder_iface);
1331 static HRESULT WINAPI PngFrameEncode_Initialize(IWICBitmapFrameEncode *iface,
1332 IPropertyBag2 *pIEncoderOptions)
1334 PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1335 BOOL interlace;
1336 PROPBAG2 opts[1]= {{0}};
1337 VARIANT opt_values[1];
1338 HRESULT opt_hres[1];
1339 HRESULT hr;
1341 TRACE("(%p,%p)\n", iface, pIEncoderOptions);
1343 opts[0].pstrName = (LPOLESTR)wszPngInterlaceOption;
1344 opts[0].vt = VT_BOOL;
1346 if (pIEncoderOptions)
1348 hr = IPropertyBag2_Read(pIEncoderOptions, 1, opts, NULL, opt_values, opt_hres);
1350 if (FAILED(hr))
1351 return hr;
1353 else
1354 memset(opt_values, 0, sizeof(opt_values));
1356 if (V_VT(&opt_values[0]) == VT_EMPTY)
1357 interlace = FALSE;
1358 else
1359 interlace = (V_BOOL(&opt_values[0]) != 0);
1361 EnterCriticalSection(&This->lock);
1363 if (This->frame_initialized)
1365 LeaveCriticalSection(&This->lock);
1366 return WINCODEC_ERR_WRONGSTATE;
1369 This->interlace = interlace;
1371 This->frame_initialized = TRUE;
1373 LeaveCriticalSection(&This->lock);
1375 return S_OK;
1378 static HRESULT WINAPI PngFrameEncode_SetSize(IWICBitmapFrameEncode *iface,
1379 UINT uiWidth, UINT uiHeight)
1381 PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1382 TRACE("(%p,%u,%u)\n", iface, uiWidth, uiHeight);
1384 EnterCriticalSection(&This->lock);
1386 if (!This->frame_initialized || This->info_written)
1388 LeaveCriticalSection(&This->lock);
1389 return WINCODEC_ERR_WRONGSTATE;
1392 This->width = uiWidth;
1393 This->height = uiHeight;
1395 LeaveCriticalSection(&This->lock);
1397 return S_OK;
1400 static HRESULT WINAPI PngFrameEncode_SetResolution(IWICBitmapFrameEncode *iface,
1401 double dpiX, double dpiY)
1403 PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1404 TRACE("(%p,%0.2f,%0.2f)\n", iface, dpiX, dpiY);
1406 EnterCriticalSection(&This->lock);
1408 if (!This->frame_initialized || This->info_written)
1410 LeaveCriticalSection(&This->lock);
1411 return WINCODEC_ERR_WRONGSTATE;
1414 This->xres = dpiX;
1415 This->yres = dpiY;
1417 LeaveCriticalSection(&This->lock);
1419 return S_OK;
1422 static HRESULT WINAPI PngFrameEncode_SetPixelFormat(IWICBitmapFrameEncode *iface,
1423 WICPixelFormatGUID *pPixelFormat)
1425 PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1426 int i;
1427 TRACE("(%p,%s)\n", iface, debugstr_guid(pPixelFormat));
1429 EnterCriticalSection(&This->lock);
1431 if (!This->frame_initialized || This->info_written)
1433 LeaveCriticalSection(&This->lock);
1434 return WINCODEC_ERR_WRONGSTATE;
1437 for (i=0; formats[i].guid; i++)
1439 if (memcmp(formats[i].guid, pPixelFormat, sizeof(GUID)) == 0)
1440 break;
1443 if (!formats[i].guid) i = 0;
1445 This->format = &formats[i];
1446 memcpy(pPixelFormat, This->format->guid, sizeof(GUID));
1448 LeaveCriticalSection(&This->lock);
1450 return S_OK;
1453 static HRESULT WINAPI PngFrameEncode_SetColorContexts(IWICBitmapFrameEncode *iface,
1454 UINT cCount, IWICColorContext **ppIColorContext)
1456 FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
1457 return E_NOTIMPL;
1460 static HRESULT WINAPI PngFrameEncode_SetPalette(IWICBitmapFrameEncode *iface,
1461 IWICPalette *pIPalette)
1463 FIXME("(%p,%p): stub\n", iface, pIPalette);
1464 return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1467 static HRESULT WINAPI PngFrameEncode_SetThumbnail(IWICBitmapFrameEncode *iface,
1468 IWICBitmapSource *pIThumbnail)
1470 FIXME("(%p,%p): stub\n", iface, pIThumbnail);
1471 return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1474 static HRESULT WINAPI PngFrameEncode_WritePixels(IWICBitmapFrameEncode *iface,
1475 UINT lineCount, UINT cbStride, UINT cbBufferSize, BYTE *pbPixels)
1477 PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1478 png_byte **row_pointers=NULL;
1479 UINT i;
1480 jmp_buf jmpbuf;
1481 TRACE("(%p,%u,%u,%u,%p)\n", iface, lineCount, cbStride, cbBufferSize, pbPixels);
1483 EnterCriticalSection(&This->lock);
1485 if (!This->frame_initialized || !This->width || !This->height || !This->format)
1487 LeaveCriticalSection(&This->lock);
1488 return WINCODEC_ERR_WRONGSTATE;
1491 if (lineCount == 0 || lineCount + This->lines_written > This->height)
1493 LeaveCriticalSection(&This->lock);
1494 return E_INVALIDARG;
1497 /* set up setjmp/longjmp error handling */
1498 if (setjmp(jmpbuf))
1500 LeaveCriticalSection(&This->lock);
1501 HeapFree(GetProcessHeap(), 0, row_pointers);
1502 return E_FAIL;
1504 ppng_set_error_fn(This->png_ptr, jmpbuf, user_error_fn, user_warning_fn);
1506 if (!This->info_written)
1508 if (This->interlace)
1510 /* libpng requires us to write all data multiple times in this case. */
1511 This->stride = (This->format->bpp * This->width + 7)/8;
1512 This->data = HeapAlloc(GetProcessHeap(), 0, This->height * This->stride);
1513 if (!This->data)
1515 LeaveCriticalSection(&This->lock);
1516 return E_OUTOFMEMORY;
1520 ppng_set_IHDR(This->png_ptr, This->info_ptr, This->width, This->height,
1521 This->format->bit_depth, This->format->color_type,
1522 This->interlace ? PNG_INTERLACE_ADAM7 : PNG_INTERLACE_NONE,
1523 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
1525 if (This->xres != 0.0 && This->yres != 0.0)
1527 ppng_set_pHYs(This->png_ptr, This->info_ptr, (This->xres+0.0127) / 0.0254,
1528 (This->yres+0.0127) / 0.0254, PNG_RESOLUTION_METER);
1531 ppng_write_info(This->png_ptr, This->info_ptr);
1533 if (This->format->remove_filler)
1534 ppng_set_filler(This->png_ptr, 0, PNG_FILLER_AFTER);
1536 if (This->format->swap_rgb)
1537 ppng_set_bgr(This->png_ptr);
1539 if (This->interlace)
1540 This->passes = ppng_set_interlace_handling(This->png_ptr);
1542 This->info_written = TRUE;
1545 if (This->interlace)
1547 /* Just store the data so we can write it in multiple passes in Commit. */
1548 for (i=0; i<lineCount; i++)
1549 memcpy(This->data + This->stride * (This->lines_written + i),
1550 pbPixels + cbStride * i,
1551 This->stride);
1553 This->lines_written += lineCount;
1555 LeaveCriticalSection(&This->lock);
1556 return S_OK;
1559 row_pointers = HeapAlloc(GetProcessHeap(), 0, lineCount * sizeof(png_byte*));
1560 if (!row_pointers)
1562 LeaveCriticalSection(&This->lock);
1563 return E_OUTOFMEMORY;
1566 for (i=0; i<lineCount; i++)
1567 row_pointers[i] = pbPixels + cbStride * i;
1569 ppng_write_rows(This->png_ptr, row_pointers, lineCount);
1570 This->lines_written += lineCount;
1572 LeaveCriticalSection(&This->lock);
1574 HeapFree(GetProcessHeap(), 0, row_pointers);
1576 return S_OK;
1579 static HRESULT WINAPI PngFrameEncode_WriteSource(IWICBitmapFrameEncode *iface,
1580 IWICBitmapSource *pIBitmapSource, WICRect *prc)
1582 PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1583 HRESULT hr;
1584 TRACE("(%p,%p,%p)\n", iface, pIBitmapSource, prc);
1586 if (!This->frame_initialized)
1587 return WINCODEC_ERR_WRONGSTATE;
1589 hr = configure_write_source(iface, pIBitmapSource, prc,
1590 This->format ? This->format->guid : NULL, This->width, This->height,
1591 This->xres, This->yres);
1593 if (SUCCEEDED(hr))
1595 hr = write_source(iface, pIBitmapSource, prc,
1596 This->format->guid, This->format->bpp, This->width, This->height);
1599 return hr;
1602 static HRESULT WINAPI PngFrameEncode_Commit(IWICBitmapFrameEncode *iface)
1604 PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1605 png_byte **row_pointers=NULL;
1606 jmp_buf jmpbuf;
1607 TRACE("(%p)\n", iface);
1609 EnterCriticalSection(&This->lock);
1611 if (!This->info_written || This->lines_written != This->height || This->frame_committed)
1613 LeaveCriticalSection(&This->lock);
1614 return WINCODEC_ERR_WRONGSTATE;
1617 /* set up setjmp/longjmp error handling */
1618 if (setjmp(jmpbuf))
1620 LeaveCriticalSection(&This->lock);
1621 HeapFree(GetProcessHeap(), 0, row_pointers);
1622 return E_FAIL;
1624 ppng_set_error_fn(This->png_ptr, jmpbuf, user_error_fn, user_warning_fn);
1626 if (This->interlace)
1628 int i;
1630 row_pointers = HeapAlloc(GetProcessHeap(), 0, This->height * sizeof(png_byte*));
1631 if (!row_pointers)
1633 LeaveCriticalSection(&This->lock);
1634 return E_OUTOFMEMORY;
1637 for (i=0; i<This->height; i++)
1638 row_pointers[i] = This->data + This->stride * i;
1640 for (i=0; i<This->passes; i++)
1641 ppng_write_rows(This->png_ptr, row_pointers, This->height);
1644 ppng_write_end(This->png_ptr, This->info_ptr);
1646 This->frame_committed = TRUE;
1648 HeapFree(GetProcessHeap(), 0, row_pointers);
1650 LeaveCriticalSection(&This->lock);
1652 return S_OK;
1655 static HRESULT WINAPI PngFrameEncode_GetMetadataQueryWriter(IWICBitmapFrameEncode *iface,
1656 IWICMetadataQueryWriter **ppIMetadataQueryWriter)
1658 FIXME("(%p, %p): stub\n", iface, ppIMetadataQueryWriter);
1659 return E_NOTIMPL;
1662 static const IWICBitmapFrameEncodeVtbl PngEncoder_FrameVtbl = {
1663 PngFrameEncode_QueryInterface,
1664 PngFrameEncode_AddRef,
1665 PngFrameEncode_Release,
1666 PngFrameEncode_Initialize,
1667 PngFrameEncode_SetSize,
1668 PngFrameEncode_SetResolution,
1669 PngFrameEncode_SetPixelFormat,
1670 PngFrameEncode_SetColorContexts,
1671 PngFrameEncode_SetPalette,
1672 PngFrameEncode_SetThumbnail,
1673 PngFrameEncode_WritePixels,
1674 PngFrameEncode_WriteSource,
1675 PngFrameEncode_Commit,
1676 PngFrameEncode_GetMetadataQueryWriter
1679 static HRESULT WINAPI PngEncoder_QueryInterface(IWICBitmapEncoder *iface, REFIID iid,
1680 void **ppv)
1682 PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1683 TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
1685 if (!ppv) return E_INVALIDARG;
1687 if (IsEqualIID(&IID_IUnknown, iid) ||
1688 IsEqualIID(&IID_IWICBitmapEncoder, iid))
1690 *ppv = &This->IWICBitmapEncoder_iface;
1692 else
1694 *ppv = NULL;
1695 return E_NOINTERFACE;
1698 IUnknown_AddRef((IUnknown*)*ppv);
1699 return S_OK;
1702 static ULONG WINAPI PngEncoder_AddRef(IWICBitmapEncoder *iface)
1704 PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1705 ULONG ref = InterlockedIncrement(&This->ref);
1707 TRACE("(%p) refcount=%u\n", iface, ref);
1709 return ref;
1712 static ULONG WINAPI PngEncoder_Release(IWICBitmapEncoder *iface)
1714 PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1715 ULONG ref = InterlockedDecrement(&This->ref);
1717 TRACE("(%p) refcount=%u\n", iface, ref);
1719 if (ref == 0)
1721 This->lock.DebugInfo->Spare[0] = 0;
1722 DeleteCriticalSection(&This->lock);
1723 if (This->png_ptr)
1724 ppng_destroy_write_struct(&This->png_ptr, &This->info_ptr);
1725 if (This->stream)
1726 IStream_Release(This->stream);
1727 HeapFree(GetProcessHeap(), 0, This->data);
1728 HeapFree(GetProcessHeap(), 0, This);
1731 return ref;
1734 static void user_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
1736 PngEncoder *This = ppng_get_io_ptr(png_ptr);
1737 HRESULT hr;
1738 ULONG byteswritten;
1740 hr = IStream_Write(This->stream, data, length, &byteswritten);
1741 if (FAILED(hr) || byteswritten != length)
1743 ppng_error(png_ptr, "failed writing data");
1747 static void user_flush(png_structp png_ptr)
1751 static HRESULT WINAPI PngEncoder_Initialize(IWICBitmapEncoder *iface,
1752 IStream *pIStream, WICBitmapEncoderCacheOption cacheOption)
1754 PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1755 jmp_buf jmpbuf;
1757 TRACE("(%p,%p,%u)\n", iface, pIStream, cacheOption);
1759 EnterCriticalSection(&This->lock);
1761 if (This->png_ptr)
1763 LeaveCriticalSection(&This->lock);
1764 return WINCODEC_ERR_WRONGSTATE;
1767 /* initialize libpng */
1768 This->png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1769 if (!This->png_ptr)
1771 LeaveCriticalSection(&This->lock);
1772 return E_FAIL;
1775 This->info_ptr = ppng_create_info_struct(This->png_ptr);
1776 if (!This->info_ptr)
1778 ppng_destroy_write_struct(&This->png_ptr, NULL);
1779 This->png_ptr = NULL;
1780 LeaveCriticalSection(&This->lock);
1781 return E_FAIL;
1784 IStream_AddRef(pIStream);
1785 This->stream = pIStream;
1787 /* set up setjmp/longjmp error handling */
1788 if (setjmp(jmpbuf))
1790 ppng_destroy_write_struct(&This->png_ptr, &This->info_ptr);
1791 This->png_ptr = NULL;
1792 IStream_Release(This->stream);
1793 This->stream = NULL;
1794 LeaveCriticalSection(&This->lock);
1795 return E_FAIL;
1797 ppng_set_error_fn(This->png_ptr, jmpbuf, user_error_fn, user_warning_fn);
1799 /* set up custom i/o handling */
1800 ppng_set_write_fn(This->png_ptr, This, user_write_data, user_flush);
1802 LeaveCriticalSection(&This->lock);
1804 return S_OK;
1807 static HRESULT WINAPI PngEncoder_GetContainerFormat(IWICBitmapEncoder *iface,
1808 GUID *pguidContainerFormat)
1810 FIXME("(%p,%s): stub\n", iface, debugstr_guid(pguidContainerFormat));
1811 return E_NOTIMPL;
1814 static HRESULT WINAPI PngEncoder_GetEncoderInfo(IWICBitmapEncoder *iface,
1815 IWICBitmapEncoderInfo **ppIEncoderInfo)
1817 FIXME("(%p,%p): stub\n", iface, ppIEncoderInfo);
1818 return E_NOTIMPL;
1821 static HRESULT WINAPI PngEncoder_SetColorContexts(IWICBitmapEncoder *iface,
1822 UINT cCount, IWICColorContext **ppIColorContext)
1824 FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
1825 return E_NOTIMPL;
1828 static HRESULT WINAPI PngEncoder_SetPalette(IWICBitmapEncoder *iface, IWICPalette *pIPalette)
1830 TRACE("(%p,%p)\n", iface, pIPalette);
1831 return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1834 static HRESULT WINAPI PngEncoder_SetThumbnail(IWICBitmapEncoder *iface, IWICBitmapSource *pIThumbnail)
1836 TRACE("(%p,%p)\n", iface, pIThumbnail);
1837 return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1840 static HRESULT WINAPI PngEncoder_SetPreview(IWICBitmapEncoder *iface, IWICBitmapSource *pIPreview)
1842 TRACE("(%p,%p)\n", iface, pIPreview);
1843 return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1846 static HRESULT WINAPI PngEncoder_CreateNewFrame(IWICBitmapEncoder *iface,
1847 IWICBitmapFrameEncode **ppIFrameEncode, IPropertyBag2 **ppIEncoderOptions)
1849 PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1850 HRESULT hr;
1851 PROPBAG2 opts[1]= {{0}};
1853 TRACE("(%p,%p,%p)\n", iface, ppIFrameEncode, ppIEncoderOptions);
1855 EnterCriticalSection(&This->lock);
1857 if (This->frame_count != 0)
1859 LeaveCriticalSection(&This->lock);
1860 return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1863 if (!This->stream)
1865 LeaveCriticalSection(&This->lock);
1866 return WINCODEC_ERR_NOTINITIALIZED;
1869 opts[0].pstrName = (LPOLESTR)wszPngInterlaceOption;
1870 opts[0].vt = VT_BOOL;
1871 opts[0].dwType = PROPBAG2_TYPE_DATA;
1873 hr = CreatePropertyBag2(opts, 1, ppIEncoderOptions);
1874 if (FAILED(hr))
1876 LeaveCriticalSection(&This->lock);
1877 return hr;
1880 This->frame_count = 1;
1882 LeaveCriticalSection(&This->lock);
1884 IWICBitmapEncoder_AddRef(iface);
1885 *ppIFrameEncode = &This->IWICBitmapFrameEncode_iface;
1887 return S_OK;
1890 static HRESULT WINAPI PngEncoder_Commit(IWICBitmapEncoder *iface)
1892 PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1893 TRACE("(%p)\n", iface);
1895 EnterCriticalSection(&This->lock);
1897 if (!This->frame_committed || This->committed)
1899 LeaveCriticalSection(&This->lock);
1900 return WINCODEC_ERR_WRONGSTATE;
1903 This->committed = TRUE;
1905 LeaveCriticalSection(&This->lock);
1907 return S_OK;
1910 static HRESULT WINAPI PngEncoder_GetMetadataQueryWriter(IWICBitmapEncoder *iface,
1911 IWICMetadataQueryWriter **ppIMetadataQueryWriter)
1913 FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryWriter);
1914 return E_NOTIMPL;
1917 static const IWICBitmapEncoderVtbl PngEncoder_Vtbl = {
1918 PngEncoder_QueryInterface,
1919 PngEncoder_AddRef,
1920 PngEncoder_Release,
1921 PngEncoder_Initialize,
1922 PngEncoder_GetContainerFormat,
1923 PngEncoder_GetEncoderInfo,
1924 PngEncoder_SetColorContexts,
1925 PngEncoder_SetPalette,
1926 PngEncoder_SetThumbnail,
1927 PngEncoder_SetPreview,
1928 PngEncoder_CreateNewFrame,
1929 PngEncoder_Commit,
1930 PngEncoder_GetMetadataQueryWriter
1933 HRESULT PngEncoder_CreateInstance(REFIID iid, void** ppv)
1935 PngEncoder *This;
1936 HRESULT ret;
1938 TRACE("(%s,%p)\n", debugstr_guid(iid), ppv);
1940 *ppv = NULL;
1942 if (!load_libpng())
1944 ERR("Failed writing PNG because unable to find %s\n",SONAME_LIBPNG);
1945 return E_FAIL;
1948 This = HeapAlloc(GetProcessHeap(), 0, sizeof(PngEncoder));
1949 if (!This) return E_OUTOFMEMORY;
1951 This->IWICBitmapEncoder_iface.lpVtbl = &PngEncoder_Vtbl;
1952 This->IWICBitmapFrameEncode_iface.lpVtbl = &PngEncoder_FrameVtbl;
1953 This->ref = 1;
1954 This->png_ptr = NULL;
1955 This->info_ptr = NULL;
1956 This->stream = NULL;
1957 This->frame_count = 0;
1958 This->frame_initialized = FALSE;
1959 This->format = NULL;
1960 This->info_written = FALSE;
1961 This->width = 0;
1962 This->height = 0;
1963 This->xres = 0.0;
1964 This->yres = 0.0;
1965 This->lines_written = 0;
1966 This->frame_committed = FALSE;
1967 This->committed = FALSE;
1968 This->data = NULL;
1969 InitializeCriticalSection(&This->lock);
1970 This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": PngEncoder.lock");
1972 ret = IWICBitmapEncoder_QueryInterface(&This->IWICBitmapEncoder_iface, iid, ppv);
1973 IWICBitmapEncoder_Release(&This->IWICBitmapEncoder_iface);
1975 return ret;
1978 #else /* !HAVE_PNG_H */
1980 HRESULT PngDecoder_CreateInstance(REFIID iid, void** ppv)
1982 ERR("Trying to load PNG picture, but PNG support is not compiled in.\n");
1983 return E_FAIL;
1986 HRESULT PngEncoder_CreateInstance(REFIID iid, void** ppv)
1988 ERR("Trying to save PNG picture, but PNG support is not compiled in.\n");
1989 return E_FAIL;
1992 #endif