dinput: Fix printing NULL strings.
[wine] / dlls / windowscodecs / pngformat.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 #include "wine/port.h"
21
22 #include <stdarg.h>
23
24 #ifdef HAVE_PNG_H
25 #include <png.h>
26 #endif
27
28 #define COBJMACROS
29
30 #include "windef.h"
31 #include "winbase.h"
32 #include "objbase.h"
33 #include "wincodec.h"
34
35 #include "wincodecs_private.h"
36
37 #include "wine/debug.h"
38 #include "wine/library.h"
39
40 WINE_DEFAULT_DEBUG_CHANNEL(wincodecs);
41
42 #ifdef SONAME_LIBPNG
43
44 static void *libpng_handle;
45 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
46 MAKE_FUNCPTR(png_create_read_struct);
47 MAKE_FUNCPTR(png_create_info_struct);
48 MAKE_FUNCPTR(png_create_write_struct);
49 MAKE_FUNCPTR(png_destroy_read_struct);
50 MAKE_FUNCPTR(png_destroy_write_struct);
51 MAKE_FUNCPTR(png_error);
52 MAKE_FUNCPTR(png_get_bit_depth);
53 MAKE_FUNCPTR(png_get_color_type);
54 MAKE_FUNCPTR(png_get_error_ptr);
55 MAKE_FUNCPTR(png_get_image_height);
56 MAKE_FUNCPTR(png_get_image_width);
57 MAKE_FUNCPTR(png_get_io_ptr);
58 MAKE_FUNCPTR(png_get_pHYs);
59 MAKE_FUNCPTR(png_get_progressive_ptr);
60 MAKE_FUNCPTR(png_get_PLTE);
61 MAKE_FUNCPTR(png_get_tRNS);
62 MAKE_FUNCPTR(png_process_data);
63 MAKE_FUNCPTR(png_progressive_combine_row);
64 MAKE_FUNCPTR(png_set_bgr);
65 MAKE_FUNCPTR(png_set_error_fn);
66 #if HAVE_PNG_SET_EXPAND_GRAY_1_2_4_TO_8
67 MAKE_FUNCPTR(png_set_expand_gray_1_2_4_to_8);
68 #else
69 MAKE_FUNCPTR(png_set_gray_1_2_4_to_8);
70 #endif
71 MAKE_FUNCPTR(png_set_filler);
72 MAKE_FUNCPTR(png_set_gray_to_rgb);
73 MAKE_FUNCPTR(png_set_IHDR);
74 MAKE_FUNCPTR(png_set_pHYs);
75 MAKE_FUNCPTR(png_set_progressive_read_fn);
76 MAKE_FUNCPTR(png_set_read_fn);
77 MAKE_FUNCPTR(png_set_strip_16);
78 MAKE_FUNCPTR(png_set_tRNS_to_alpha);
79 MAKE_FUNCPTR(png_set_write_fn);
80 MAKE_FUNCPTR(png_read_end);
81 MAKE_FUNCPTR(png_read_image);
82 MAKE_FUNCPTR(png_read_info);
83 MAKE_FUNCPTR(png_read_update_info);
84 MAKE_FUNCPTR(png_write_end);
85 MAKE_FUNCPTR(png_write_info);
86 MAKE_FUNCPTR(png_write_rows);
87 #undef MAKE_FUNCPTR
88
89 static void *load_libpng(void)
90 {
91     if((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL) {
92
93 #define LOAD_FUNCPTR(f) \
94     if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
95         libpng_handle = NULL; \
96         return NULL; \
97     }
98         LOAD_FUNCPTR(png_create_read_struct);
99         LOAD_FUNCPTR(png_create_info_struct);
100         LOAD_FUNCPTR(png_create_write_struct);
101         LOAD_FUNCPTR(png_destroy_read_struct);
102         LOAD_FUNCPTR(png_destroy_write_struct);
103         LOAD_FUNCPTR(png_error);
104         LOAD_FUNCPTR(png_get_bit_depth);
105         LOAD_FUNCPTR(png_get_color_type);
106         LOAD_FUNCPTR(png_get_error_ptr);
107         LOAD_FUNCPTR(png_get_image_height);
108         LOAD_FUNCPTR(png_get_image_width);
109         LOAD_FUNCPTR(png_get_io_ptr);
110         LOAD_FUNCPTR(png_get_pHYs);
111         LOAD_FUNCPTR(png_get_progressive_ptr);
112         LOAD_FUNCPTR(png_get_PLTE);
113         LOAD_FUNCPTR(png_get_tRNS);
114         LOAD_FUNCPTR(png_process_data);
115         LOAD_FUNCPTR(png_progressive_combine_row);
116         LOAD_FUNCPTR(png_set_bgr);
117         LOAD_FUNCPTR(png_set_error_fn);
118 #if HAVE_PNG_SET_EXPAND_GRAY_1_2_4_TO_8
119         LOAD_FUNCPTR(png_set_expand_gray_1_2_4_to_8);
120 #else
121         LOAD_FUNCPTR(png_set_gray_1_2_4_to_8);
122 #endif
123         LOAD_FUNCPTR(png_set_filler);
124         LOAD_FUNCPTR(png_set_gray_to_rgb);
125         LOAD_FUNCPTR(png_set_IHDR);
126         LOAD_FUNCPTR(png_set_pHYs);
127         LOAD_FUNCPTR(png_set_progressive_read_fn);
128         LOAD_FUNCPTR(png_set_read_fn);
129         LOAD_FUNCPTR(png_set_strip_16);
130         LOAD_FUNCPTR(png_set_tRNS_to_alpha);
131         LOAD_FUNCPTR(png_set_write_fn);
132         LOAD_FUNCPTR(png_read_end);
133         LOAD_FUNCPTR(png_read_image);
134         LOAD_FUNCPTR(png_read_info);
135         LOAD_FUNCPTR(png_read_update_info);
136         LOAD_FUNCPTR(png_write_end);
137         LOAD_FUNCPTR(png_write_info);
138         LOAD_FUNCPTR(png_write_rows);
139
140 #undef LOAD_FUNCPTR
141     }
142     return libpng_handle;
143 }
144
145 static void user_error_fn(png_structp png_ptr, png_const_charp error_message)
146 {
147     jmp_buf *pjmpbuf;
148
149     /* This uses setjmp/longjmp just like the default. We can't use the
150      * default because there's no way to access the jmp buffer in the png_struct
151      * that works in 1.2 and 1.4 and allows us to dynamically load libpng. */
152     WARN("PNG error: %s\n", debugstr_a(error_message));
153     pjmpbuf = ppng_get_error_ptr(png_ptr);
154     longjmp(*pjmpbuf, 1);
155 }
156
157 static void user_warning_fn(png_structp png_ptr, png_const_charp warning_message)
158 {
159     WARN("PNG warning: %s\n", debugstr_a(warning_message));
160 }
161
162 typedef struct {
163     IWICBitmapDecoder IWICBitmapDecoder_iface;
164     IWICBitmapFrameDecode IWICBitmapFrameDecode_iface;
165     LONG ref;
166     png_structp png_ptr;
167     png_infop info_ptr;
168     BOOL initialized;
169     int bpp;
170     int width, height;
171     UINT stride;
172     const WICPixelFormatGUID *format;
173     BYTE *image_bits;
174     CRITICAL_SECTION lock; /* must be held when png structures are accessed or initialized is set */
175 } PngDecoder;
176
177 static inline PngDecoder *impl_from_IWICBitmapDecoder(IWICBitmapDecoder *iface)
178 {
179     return CONTAINING_RECORD(iface, PngDecoder, IWICBitmapDecoder_iface);
180 }
181
182 static inline PngDecoder *impl_from_IWICBitmapFrameDecode(IWICBitmapFrameDecode *iface)
183 {
184     return CONTAINING_RECORD(iface, PngDecoder, IWICBitmapFrameDecode_iface);
185 }
186
187 static const IWICBitmapFrameDecodeVtbl PngDecoder_FrameVtbl;
188
189 static HRESULT WINAPI PngDecoder_QueryInterface(IWICBitmapDecoder *iface, REFIID iid,
190     void **ppv)
191 {
192     PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
193     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
194
195     if (!ppv) return E_INVALIDARG;
196
197     if (IsEqualIID(&IID_IUnknown, iid) || IsEqualIID(&IID_IWICBitmapDecoder, iid))
198     {
199         *ppv = This;
200     }
201     else
202     {
203         *ppv = NULL;
204         return E_NOINTERFACE;
205     }
206
207     IUnknown_AddRef((IUnknown*)*ppv);
208     return S_OK;
209 }
210
211 static ULONG WINAPI PngDecoder_AddRef(IWICBitmapDecoder *iface)
212 {
213     PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
214     ULONG ref = InterlockedIncrement(&This->ref);
215
216     TRACE("(%p) refcount=%u\n", iface, ref);
217
218     return ref;
219 }
220
221 static ULONG WINAPI PngDecoder_Release(IWICBitmapDecoder *iface)
222 {
223     PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
224     ULONG ref = InterlockedDecrement(&This->ref);
225
226     TRACE("(%p) refcount=%u\n", iface, ref);
227
228     if (ref == 0)
229     {
230         if (This->png_ptr)
231             ppng_destroy_read_struct(&This->png_ptr, &This->info_ptr, NULL);
232         This->lock.DebugInfo->Spare[0] = 0;
233         DeleteCriticalSection(&This->lock);
234         HeapFree(GetProcessHeap(), 0, This->image_bits);
235         HeapFree(GetProcessHeap(), 0, This);
236     }
237
238     return ref;
239 }
240
241 static HRESULT WINAPI PngDecoder_QueryCapability(IWICBitmapDecoder *iface, IStream *pIStream,
242     DWORD *pdwCapability)
243 {
244     FIXME("(%p,%p,%p): stub\n", iface, pIStream, pdwCapability);
245     return E_NOTIMPL;
246 }
247
248 static void info_callback(png_structp png_ptr, png_infop info)
249 {
250     int color_type, bit_depth;
251     png_bytep trans;
252     int num_trans;
253     png_uint_32 transparency;
254     png_color_16p trans_values;
255     UINT image_size;
256     HRESULT hr = S_OK;
257     PngDecoder *This;
258
259     This = (PngDecoder*) ppng_get_progressive_ptr(png_ptr);
260
261     /* choose a pixel format */
262     color_type = ppng_get_color_type(This->png_ptr, This->info_ptr);
263     bit_depth = ppng_get_bit_depth(This->png_ptr, This->info_ptr);
264
265     /* check for color-keyed alpha */
266     transparency = ppng_get_tRNS(This->png_ptr, This->info_ptr, &trans, &num_trans, &trans_values);
267
268     if (transparency && color_type != PNG_COLOR_TYPE_PALETTE)
269     {
270         /* expand to RGBA */
271         if (color_type == PNG_COLOR_TYPE_GRAY)
272         {
273             if (bit_depth < 8)
274             {
275 #if HAVE_PNG_SET_EXPAND_GRAY_1_2_4_TO_8
276                 ppng_set_expand_gray_1_2_4_to_8(This->png_ptr);
277 #else
278                 ppng_set_gray_1_2_4_to_8(This->png_ptr);
279 #endif
280                 bit_depth = 8;
281             }
282             ppng_set_gray_to_rgb(This->png_ptr);
283         }
284         ppng_set_tRNS_to_alpha(This->png_ptr);
285         color_type = PNG_COLOR_TYPE_RGB_ALPHA;
286     }
287
288     switch (color_type)
289     {
290     case PNG_COLOR_TYPE_GRAY:
291         This->bpp = bit_depth;
292         switch (bit_depth)
293         {
294         case 1: This->format = &GUID_WICPixelFormatBlackWhite; break;
295         case 2: This->format = &GUID_WICPixelFormat2bppGray; break;
296         case 4: This->format = &GUID_WICPixelFormat4bppGray; break;
297         case 8: This->format = &GUID_WICPixelFormat8bppGray; break;
298         case 16: This->format = &GUID_WICPixelFormat16bppGray; break;
299         default:
300             ERR("invalid grayscale bit depth: %i\n", bit_depth);
301             hr = E_FAIL;
302             goto end;
303         }
304         break;
305     case PNG_COLOR_TYPE_GRAY_ALPHA:
306         /* WIC does not support grayscale alpha formats so use RGBA */
307         ppng_set_gray_to_rgb(This->png_ptr);
308     case PNG_COLOR_TYPE_RGB_ALPHA:
309         This->bpp = bit_depth * 4;
310         switch (bit_depth)
311         {
312         case 8:
313             ppng_set_bgr(This->png_ptr);
314             This->format = &GUID_WICPixelFormat32bppBGRA;
315             break;
316         case 16: This->format = &GUID_WICPixelFormat64bppRGBA; break;
317         default:
318             ERR("invalid RGBA bit depth: %i\n", bit_depth);
319             hr = E_FAIL;
320             goto end;
321         }
322         break;
323     case PNG_COLOR_TYPE_PALETTE:
324         This->bpp = bit_depth;
325         switch (bit_depth)
326         {
327         case 1: This->format = &GUID_WICPixelFormat1bppIndexed; break;
328         case 2: This->format = &GUID_WICPixelFormat2bppIndexed; break;
329         case 4: This->format = &GUID_WICPixelFormat4bppIndexed; break;
330         case 8: This->format = &GUID_WICPixelFormat8bppIndexed; break;
331         default:
332             ERR("invalid indexed color bit depth: %i\n", bit_depth);
333             hr = E_FAIL;
334             goto end;
335         }
336         break;
337     case PNG_COLOR_TYPE_RGB:
338         This->bpp = bit_depth * 3;
339         switch (bit_depth)
340         {
341         case 8:
342             ppng_set_bgr(This->png_ptr);
343             This->format = &GUID_WICPixelFormat24bppBGR;
344             break;
345         case 16: This->format = &GUID_WICPixelFormat48bppRGB; break;
346         default:
347             ERR("invalid RGB color bit depth: %i\n", bit_depth);
348             hr = E_FAIL;
349             goto end;
350         }
351         break;
352     default:
353         ERR("invalid color type %i\n", color_type);
354         hr = E_FAIL;
355         goto end;
356     }
357
358     This->width = ppng_get_image_width(This->png_ptr, This->info_ptr);
359     This->height = ppng_get_image_height(This->png_ptr, This->info_ptr);
360     This->stride = This->width * This->bpp;
361     image_size = This->stride * This->height;
362
363     This->image_bits = HeapAlloc(GetProcessHeap(), 0, image_size);
364     if (!This->image_bits)
365     {
366         hr = E_OUTOFMEMORY;
367         goto end;
368     }
369
370     ppng_read_update_info(This->png_ptr, This->info_ptr);
371     This->initialized = TRUE;
372
373 end:
374     if (FAILED(hr))
375         ERR("PNG info parsing failed, hr=0x%08X\n", hr);
376 }
377
378 static void row_callback(png_structp png_ptr, png_bytep new_row,
379                          png_uint_32 row_num, int pass)
380 {
381     png_bytep old_row;
382     PngDecoder *This;
383
384     This = (PngDecoder*) ppng_get_progressive_ptr(png_ptr);
385     if (!This->initialized)
386         return;
387
388     old_row = ((png_bytep)This->image_bits) + row_num*This->stride;
389     ppng_progressive_combine_row(png_ptr, old_row, new_row);
390 }
391
392 static void end_callback(png_structp png_ptr, png_infop info)
393 {
394 }
395
396 static HRESULT WINAPI PngDecoder_Initialize(IWICBitmapDecoder *iface, IStream *pIStream,
397     WICDecodeOptions cacheOptions)
398 {
399     PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
400     LARGE_INTEGER seek;
401     HRESULT hr=S_OK;
402     png_bytep *row_pointers=NULL;
403     jmp_buf jmpbuf;
404     BYTE buffer[8096];
405     ULONG bytesRead = 0;
406
407     TRACE("(%p,%p,%x)\n", iface, pIStream, cacheOptions);
408
409     EnterCriticalSection(&This->lock);
410
411     /* initialize libpng */
412     This->png_ptr = ppng_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
413     if (!This->png_ptr)
414     {
415         hr = E_FAIL;
416         goto end;
417     }
418
419     This->info_ptr = ppng_create_info_struct(This->png_ptr);
420     if (!This->info_ptr)
421     {
422         ppng_destroy_read_struct(&This->png_ptr, NULL, NULL);
423         This->png_ptr = NULL;
424         hr = E_FAIL;
425         goto end;
426     }
427
428     /* set up setjmp/longjmp error handling */
429     if (setjmp(jmpbuf))
430     {
431         ppng_destroy_read_struct(&This->png_ptr, &This->info_ptr, NULL);
432         HeapFree(GetProcessHeap(), 0, row_pointers);
433         This->png_ptr = NULL;
434         hr = E_FAIL;
435         goto end;
436     }
437     ppng_set_error_fn(This->png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
438
439     /* seek to the start of the stream */
440     seek.QuadPart = 0;
441     hr = IStream_Seek(pIStream, seek, STREAM_SEEK_SET, NULL);
442     if (FAILED(hr)) goto end;
443
444     /* set up progressive loading */
445     ppng_set_progressive_read_fn(This->png_ptr, (void*)This,
446         info_callback, row_callback, end_callback);
447
448     do
449     {
450         hr = IStream_Read(pIStream, buffer, sizeof(buffer), &bytesRead);
451         if (SUCCEEDED(hr))
452             ppng_process_data(This->png_ptr, This->info_ptr, buffer, bytesRead);
453     } while (bytesRead == sizeof(buffer));
454     if (hr == S_FALSE)
455         hr = S_OK;
456     if (FAILED(hr))
457         ERR("reading PNG file failed, error 0x%08X\n", hr);
458     if (!This->initialized)
459         hr = E_FAIL;
460
461 end:
462
463     LeaveCriticalSection(&This->lock);
464
465     return hr;
466 }
467
468 static HRESULT WINAPI PngDecoder_GetContainerFormat(IWICBitmapDecoder *iface,
469     GUID *pguidContainerFormat)
470 {
471     memcpy(pguidContainerFormat, &GUID_ContainerFormatPng, sizeof(GUID));
472     return S_OK;
473 }
474
475 static HRESULT WINAPI PngDecoder_GetDecoderInfo(IWICBitmapDecoder *iface,
476     IWICBitmapDecoderInfo **ppIDecoderInfo)
477 {
478     HRESULT hr;
479     IWICComponentInfo *compinfo;
480
481     TRACE("(%p,%p)\n", iface, ppIDecoderInfo);
482
483     hr = CreateComponentInfo(&CLSID_WICPngDecoder, &compinfo);
484     if (FAILED(hr)) return hr;
485
486     hr = IWICComponentInfo_QueryInterface(compinfo, &IID_IWICBitmapDecoderInfo,
487         (void**)ppIDecoderInfo);
488
489     IWICComponentInfo_Release(compinfo);
490
491     return hr;
492 }
493
494 static HRESULT WINAPI PngDecoder_CopyPalette(IWICBitmapDecoder *iface,
495     IWICPalette *pIPalette)
496 {
497     FIXME("(%p,%p): stub\n", iface, pIPalette);
498     return E_NOTIMPL;
499 }
500
501 static HRESULT WINAPI PngDecoder_GetMetadataQueryReader(IWICBitmapDecoder *iface,
502     IWICMetadataQueryReader **ppIMetadataQueryReader)
503 {
504     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
505     return E_NOTIMPL;
506 }
507
508 static HRESULT WINAPI PngDecoder_GetPreview(IWICBitmapDecoder *iface,
509     IWICBitmapSource **ppIBitmapSource)
510 {
511     FIXME("(%p,%p): stub\n", iface, ppIBitmapSource);
512     return E_NOTIMPL;
513 }
514
515 static HRESULT WINAPI PngDecoder_GetColorContexts(IWICBitmapDecoder *iface,
516     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
517 {
518     FIXME("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);
519     return E_NOTIMPL;
520 }
521
522 static HRESULT WINAPI PngDecoder_GetThumbnail(IWICBitmapDecoder *iface,
523     IWICBitmapSource **ppIThumbnail)
524 {
525     TRACE("(%p,%p)\n", iface, ppIThumbnail);
526     return WINCODEC_ERR_CODECNOTHUMBNAIL;
527 }
528
529 static HRESULT WINAPI PngDecoder_GetFrameCount(IWICBitmapDecoder *iface,
530     UINT *pCount)
531 {
532     *pCount = 1;
533     return S_OK;
534 }
535
536 static HRESULT WINAPI PngDecoder_GetFrame(IWICBitmapDecoder *iface,
537     UINT index, IWICBitmapFrameDecode **ppIBitmapFrame)
538 {
539     PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
540     TRACE("(%p,%u,%p)\n", iface, index, ppIBitmapFrame);
541
542     if (!This->initialized) return WINCODEC_ERR_NOTINITIALIZED;
543
544     if (index != 0) return E_INVALIDARG;
545
546     IWICBitmapDecoder_AddRef(iface);
547
548     *ppIBitmapFrame = &This->IWICBitmapFrameDecode_iface;
549
550     return S_OK;
551 }
552
553 static const IWICBitmapDecoderVtbl PngDecoder_Vtbl = {
554     PngDecoder_QueryInterface,
555     PngDecoder_AddRef,
556     PngDecoder_Release,
557     PngDecoder_QueryCapability,
558     PngDecoder_Initialize,
559     PngDecoder_GetContainerFormat,
560     PngDecoder_GetDecoderInfo,
561     PngDecoder_CopyPalette,
562     PngDecoder_GetMetadataQueryReader,
563     PngDecoder_GetPreview,
564     PngDecoder_GetColorContexts,
565     PngDecoder_GetThumbnail,
566     PngDecoder_GetFrameCount,
567     PngDecoder_GetFrame
568 };
569
570 static HRESULT WINAPI PngDecoder_Frame_QueryInterface(IWICBitmapFrameDecode *iface, REFIID iid,
571     void **ppv)
572 {
573     if (!ppv) return E_INVALIDARG;
574
575     if (IsEqualIID(&IID_IUnknown, iid) ||
576         IsEqualIID(&IID_IWICBitmapSource, iid) ||
577         IsEqualIID(&IID_IWICBitmapFrameDecode, iid))
578     {
579         *ppv = iface;
580     }
581     else
582     {
583         *ppv = NULL;
584         return E_NOINTERFACE;
585     }
586
587     IUnknown_AddRef((IUnknown*)*ppv);
588     return S_OK;
589 }
590
591 static ULONG WINAPI PngDecoder_Frame_AddRef(IWICBitmapFrameDecode *iface)
592 {
593     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
594     return IUnknown_AddRef((IUnknown*)This);
595 }
596
597 static ULONG WINAPI PngDecoder_Frame_Release(IWICBitmapFrameDecode *iface)
598 {
599     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
600     return IUnknown_Release((IUnknown*)This);
601 }
602
603 static HRESULT WINAPI PngDecoder_Frame_GetSize(IWICBitmapFrameDecode *iface,
604     UINT *puiWidth, UINT *puiHeight)
605 {
606     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
607     *puiWidth = This->width;
608     *puiHeight = This->height;
609     TRACE("(%p)->(%u,%u)\n", iface, *puiWidth, *puiHeight);
610     return S_OK;
611 }
612
613 static HRESULT WINAPI PngDecoder_Frame_GetPixelFormat(IWICBitmapFrameDecode *iface,
614     WICPixelFormatGUID *pPixelFormat)
615 {
616     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
617     TRACE("(%p,%p)\n", iface, pPixelFormat);
618
619     memcpy(pPixelFormat, This->format, sizeof(GUID));
620
621     return S_OK;
622 }
623
624 static HRESULT WINAPI PngDecoder_Frame_GetResolution(IWICBitmapFrameDecode *iface,
625     double *pDpiX, double *pDpiY)
626 {
627     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
628     png_uint_32 ret, xres, yres;
629     int unit_type;
630
631     EnterCriticalSection(&This->lock);
632
633     ret = ppng_get_pHYs(This->png_ptr, This->info_ptr, &xres, &yres, &unit_type);
634
635     if (ret && unit_type == PNG_RESOLUTION_METER)
636     {
637         *pDpiX = xres * 0.0254;
638         *pDpiY = yres * 0.0254;
639     }
640     else
641     {
642         WARN("no pHYs block present\n");
643         *pDpiX = *pDpiY = 96.0;
644     }
645
646     LeaveCriticalSection(&This->lock);
647
648     TRACE("(%p)->(%0.2f,%0.2f)\n", iface, *pDpiX, *pDpiY);
649
650     return S_OK;
651 }
652
653 static HRESULT WINAPI PngDecoder_Frame_CopyPalette(IWICBitmapFrameDecode *iface,
654     IWICPalette *pIPalette)
655 {
656     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
657     png_uint_32 ret;
658     png_colorp png_palette;
659     int num_palette;
660     WICColor palette[256];
661     png_bytep trans;
662     int num_trans;
663     png_color_16p trans_values;
664     int i;
665     HRESULT hr=S_OK;
666
667     TRACE("(%p,%p)\n", iface, pIPalette);
668
669     EnterCriticalSection(&This->lock);
670
671     ret = ppng_get_PLTE(This->png_ptr, This->info_ptr, &png_palette, &num_palette);
672     if (!ret)
673     {
674         hr = WINCODEC_ERR_PALETTEUNAVAILABLE;
675         goto end;
676     }
677
678     if (num_palette > 256)
679     {
680         ERR("palette has %i colors?!\n", num_palette);
681         hr = E_FAIL;
682         goto end;
683     }
684
685     for (i=0; i<num_palette; i++)
686     {
687         palette[i] = (0xff000000|
688                       png_palette[i].red << 16|
689                       png_palette[i].green << 8|
690                       png_palette[i].blue);
691     }
692
693     ret = ppng_get_tRNS(This->png_ptr, This->info_ptr, &trans, &num_trans, &trans_values);
694     if (ret)
695     {
696         for (i=0; i<num_trans; i++)
697         {
698             palette[trans[i]] = 0x00000000;
699         }
700     }
701
702 end:
703
704     LeaveCriticalSection(&This->lock);
705
706     if (SUCCEEDED(hr))
707         hr = IWICPalette_InitializeCustom(pIPalette, palette, num_palette);
708
709     return hr;
710 }
711
712 static HRESULT WINAPI PngDecoder_Frame_CopyPixels(IWICBitmapFrameDecode *iface,
713     const WICRect *prc, UINT cbStride, UINT cbBufferSize, BYTE *pbBuffer)
714 {
715     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
716     TRACE("(%p,%p,%u,%u,%p)\n", iface, prc, cbStride, cbBufferSize, pbBuffer);
717
718     return copy_pixels(This->bpp, This->image_bits,
719         This->width, This->height, This->stride,
720         prc, cbStride, cbBufferSize, pbBuffer);
721 }
722
723 static HRESULT WINAPI PngDecoder_Frame_GetMetadataQueryReader(IWICBitmapFrameDecode *iface,
724     IWICMetadataQueryReader **ppIMetadataQueryReader)
725 {
726     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
727     return E_NOTIMPL;
728 }
729
730 static HRESULT WINAPI PngDecoder_Frame_GetColorContexts(IWICBitmapFrameDecode *iface,
731     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
732 {
733     FIXME("(%p,%u,%p,%p): stub\n", iface, cCount, ppIColorContexts, pcActualCount);
734     return E_NOTIMPL;
735 }
736
737 static HRESULT WINAPI PngDecoder_Frame_GetThumbnail(IWICBitmapFrameDecode *iface,
738     IWICBitmapSource **ppIThumbnail)
739 {
740     FIXME("(%p,%p): stub\n", iface, ppIThumbnail);
741     return E_NOTIMPL;
742 }
743
744 static const IWICBitmapFrameDecodeVtbl PngDecoder_FrameVtbl = {
745     PngDecoder_Frame_QueryInterface,
746     PngDecoder_Frame_AddRef,
747     PngDecoder_Frame_Release,
748     PngDecoder_Frame_GetSize,
749     PngDecoder_Frame_GetPixelFormat,
750     PngDecoder_Frame_GetResolution,
751     PngDecoder_Frame_CopyPalette,
752     PngDecoder_Frame_CopyPixels,
753     PngDecoder_Frame_GetMetadataQueryReader,
754     PngDecoder_Frame_GetColorContexts,
755     PngDecoder_Frame_GetThumbnail
756 };
757
758 HRESULT PngDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
759 {
760     PngDecoder *This;
761     HRESULT ret;
762
763     TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);
764
765     *ppv = NULL;
766
767     if (pUnkOuter) return CLASS_E_NOAGGREGATION;
768
769     if (!libpng_handle && !load_libpng())
770     {
771         ERR("Failed reading PNG because unable to find %s\n",SONAME_LIBPNG);
772         return E_FAIL;
773     }
774
775     This = HeapAlloc(GetProcessHeap(), 0, sizeof(PngDecoder));
776     if (!This) return E_OUTOFMEMORY;
777
778     This->IWICBitmapDecoder_iface.lpVtbl = &PngDecoder_Vtbl;
779     This->IWICBitmapFrameDecode_iface.lpVtbl = &PngDecoder_FrameVtbl;
780     This->ref = 1;
781     This->png_ptr = NULL;
782     This->info_ptr = NULL;
783     This->initialized = FALSE;
784     This->image_bits = NULL;
785     InitializeCriticalSection(&This->lock);
786     This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": PngDecoder.lock");
787
788     ret = IUnknown_QueryInterface((IUnknown*)This, iid, ppv);
789     IUnknown_Release((IUnknown*)This);
790
791     return ret;
792 }
793
794 struct png_pixelformat {
795     const WICPixelFormatGUID *guid;
796     UINT bpp;
797     int bit_depth;
798     int color_type;
799     BOOL remove_filler;
800     BOOL swap_rgb;
801 };
802
803 static const struct png_pixelformat formats[] = {
804     {&GUID_WICPixelFormat24bppBGR, 24, 8, PNG_COLOR_TYPE_RGB, 0, 1},
805     {&GUID_WICPixelFormatBlackWhite, 1, 1, PNG_COLOR_TYPE_GRAY, 0, 0},
806     {&GUID_WICPixelFormat2bppGray, 2, 2, PNG_COLOR_TYPE_GRAY, 0, 0},
807     {&GUID_WICPixelFormat4bppGray, 4, 4, PNG_COLOR_TYPE_GRAY, 0, 0},
808     {&GUID_WICPixelFormat8bppGray, 8, 8, PNG_COLOR_TYPE_GRAY, 0, 0},
809     {&GUID_WICPixelFormat16bppGray, 16, 16, PNG_COLOR_TYPE_GRAY, 0, 0},
810     {&GUID_WICPixelFormat32bppBGR, 32, 8, PNG_COLOR_TYPE_RGB, 1, 1},
811     {&GUID_WICPixelFormat32bppBGRA, 32, 8, PNG_COLOR_TYPE_RGB_ALPHA, 0, 1},
812     {&GUID_WICPixelFormat48bppRGB, 48, 16, PNG_COLOR_TYPE_RGB, 0, 0},
813     {&GUID_WICPixelFormat64bppRGBA, 64, 16, PNG_COLOR_TYPE_RGB_ALPHA, 0, 0},
814     {NULL},
815 };
816
817 typedef struct PngEncoder {
818     IWICBitmapEncoder IWICBitmapEncoder_iface;
819     IWICBitmapFrameEncode IWICBitmapFrameEncode_iface;
820     LONG ref;
821     IStream *stream;
822     png_structp png_ptr;
823     png_infop info_ptr;
824     UINT frame_count;
825     BOOL frame_initialized;
826     const struct png_pixelformat *format;
827     BOOL info_written;
828     UINT width, height;
829     double xres, yres;
830     UINT lines_written;
831     BOOL frame_committed;
832     BOOL committed;
833     CRITICAL_SECTION lock;
834 } PngEncoder;
835
836 static inline PngEncoder *impl_from_IWICBitmapEncoder(IWICBitmapEncoder *iface)
837 {
838     return CONTAINING_RECORD(iface, PngEncoder, IWICBitmapEncoder_iface);
839 }
840
841 static inline PngEncoder *impl_from_IWICBitmapFrameEncode(IWICBitmapFrameEncode *iface)
842 {
843     return CONTAINING_RECORD(iface, PngEncoder, IWICBitmapFrameEncode_iface);
844 }
845
846 static HRESULT WINAPI PngFrameEncode_QueryInterface(IWICBitmapFrameEncode *iface, REFIID iid,
847     void **ppv)
848 {
849     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
850     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
851
852     if (!ppv) return E_INVALIDARG;
853
854     if (IsEqualIID(&IID_IUnknown, iid) ||
855         IsEqualIID(&IID_IWICBitmapFrameEncode, iid))
856     {
857         *ppv = &This->IWICBitmapFrameEncode_iface;
858     }
859     else
860     {
861         *ppv = NULL;
862         return E_NOINTERFACE;
863     }
864
865     IUnknown_AddRef((IUnknown*)*ppv);
866     return S_OK;
867 }
868
869 static ULONG WINAPI PngFrameEncode_AddRef(IWICBitmapFrameEncode *iface)
870 {
871     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
872     return IUnknown_AddRef((IUnknown*)This);
873 }
874
875 static ULONG WINAPI PngFrameEncode_Release(IWICBitmapFrameEncode *iface)
876 {
877     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
878     return IUnknown_Release((IUnknown*)This);
879 }
880
881 static HRESULT WINAPI PngFrameEncode_Initialize(IWICBitmapFrameEncode *iface,
882     IPropertyBag2 *pIEncoderOptions)
883 {
884     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
885     TRACE("(%p,%p)\n", iface, pIEncoderOptions);
886
887     EnterCriticalSection(&This->lock);
888
889     if (This->frame_initialized)
890     {
891         LeaveCriticalSection(&This->lock);
892         return WINCODEC_ERR_WRONGSTATE;
893     }
894
895     This->frame_initialized = TRUE;
896
897     LeaveCriticalSection(&This->lock);
898
899     return S_OK;
900 }
901
902 static HRESULT WINAPI PngFrameEncode_SetSize(IWICBitmapFrameEncode *iface,
903     UINT uiWidth, UINT uiHeight)
904 {
905     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
906     TRACE("(%p,%u,%u)\n", iface, uiWidth, uiHeight);
907
908     EnterCriticalSection(&This->lock);
909
910     if (!This->frame_initialized || This->info_written)
911     {
912         LeaveCriticalSection(&This->lock);
913         return WINCODEC_ERR_WRONGSTATE;
914     }
915
916     This->width = uiWidth;
917     This->height = uiHeight;
918
919     LeaveCriticalSection(&This->lock);
920
921     return S_OK;
922 }
923
924 static HRESULT WINAPI PngFrameEncode_SetResolution(IWICBitmapFrameEncode *iface,
925     double dpiX, double dpiY)
926 {
927     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
928     TRACE("(%p,%0.2f,%0.2f)\n", iface, dpiX, dpiY);
929
930     EnterCriticalSection(&This->lock);
931
932     if (!This->frame_initialized || This->info_written)
933     {
934         LeaveCriticalSection(&This->lock);
935         return WINCODEC_ERR_WRONGSTATE;
936     }
937
938     This->xres = dpiX;
939     This->yres = dpiY;
940
941     LeaveCriticalSection(&This->lock);
942
943     return S_OK;
944 }
945
946 static HRESULT WINAPI PngFrameEncode_SetPixelFormat(IWICBitmapFrameEncode *iface,
947     WICPixelFormatGUID *pPixelFormat)
948 {
949     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
950     int i;
951     TRACE("(%p,%s)\n", iface, debugstr_guid(pPixelFormat));
952
953     EnterCriticalSection(&This->lock);
954
955     if (!This->frame_initialized || This->info_written)
956     {
957         LeaveCriticalSection(&This->lock);
958         return WINCODEC_ERR_WRONGSTATE;
959     }
960
961     for (i=0; formats[i].guid; i++)
962     {
963         if (memcmp(formats[i].guid, pPixelFormat, sizeof(GUID)) == 0)
964             break;
965     }
966
967     if (!formats[i].guid) i = 0;
968
969     This->format = &formats[i];
970     memcpy(pPixelFormat, This->format->guid, sizeof(GUID));
971
972     LeaveCriticalSection(&This->lock);
973
974     return S_OK;
975 }
976
977 static HRESULT WINAPI PngFrameEncode_SetColorContexts(IWICBitmapFrameEncode *iface,
978     UINT cCount, IWICColorContext **ppIColorContext)
979 {
980     FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
981     return E_NOTIMPL;
982 }
983
984 static HRESULT WINAPI PngFrameEncode_SetPalette(IWICBitmapFrameEncode *iface,
985     IWICPalette *pIPalette)
986 {
987     FIXME("(%p,%p): stub\n", iface, pIPalette);
988     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
989 }
990
991 static HRESULT WINAPI PngFrameEncode_SetThumbnail(IWICBitmapFrameEncode *iface,
992     IWICBitmapSource *pIThumbnail)
993 {
994     FIXME("(%p,%p): stub\n", iface, pIThumbnail);
995     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
996 }
997
998 static HRESULT WINAPI PngFrameEncode_WritePixels(IWICBitmapFrameEncode *iface,
999     UINT lineCount, UINT cbStride, UINT cbBufferSize, BYTE *pbPixels)
1000 {
1001     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1002     png_byte **row_pointers=NULL;
1003     UINT i;
1004     jmp_buf jmpbuf;
1005     TRACE("(%p,%u,%u,%u,%p)\n", iface, lineCount, cbStride, cbBufferSize, pbPixels);
1006
1007     EnterCriticalSection(&This->lock);
1008
1009     if (!This->frame_initialized || !This->width || !This->height || !This->format)
1010     {
1011         LeaveCriticalSection(&This->lock);
1012         return WINCODEC_ERR_WRONGSTATE;
1013     }
1014
1015     if (lineCount == 0 || lineCount + This->lines_written > This->height)
1016     {
1017         LeaveCriticalSection(&This->lock);
1018         return E_INVALIDARG;
1019     }
1020
1021     /* set up setjmp/longjmp error handling */
1022     if (setjmp(jmpbuf))
1023     {
1024         LeaveCriticalSection(&This->lock);
1025         HeapFree(GetProcessHeap(), 0, row_pointers);
1026         return E_FAIL;
1027     }
1028     ppng_set_error_fn(This->png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
1029
1030     if (!This->info_written)
1031     {
1032         ppng_set_IHDR(This->png_ptr, This->info_ptr, This->width, This->height,
1033             This->format->bit_depth, This->format->color_type, PNG_INTERLACE_NONE,
1034             PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
1035
1036         if (This->xres != 0.0 && This->yres != 0.0)
1037         {
1038             ppng_set_pHYs(This->png_ptr, This->info_ptr, (This->xres+0.0127) / 0.0254,
1039                 (This->yres+0.0127) / 0.0254, PNG_RESOLUTION_METER);
1040         }
1041
1042         ppng_write_info(This->png_ptr, This->info_ptr);
1043
1044         if (This->format->remove_filler)
1045             ppng_set_filler(This->png_ptr, 0, PNG_FILLER_AFTER);
1046
1047         if (This->format->swap_rgb)
1048             ppng_set_bgr(This->png_ptr);
1049
1050         This->info_written = TRUE;
1051     }
1052
1053     row_pointers = HeapAlloc(GetProcessHeap(), 0, lineCount * sizeof(png_byte*));
1054     if (!row_pointers)
1055     {
1056         LeaveCriticalSection(&This->lock);
1057         return E_OUTOFMEMORY;
1058     }
1059
1060     for (i=0; i<lineCount; i++)
1061         row_pointers[i] = pbPixels + cbStride * i;
1062
1063     ppng_write_rows(This->png_ptr, row_pointers, lineCount);
1064     This->lines_written += lineCount;
1065
1066     LeaveCriticalSection(&This->lock);
1067
1068     HeapFree(GetProcessHeap(), 0, row_pointers);
1069
1070     return S_OK;
1071 }
1072
1073 static HRESULT WINAPI PngFrameEncode_WriteSource(IWICBitmapFrameEncode *iface,
1074     IWICBitmapSource *pIBitmapSource, WICRect *prc)
1075 {
1076     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1077     HRESULT hr;
1078     WICRect rc;
1079     WICPixelFormatGUID guid;
1080     UINT stride;
1081     BYTE *pixeldata;
1082     TRACE("(%p,%p,%p)\n", iface, pIBitmapSource, prc);
1083
1084     if (!This->frame_initialized || !This->width || !This->height)
1085         return WINCODEC_ERR_WRONGSTATE;
1086
1087     if (!This->format)
1088     {
1089         hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
1090         if (FAILED(hr)) return hr;
1091         hr = IWICBitmapFrameEncode_SetPixelFormat(iface, &guid);
1092         if (FAILED(hr)) return hr;
1093     }
1094
1095     hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
1096     if (FAILED(hr)) return hr;
1097     if (memcmp(&guid, This->format->guid, sizeof(GUID)) != 0)
1098     {
1099         /* FIXME: should use WICConvertBitmapSource to convert */
1100         ERR("format %s unsupported\n", debugstr_guid(&guid));
1101         return E_FAIL;
1102     }
1103
1104     if (This->xres == 0.0 || This->yres == 0.0)
1105     {
1106         double xres, yres;
1107         hr = IWICBitmapSource_GetResolution(pIBitmapSource, &xres, &yres);
1108         if (FAILED(hr)) return hr;
1109         hr = IWICBitmapFrameEncode_SetResolution(iface, xres, yres);
1110         if (FAILED(hr)) return hr;
1111     }
1112
1113     if (!prc)
1114     {
1115         UINT width, height;
1116         hr = IWICBitmapSource_GetSize(pIBitmapSource, &width, &height);
1117         if (FAILED(hr)) return hr;
1118         rc.X = 0;
1119         rc.Y = 0;
1120         rc.Width = width;
1121         rc.Height = height;
1122         prc = &rc;
1123     }
1124
1125     if (prc->Width != This->width) return E_INVALIDARG;
1126
1127     stride = (This->format->bpp * This->width + 7)/8;
1128
1129     pixeldata = HeapAlloc(GetProcessHeap(), 0, stride * prc->Height);
1130     if (!pixeldata) return E_OUTOFMEMORY;
1131
1132     hr = IWICBitmapSource_CopyPixels(pIBitmapSource, prc, stride,
1133         stride*prc->Height, pixeldata);
1134
1135     if (SUCCEEDED(hr))
1136     {
1137         hr = IWICBitmapFrameEncode_WritePixels(iface, prc->Height, stride,
1138             stride*prc->Height, pixeldata);
1139     }
1140
1141     HeapFree(GetProcessHeap(), 0, pixeldata);
1142
1143     return hr;
1144 }
1145
1146 static HRESULT WINAPI PngFrameEncode_Commit(IWICBitmapFrameEncode *iface)
1147 {
1148     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1149     jmp_buf jmpbuf;
1150     TRACE("(%p)\n", iface);
1151
1152     EnterCriticalSection(&This->lock);
1153
1154     if (!This->info_written || This->lines_written != This->height || This->frame_committed)
1155     {
1156         LeaveCriticalSection(&This->lock);
1157         return WINCODEC_ERR_WRONGSTATE;
1158     }
1159
1160     /* set up setjmp/longjmp error handling */
1161     if (setjmp(jmpbuf))
1162     {
1163         LeaveCriticalSection(&This->lock);
1164         return E_FAIL;
1165     }
1166     ppng_set_error_fn(This->png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
1167
1168     ppng_write_end(This->png_ptr, This->info_ptr);
1169
1170     This->frame_committed = TRUE;
1171
1172     LeaveCriticalSection(&This->lock);
1173
1174     return S_OK;
1175 }
1176
1177 static HRESULT WINAPI PngFrameEncode_GetMetadataQueryWriter(IWICBitmapFrameEncode *iface,
1178     IWICMetadataQueryWriter **ppIMetadataQueryWriter)
1179 {
1180     FIXME("(%p, %p): stub\n", iface, ppIMetadataQueryWriter);
1181     return E_NOTIMPL;
1182 }
1183
1184 static const IWICBitmapFrameEncodeVtbl PngEncoder_FrameVtbl = {
1185     PngFrameEncode_QueryInterface,
1186     PngFrameEncode_AddRef,
1187     PngFrameEncode_Release,
1188     PngFrameEncode_Initialize,
1189     PngFrameEncode_SetSize,
1190     PngFrameEncode_SetResolution,
1191     PngFrameEncode_SetPixelFormat,
1192     PngFrameEncode_SetColorContexts,
1193     PngFrameEncode_SetPalette,
1194     PngFrameEncode_SetThumbnail,
1195     PngFrameEncode_WritePixels,
1196     PngFrameEncode_WriteSource,
1197     PngFrameEncode_Commit,
1198     PngFrameEncode_GetMetadataQueryWriter
1199 };
1200
1201 static HRESULT WINAPI PngEncoder_QueryInterface(IWICBitmapEncoder *iface, REFIID iid,
1202     void **ppv)
1203 {
1204     PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1205     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
1206
1207     if (!ppv) return E_INVALIDARG;
1208
1209     if (IsEqualIID(&IID_IUnknown, iid) ||
1210         IsEqualIID(&IID_IWICBitmapEncoder, iid))
1211     {
1212         *ppv = This;
1213     }
1214     else
1215     {
1216         *ppv = NULL;
1217         return E_NOINTERFACE;
1218     }
1219
1220     IUnknown_AddRef((IUnknown*)*ppv);
1221     return S_OK;
1222 }
1223
1224 static ULONG WINAPI PngEncoder_AddRef(IWICBitmapEncoder *iface)
1225 {
1226     PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1227     ULONG ref = InterlockedIncrement(&This->ref);
1228
1229     TRACE("(%p) refcount=%u\n", iface, ref);
1230
1231     return ref;
1232 }
1233
1234 static ULONG WINAPI PngEncoder_Release(IWICBitmapEncoder *iface)
1235 {
1236     PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1237     ULONG ref = InterlockedDecrement(&This->ref);
1238
1239     TRACE("(%p) refcount=%u\n", iface, ref);
1240
1241     if (ref == 0)
1242     {
1243         This->lock.DebugInfo->Spare[0] = 0;
1244         DeleteCriticalSection(&This->lock);
1245         if (This->png_ptr)
1246             ppng_destroy_write_struct(&This->png_ptr, &This->info_ptr);
1247         if (This->stream)
1248             IStream_Release(This->stream);
1249         HeapFree(GetProcessHeap(), 0, This);
1250     }
1251
1252     return ref;
1253 }
1254
1255 static void user_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
1256 {
1257     PngEncoder *This = ppng_get_io_ptr(png_ptr);
1258     HRESULT hr;
1259     ULONG byteswritten;
1260
1261     hr = IStream_Write(This->stream, data, length, &byteswritten);
1262     if (FAILED(hr) || byteswritten != length)
1263     {
1264         ppng_error(png_ptr, "failed writing data");
1265     }
1266 }
1267
1268 static void user_flush(png_structp png_ptr)
1269 {
1270 }
1271
1272 static HRESULT WINAPI PngEncoder_Initialize(IWICBitmapEncoder *iface,
1273     IStream *pIStream, WICBitmapEncoderCacheOption cacheOption)
1274 {
1275     PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1276     jmp_buf jmpbuf;
1277
1278     TRACE("(%p,%p,%u)\n", iface, pIStream, cacheOption);
1279
1280     EnterCriticalSection(&This->lock);
1281
1282     if (This->png_ptr)
1283     {
1284         LeaveCriticalSection(&This->lock);
1285         return WINCODEC_ERR_WRONGSTATE;
1286     }
1287
1288     /* initialize libpng */
1289     This->png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1290     if (!This->png_ptr)
1291     {
1292         LeaveCriticalSection(&This->lock);
1293         return E_FAIL;
1294     }
1295
1296     This->info_ptr = ppng_create_info_struct(This->png_ptr);
1297     if (!This->info_ptr)
1298     {
1299         ppng_destroy_write_struct(&This->png_ptr, NULL);
1300         This->png_ptr = NULL;
1301         LeaveCriticalSection(&This->lock);
1302         return E_FAIL;
1303     }
1304
1305     IStream_AddRef(pIStream);
1306     This->stream = pIStream;
1307
1308     /* set up setjmp/longjmp error handling */
1309     if (setjmp(jmpbuf))
1310     {
1311         ppng_destroy_write_struct(&This->png_ptr, &This->info_ptr);
1312         This->png_ptr = NULL;
1313         IStream_Release(This->stream);
1314         This->stream = NULL;
1315         LeaveCriticalSection(&This->lock);
1316         return E_FAIL;
1317     }
1318     ppng_set_error_fn(This->png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
1319
1320     /* set up custom i/o handling */
1321     ppng_set_write_fn(This->png_ptr, This, user_write_data, user_flush);
1322
1323     LeaveCriticalSection(&This->lock);
1324
1325     return S_OK;
1326 }
1327
1328 static HRESULT WINAPI PngEncoder_GetContainerFormat(IWICBitmapEncoder *iface,
1329     GUID *pguidContainerFormat)
1330 {
1331     FIXME("(%p,%s): stub\n", iface, debugstr_guid(pguidContainerFormat));
1332     return E_NOTIMPL;
1333 }
1334
1335 static HRESULT WINAPI PngEncoder_GetEncoderInfo(IWICBitmapEncoder *iface,
1336     IWICBitmapEncoderInfo **ppIEncoderInfo)
1337 {
1338     FIXME("(%p,%p): stub\n", iface, ppIEncoderInfo);
1339     return E_NOTIMPL;
1340 }
1341
1342 static HRESULT WINAPI PngEncoder_SetColorContexts(IWICBitmapEncoder *iface,
1343     UINT cCount, IWICColorContext **ppIColorContext)
1344 {
1345     FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
1346     return E_NOTIMPL;
1347 }
1348
1349 static HRESULT WINAPI PngEncoder_SetPalette(IWICBitmapEncoder *iface, IWICPalette *pIPalette)
1350 {
1351     TRACE("(%p,%p)\n", iface, pIPalette);
1352     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1353 }
1354
1355 static HRESULT WINAPI PngEncoder_SetThumbnail(IWICBitmapEncoder *iface, IWICBitmapSource *pIThumbnail)
1356 {
1357     TRACE("(%p,%p)\n", iface, pIThumbnail);
1358     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1359 }
1360
1361 static HRESULT WINAPI PngEncoder_SetPreview(IWICBitmapEncoder *iface, IWICBitmapSource *pIPreview)
1362 {
1363     TRACE("(%p,%p)\n", iface, pIPreview);
1364     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1365 }
1366
1367 static HRESULT WINAPI PngEncoder_CreateNewFrame(IWICBitmapEncoder *iface,
1368     IWICBitmapFrameEncode **ppIFrameEncode, IPropertyBag2 **ppIEncoderOptions)
1369 {
1370     PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1371     HRESULT hr;
1372     TRACE("(%p,%p,%p)\n", iface, ppIFrameEncode, ppIEncoderOptions);
1373
1374     EnterCriticalSection(&This->lock);
1375
1376     if (This->frame_count != 0)
1377     {
1378         LeaveCriticalSection(&This->lock);
1379         return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1380     }
1381
1382     if (!This->stream)
1383     {
1384         LeaveCriticalSection(&This->lock);
1385         return WINCODEC_ERR_NOTINITIALIZED;
1386     }
1387
1388     hr = CreatePropertyBag2(ppIEncoderOptions);
1389     if (FAILED(hr))
1390     {
1391         LeaveCriticalSection(&This->lock);
1392         return hr;
1393     }
1394
1395     This->frame_count = 1;
1396
1397     LeaveCriticalSection(&This->lock);
1398
1399     IWICBitmapEncoder_AddRef(iface);
1400     *ppIFrameEncode = &This->IWICBitmapFrameEncode_iface;
1401
1402     return S_OK;
1403 }
1404
1405 static HRESULT WINAPI PngEncoder_Commit(IWICBitmapEncoder *iface)
1406 {
1407     PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1408     TRACE("(%p)\n", iface);
1409
1410     EnterCriticalSection(&This->lock);
1411
1412     if (!This->frame_committed || This->committed)
1413     {
1414         LeaveCriticalSection(&This->lock);
1415         return WINCODEC_ERR_WRONGSTATE;
1416     }
1417
1418     This->committed = TRUE;
1419
1420     LeaveCriticalSection(&This->lock);
1421
1422     return S_OK;
1423 }
1424
1425 static HRESULT WINAPI PngEncoder_GetMetadataQueryWriter(IWICBitmapEncoder *iface,
1426     IWICMetadataQueryWriter **ppIMetadataQueryWriter)
1427 {
1428     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryWriter);
1429     return E_NOTIMPL;
1430 }
1431
1432 static const IWICBitmapEncoderVtbl PngEncoder_Vtbl = {
1433     PngEncoder_QueryInterface,
1434     PngEncoder_AddRef,
1435     PngEncoder_Release,
1436     PngEncoder_Initialize,
1437     PngEncoder_GetContainerFormat,
1438     PngEncoder_GetEncoderInfo,
1439     PngEncoder_SetColorContexts,
1440     PngEncoder_SetPalette,
1441     PngEncoder_SetThumbnail,
1442     PngEncoder_SetPreview,
1443     PngEncoder_CreateNewFrame,
1444     PngEncoder_Commit,
1445     PngEncoder_GetMetadataQueryWriter
1446 };
1447
1448 HRESULT PngEncoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
1449 {
1450     PngEncoder *This;
1451     HRESULT ret;
1452
1453     TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);
1454
1455     *ppv = NULL;
1456
1457     if (pUnkOuter) return CLASS_E_NOAGGREGATION;
1458
1459     if (!libpng_handle && !load_libpng())
1460     {
1461         ERR("Failed writing PNG because unable to find %s\n",SONAME_LIBPNG);
1462         return E_FAIL;
1463     }
1464
1465     This = HeapAlloc(GetProcessHeap(), 0, sizeof(PngEncoder));
1466     if (!This) return E_OUTOFMEMORY;
1467
1468     This->IWICBitmapEncoder_iface.lpVtbl = &PngEncoder_Vtbl;
1469     This->IWICBitmapFrameEncode_iface.lpVtbl = &PngEncoder_FrameVtbl;
1470     This->ref = 1;
1471     This->png_ptr = NULL;
1472     This->info_ptr = NULL;
1473     This->stream = NULL;
1474     This->frame_count = 0;
1475     This->frame_initialized = FALSE;
1476     This->format = NULL;
1477     This->info_written = FALSE;
1478     This->width = 0;
1479     This->height = 0;
1480     This->xres = 0.0;
1481     This->yres = 0.0;
1482     This->lines_written = 0;
1483     This->frame_committed = FALSE;
1484     This->committed = FALSE;
1485     InitializeCriticalSection(&This->lock);
1486     This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": PngEncoder.lock");
1487
1488     ret = IUnknown_QueryInterface((IUnknown*)This, iid, ppv);
1489     IUnknown_Release((IUnknown*)This);
1490
1491     return ret;
1492 }
1493
1494 #else /* !HAVE_PNG_H */
1495
1496 HRESULT PngDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
1497 {
1498     ERR("Trying to load PNG picture, but PNG support is not compiled in.\n");
1499     return E_FAIL;
1500 }
1501
1502 HRESULT PngEncoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
1503 {
1504     ERR("Trying to save PNG picture, but PNG support is not compiled in.\n");
1505     return E_FAIL;
1506 }
1507
1508 #endif