wined3d: Rename IWineD3DDeviceImpl_FindTexUnitMap() to device_update_tex_unit_map().
[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     FIXME("(%p,%p): stub\n", iface, ppIDecoderInfo);
479     return E_NOTIMPL;
480 }
481
482 static HRESULT WINAPI PngDecoder_CopyPalette(IWICBitmapDecoder *iface,
483     IWICPalette *pIPalette)
484 {
485     FIXME("(%p,%p): stub\n", iface, pIPalette);
486     return E_NOTIMPL;
487 }
488
489 static HRESULT WINAPI PngDecoder_GetMetadataQueryReader(IWICBitmapDecoder *iface,
490     IWICMetadataQueryReader **ppIMetadataQueryReader)
491 {
492     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
493     return E_NOTIMPL;
494 }
495
496 static HRESULT WINAPI PngDecoder_GetPreview(IWICBitmapDecoder *iface,
497     IWICBitmapSource **ppIBitmapSource)
498 {
499     FIXME("(%p,%p): stub\n", iface, ppIBitmapSource);
500     return E_NOTIMPL;
501 }
502
503 static HRESULT WINAPI PngDecoder_GetColorContexts(IWICBitmapDecoder *iface,
504     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
505 {
506     FIXME("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);
507     return E_NOTIMPL;
508 }
509
510 static HRESULT WINAPI PngDecoder_GetThumbnail(IWICBitmapDecoder *iface,
511     IWICBitmapSource **ppIThumbnail)
512 {
513     TRACE("(%p,%p)\n", iface, ppIThumbnail);
514     return WINCODEC_ERR_CODECNOTHUMBNAIL;
515 }
516
517 static HRESULT WINAPI PngDecoder_GetFrameCount(IWICBitmapDecoder *iface,
518     UINT *pCount)
519 {
520     *pCount = 1;
521     return S_OK;
522 }
523
524 static HRESULT WINAPI PngDecoder_GetFrame(IWICBitmapDecoder *iface,
525     UINT index, IWICBitmapFrameDecode **ppIBitmapFrame)
526 {
527     PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
528     TRACE("(%p,%u,%p)\n", iface, index, ppIBitmapFrame);
529
530     if (!This->initialized) return WINCODEC_ERR_NOTINITIALIZED;
531
532     if (index != 0) return E_INVALIDARG;
533
534     IWICBitmapDecoder_AddRef(iface);
535
536     *ppIBitmapFrame = &This->IWICBitmapFrameDecode_iface;
537
538     return S_OK;
539 }
540
541 static const IWICBitmapDecoderVtbl PngDecoder_Vtbl = {
542     PngDecoder_QueryInterface,
543     PngDecoder_AddRef,
544     PngDecoder_Release,
545     PngDecoder_QueryCapability,
546     PngDecoder_Initialize,
547     PngDecoder_GetContainerFormat,
548     PngDecoder_GetDecoderInfo,
549     PngDecoder_CopyPalette,
550     PngDecoder_GetMetadataQueryReader,
551     PngDecoder_GetPreview,
552     PngDecoder_GetColorContexts,
553     PngDecoder_GetThumbnail,
554     PngDecoder_GetFrameCount,
555     PngDecoder_GetFrame
556 };
557
558 static HRESULT WINAPI PngDecoder_Frame_QueryInterface(IWICBitmapFrameDecode *iface, REFIID iid,
559     void **ppv)
560 {
561     if (!ppv) return E_INVALIDARG;
562
563     if (IsEqualIID(&IID_IUnknown, iid) ||
564         IsEqualIID(&IID_IWICBitmapSource, iid) ||
565         IsEqualIID(&IID_IWICBitmapFrameDecode, iid))
566     {
567         *ppv = iface;
568     }
569     else
570     {
571         *ppv = NULL;
572         return E_NOINTERFACE;
573     }
574
575     IUnknown_AddRef((IUnknown*)*ppv);
576     return S_OK;
577 }
578
579 static ULONG WINAPI PngDecoder_Frame_AddRef(IWICBitmapFrameDecode *iface)
580 {
581     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
582     return IUnknown_AddRef((IUnknown*)This);
583 }
584
585 static ULONG WINAPI PngDecoder_Frame_Release(IWICBitmapFrameDecode *iface)
586 {
587     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
588     return IUnknown_Release((IUnknown*)This);
589 }
590
591 static HRESULT WINAPI PngDecoder_Frame_GetSize(IWICBitmapFrameDecode *iface,
592     UINT *puiWidth, UINT *puiHeight)
593 {
594     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
595     *puiWidth = This->width;
596     *puiHeight = This->height;
597     TRACE("(%p)->(%u,%u)\n", iface, *puiWidth, *puiHeight);
598     return S_OK;
599 }
600
601 static HRESULT WINAPI PngDecoder_Frame_GetPixelFormat(IWICBitmapFrameDecode *iface,
602     WICPixelFormatGUID *pPixelFormat)
603 {
604     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
605     TRACE("(%p,%p)\n", iface, pPixelFormat);
606
607     memcpy(pPixelFormat, This->format, sizeof(GUID));
608
609     return S_OK;
610 }
611
612 static HRESULT WINAPI PngDecoder_Frame_GetResolution(IWICBitmapFrameDecode *iface,
613     double *pDpiX, double *pDpiY)
614 {
615     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
616     png_uint_32 ret, xres, yres;
617     int unit_type;
618
619     EnterCriticalSection(&This->lock);
620
621     ret = ppng_get_pHYs(This->png_ptr, This->info_ptr, &xres, &yres, &unit_type);
622
623     if (ret && unit_type == PNG_RESOLUTION_METER)
624     {
625         *pDpiX = xres * 0.0254;
626         *pDpiY = yres * 0.0254;
627     }
628     else
629     {
630         WARN("no pHYs block present\n");
631         *pDpiX = *pDpiY = 96.0;
632     }
633
634     LeaveCriticalSection(&This->lock);
635
636     TRACE("(%p)->(%0.2f,%0.2f)\n", iface, *pDpiX, *pDpiY);
637
638     return S_OK;
639 }
640
641 static HRESULT WINAPI PngDecoder_Frame_CopyPalette(IWICBitmapFrameDecode *iface,
642     IWICPalette *pIPalette)
643 {
644     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
645     png_uint_32 ret;
646     png_colorp png_palette;
647     int num_palette;
648     WICColor palette[256];
649     png_bytep trans;
650     int num_trans;
651     png_color_16p trans_values;
652     int i;
653     HRESULT hr=S_OK;
654
655     TRACE("(%p,%p)\n", iface, pIPalette);
656
657     EnterCriticalSection(&This->lock);
658
659     ret = ppng_get_PLTE(This->png_ptr, This->info_ptr, &png_palette, &num_palette);
660     if (!ret)
661     {
662         hr = WINCODEC_ERR_PALETTEUNAVAILABLE;
663         goto end;
664     }
665
666     if (num_palette > 256)
667     {
668         ERR("palette has %i colors?!\n", num_palette);
669         hr = E_FAIL;
670         goto end;
671     }
672
673     for (i=0; i<num_palette; i++)
674     {
675         palette[i] = (0xff000000|
676                       png_palette[i].red << 16|
677                       png_palette[i].green << 8|
678                       png_palette[i].blue);
679     }
680
681     ret = ppng_get_tRNS(This->png_ptr, This->info_ptr, &trans, &num_trans, &trans_values);
682     if (ret)
683     {
684         for (i=0; i<num_trans; i++)
685         {
686             palette[trans[i]] = 0x00000000;
687         }
688     }
689
690 end:
691
692     LeaveCriticalSection(&This->lock);
693
694     if (SUCCEEDED(hr))
695         hr = IWICPalette_InitializeCustom(pIPalette, palette, num_palette);
696
697     return hr;
698 }
699
700 static HRESULT WINAPI PngDecoder_Frame_CopyPixels(IWICBitmapFrameDecode *iface,
701     const WICRect *prc, UINT cbStride, UINT cbBufferSize, BYTE *pbBuffer)
702 {
703     PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
704     TRACE("(%p,%p,%u,%u,%p)\n", iface, prc, cbStride, cbBufferSize, pbBuffer);
705
706     return copy_pixels(This->bpp, This->image_bits,
707         This->width, This->height, This->stride,
708         prc, cbStride, cbBufferSize, pbBuffer);
709 }
710
711 static HRESULT WINAPI PngDecoder_Frame_GetMetadataQueryReader(IWICBitmapFrameDecode *iface,
712     IWICMetadataQueryReader **ppIMetadataQueryReader)
713 {
714     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
715     return E_NOTIMPL;
716 }
717
718 static HRESULT WINAPI PngDecoder_Frame_GetColorContexts(IWICBitmapFrameDecode *iface,
719     UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
720 {
721     FIXME("(%p,%u,%p,%p): stub\n", iface, cCount, ppIColorContexts, pcActualCount);
722     return E_NOTIMPL;
723 }
724
725 static HRESULT WINAPI PngDecoder_Frame_GetThumbnail(IWICBitmapFrameDecode *iface,
726     IWICBitmapSource **ppIThumbnail)
727 {
728     FIXME("(%p,%p): stub\n", iface, ppIThumbnail);
729     return E_NOTIMPL;
730 }
731
732 static const IWICBitmapFrameDecodeVtbl PngDecoder_FrameVtbl = {
733     PngDecoder_Frame_QueryInterface,
734     PngDecoder_Frame_AddRef,
735     PngDecoder_Frame_Release,
736     PngDecoder_Frame_GetSize,
737     PngDecoder_Frame_GetPixelFormat,
738     PngDecoder_Frame_GetResolution,
739     PngDecoder_Frame_CopyPalette,
740     PngDecoder_Frame_CopyPixels,
741     PngDecoder_Frame_GetMetadataQueryReader,
742     PngDecoder_Frame_GetColorContexts,
743     PngDecoder_Frame_GetThumbnail
744 };
745
746 HRESULT PngDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
747 {
748     PngDecoder *This;
749     HRESULT ret;
750
751     TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);
752
753     *ppv = NULL;
754
755     if (pUnkOuter) return CLASS_E_NOAGGREGATION;
756
757     if (!libpng_handle && !load_libpng())
758     {
759         ERR("Failed reading PNG because unable to find %s\n",SONAME_LIBPNG);
760         return E_FAIL;
761     }
762
763     This = HeapAlloc(GetProcessHeap(), 0, sizeof(PngDecoder));
764     if (!This) return E_OUTOFMEMORY;
765
766     This->IWICBitmapDecoder_iface.lpVtbl = &PngDecoder_Vtbl;
767     This->IWICBitmapFrameDecode_iface.lpVtbl = &PngDecoder_FrameVtbl;
768     This->ref = 1;
769     This->png_ptr = NULL;
770     This->info_ptr = NULL;
771     This->initialized = FALSE;
772     This->image_bits = NULL;
773     InitializeCriticalSection(&This->lock);
774     This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": PngDecoder.lock");
775
776     ret = IUnknown_QueryInterface((IUnknown*)This, iid, ppv);
777     IUnknown_Release((IUnknown*)This);
778
779     return ret;
780 }
781
782 struct png_pixelformat {
783     const WICPixelFormatGUID *guid;
784     UINT bpp;
785     int bit_depth;
786     int color_type;
787     BOOL remove_filler;
788     BOOL swap_rgb;
789 };
790
791 static const struct png_pixelformat formats[] = {
792     {&GUID_WICPixelFormat24bppBGR, 24, 8, PNG_COLOR_TYPE_RGB, 0, 1},
793     {&GUID_WICPixelFormatBlackWhite, 1, 1, PNG_COLOR_TYPE_GRAY, 0, 0},
794     {&GUID_WICPixelFormat2bppGray, 2, 2, PNG_COLOR_TYPE_GRAY, 0, 0},
795     {&GUID_WICPixelFormat4bppGray, 4, 4, PNG_COLOR_TYPE_GRAY, 0, 0},
796     {&GUID_WICPixelFormat8bppGray, 8, 8, PNG_COLOR_TYPE_GRAY, 0, 0},
797     {&GUID_WICPixelFormat16bppGray, 16, 16, PNG_COLOR_TYPE_GRAY, 0, 0},
798     {&GUID_WICPixelFormat32bppBGR, 32, 8, PNG_COLOR_TYPE_RGB, 1, 1},
799     {&GUID_WICPixelFormat32bppBGRA, 32, 8, PNG_COLOR_TYPE_RGB_ALPHA, 0, 1},
800     {&GUID_WICPixelFormat48bppRGB, 48, 16, PNG_COLOR_TYPE_RGB, 0, 0},
801     {&GUID_WICPixelFormat64bppRGBA, 64, 16, PNG_COLOR_TYPE_RGB_ALPHA, 0, 0},
802     {NULL},
803 };
804
805 typedef struct PngEncoder {
806     IWICBitmapEncoder IWICBitmapEncoder_iface;
807     IWICBitmapFrameEncode IWICBitmapFrameEncode_iface;
808     LONG ref;
809     IStream *stream;
810     png_structp png_ptr;
811     png_infop info_ptr;
812     UINT frame_count;
813     BOOL frame_initialized;
814     const struct png_pixelformat *format;
815     BOOL info_written;
816     UINT width, height;
817     double xres, yres;
818     UINT lines_written;
819     BOOL frame_committed;
820     BOOL committed;
821     CRITICAL_SECTION lock;
822 } PngEncoder;
823
824 static inline PngEncoder *impl_from_IWICBitmapEncoder(IWICBitmapEncoder *iface)
825 {
826     return CONTAINING_RECORD(iface, PngEncoder, IWICBitmapEncoder_iface);
827 }
828
829 static inline PngEncoder *impl_from_IWICBitmapFrameEncode(IWICBitmapFrameEncode *iface)
830 {
831     return CONTAINING_RECORD(iface, PngEncoder, IWICBitmapFrameEncode_iface);
832 }
833
834 static HRESULT WINAPI PngFrameEncode_QueryInterface(IWICBitmapFrameEncode *iface, REFIID iid,
835     void **ppv)
836 {
837     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
838     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
839
840     if (!ppv) return E_INVALIDARG;
841
842     if (IsEqualIID(&IID_IUnknown, iid) ||
843         IsEqualIID(&IID_IWICBitmapFrameEncode, iid))
844     {
845         *ppv = &This->IWICBitmapFrameEncode_iface;
846     }
847     else
848     {
849         *ppv = NULL;
850         return E_NOINTERFACE;
851     }
852
853     IUnknown_AddRef((IUnknown*)*ppv);
854     return S_OK;
855 }
856
857 static ULONG WINAPI PngFrameEncode_AddRef(IWICBitmapFrameEncode *iface)
858 {
859     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
860     return IUnknown_AddRef((IUnknown*)This);
861 }
862
863 static ULONG WINAPI PngFrameEncode_Release(IWICBitmapFrameEncode *iface)
864 {
865     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
866     return IUnknown_Release((IUnknown*)This);
867 }
868
869 static HRESULT WINAPI PngFrameEncode_Initialize(IWICBitmapFrameEncode *iface,
870     IPropertyBag2 *pIEncoderOptions)
871 {
872     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
873     TRACE("(%p,%p)\n", iface, pIEncoderOptions);
874
875     EnterCriticalSection(&This->lock);
876
877     if (This->frame_initialized)
878     {
879         LeaveCriticalSection(&This->lock);
880         return WINCODEC_ERR_WRONGSTATE;
881     }
882
883     This->frame_initialized = TRUE;
884
885     LeaveCriticalSection(&This->lock);
886
887     return S_OK;
888 }
889
890 static HRESULT WINAPI PngFrameEncode_SetSize(IWICBitmapFrameEncode *iface,
891     UINT uiWidth, UINT uiHeight)
892 {
893     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
894     TRACE("(%p,%u,%u)\n", iface, uiWidth, uiHeight);
895
896     EnterCriticalSection(&This->lock);
897
898     if (!This->frame_initialized || This->info_written)
899     {
900         LeaveCriticalSection(&This->lock);
901         return WINCODEC_ERR_WRONGSTATE;
902     }
903
904     This->width = uiWidth;
905     This->height = uiHeight;
906
907     LeaveCriticalSection(&This->lock);
908
909     return S_OK;
910 }
911
912 static HRESULT WINAPI PngFrameEncode_SetResolution(IWICBitmapFrameEncode *iface,
913     double dpiX, double dpiY)
914 {
915     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
916     TRACE("(%p,%0.2f,%0.2f)\n", iface, dpiX, dpiY);
917
918     EnterCriticalSection(&This->lock);
919
920     if (!This->frame_initialized || This->info_written)
921     {
922         LeaveCriticalSection(&This->lock);
923         return WINCODEC_ERR_WRONGSTATE;
924     }
925
926     This->xres = dpiX;
927     This->yres = dpiY;
928
929     LeaveCriticalSection(&This->lock);
930
931     return S_OK;
932 }
933
934 static HRESULT WINAPI PngFrameEncode_SetPixelFormat(IWICBitmapFrameEncode *iface,
935     WICPixelFormatGUID *pPixelFormat)
936 {
937     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
938     int i;
939     TRACE("(%p,%s)\n", iface, debugstr_guid(pPixelFormat));
940
941     EnterCriticalSection(&This->lock);
942
943     if (!This->frame_initialized || This->info_written)
944     {
945         LeaveCriticalSection(&This->lock);
946         return WINCODEC_ERR_WRONGSTATE;
947     }
948
949     for (i=0; formats[i].guid; i++)
950     {
951         if (memcmp(formats[i].guid, pPixelFormat, sizeof(GUID)) == 0)
952             break;
953     }
954
955     if (!formats[i].guid) i = 0;
956
957     This->format = &formats[i];
958     memcpy(pPixelFormat, This->format->guid, sizeof(GUID));
959
960     LeaveCriticalSection(&This->lock);
961
962     return S_OK;
963 }
964
965 static HRESULT WINAPI PngFrameEncode_SetColorContexts(IWICBitmapFrameEncode *iface,
966     UINT cCount, IWICColorContext **ppIColorContext)
967 {
968     FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
969     return E_NOTIMPL;
970 }
971
972 static HRESULT WINAPI PngFrameEncode_SetPalette(IWICBitmapFrameEncode *iface,
973     IWICPalette *pIPalette)
974 {
975     FIXME("(%p,%p): stub\n", iface, pIPalette);
976     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
977 }
978
979 static HRESULT WINAPI PngFrameEncode_SetThumbnail(IWICBitmapFrameEncode *iface,
980     IWICBitmapSource *pIThumbnail)
981 {
982     FIXME("(%p,%p): stub\n", iface, pIThumbnail);
983     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
984 }
985
986 static HRESULT WINAPI PngFrameEncode_WritePixels(IWICBitmapFrameEncode *iface,
987     UINT lineCount, UINT cbStride, UINT cbBufferSize, BYTE *pbPixels)
988 {
989     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
990     png_byte **row_pointers=NULL;
991     UINT i;
992     jmp_buf jmpbuf;
993     TRACE("(%p,%u,%u,%u,%p)\n", iface, lineCount, cbStride, cbBufferSize, pbPixels);
994
995     EnterCriticalSection(&This->lock);
996
997     if (!This->frame_initialized || !This->width || !This->height || !This->format)
998     {
999         LeaveCriticalSection(&This->lock);
1000         return WINCODEC_ERR_WRONGSTATE;
1001     }
1002
1003     if (lineCount == 0 || lineCount + This->lines_written > This->height)
1004     {
1005         LeaveCriticalSection(&This->lock);
1006         return E_INVALIDARG;
1007     }
1008
1009     /* set up setjmp/longjmp error handling */
1010     if (setjmp(jmpbuf))
1011     {
1012         LeaveCriticalSection(&This->lock);
1013         HeapFree(GetProcessHeap(), 0, row_pointers);
1014         return E_FAIL;
1015     }
1016     ppng_set_error_fn(This->png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
1017
1018     if (!This->info_written)
1019     {
1020         ppng_set_IHDR(This->png_ptr, This->info_ptr, This->width, This->height,
1021             This->format->bit_depth, This->format->color_type, PNG_INTERLACE_NONE,
1022             PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
1023
1024         if (This->xres != 0.0 && This->yres != 0.0)
1025         {
1026             ppng_set_pHYs(This->png_ptr, This->info_ptr, (This->xres+0.0127) / 0.0254,
1027                 (This->yres+0.0127) / 0.0254, PNG_RESOLUTION_METER);
1028         }
1029
1030         ppng_write_info(This->png_ptr, This->info_ptr);
1031
1032         if (This->format->remove_filler)
1033             ppng_set_filler(This->png_ptr, 0, PNG_FILLER_AFTER);
1034
1035         if (This->format->swap_rgb)
1036             ppng_set_bgr(This->png_ptr);
1037
1038         This->info_written = TRUE;
1039     }
1040
1041     row_pointers = HeapAlloc(GetProcessHeap(), 0, lineCount * sizeof(png_byte*));
1042     if (!row_pointers)
1043     {
1044         LeaveCriticalSection(&This->lock);
1045         return E_OUTOFMEMORY;
1046     }
1047
1048     for (i=0; i<lineCount; i++)
1049         row_pointers[i] = pbPixels + cbStride * i;
1050
1051     ppng_write_rows(This->png_ptr, row_pointers, lineCount);
1052     This->lines_written += lineCount;
1053
1054     LeaveCriticalSection(&This->lock);
1055
1056     HeapFree(GetProcessHeap(), 0, row_pointers);
1057
1058     return S_OK;
1059 }
1060
1061 static HRESULT WINAPI PngFrameEncode_WriteSource(IWICBitmapFrameEncode *iface,
1062     IWICBitmapSource *pIBitmapSource, WICRect *prc)
1063 {
1064     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1065     HRESULT hr;
1066     WICRect rc;
1067     WICPixelFormatGUID guid;
1068     UINT stride;
1069     BYTE *pixeldata;
1070     TRACE("(%p,%p,%p)\n", iface, pIBitmapSource, prc);
1071
1072     if (!This->frame_initialized || !This->width || !This->height)
1073         return WINCODEC_ERR_WRONGSTATE;
1074
1075     if (!This->format)
1076     {
1077         hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
1078         if (FAILED(hr)) return hr;
1079         hr = IWICBitmapFrameEncode_SetPixelFormat(iface, &guid);
1080         if (FAILED(hr)) return hr;
1081     }
1082
1083     hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
1084     if (FAILED(hr)) return hr;
1085     if (memcmp(&guid, This->format->guid, sizeof(GUID)) != 0)
1086     {
1087         /* FIXME: should use WICConvertBitmapSource to convert */
1088         ERR("format %s unsupported\n", debugstr_guid(&guid));
1089         return E_FAIL;
1090     }
1091
1092     if (This->xres == 0.0 || This->yres == 0.0)
1093     {
1094         double xres, yres;
1095         hr = IWICBitmapSource_GetResolution(pIBitmapSource, &xres, &yres);
1096         if (FAILED(hr)) return hr;
1097         hr = IWICBitmapFrameEncode_SetResolution(iface, xres, yres);
1098         if (FAILED(hr)) return hr;
1099     }
1100
1101     if (!prc)
1102     {
1103         UINT width, height;
1104         hr = IWICBitmapSource_GetSize(pIBitmapSource, &width, &height);
1105         if (FAILED(hr)) return hr;
1106         rc.X = 0;
1107         rc.Y = 0;
1108         rc.Width = width;
1109         rc.Height = height;
1110         prc = &rc;
1111     }
1112
1113     if (prc->Width != This->width) return E_INVALIDARG;
1114
1115     stride = (This->format->bpp * This->width + 7)/8;
1116
1117     pixeldata = HeapAlloc(GetProcessHeap(), 0, stride * prc->Height);
1118     if (!pixeldata) return E_OUTOFMEMORY;
1119
1120     hr = IWICBitmapSource_CopyPixels(pIBitmapSource, prc, stride,
1121         stride*prc->Height, pixeldata);
1122
1123     if (SUCCEEDED(hr))
1124     {
1125         hr = IWICBitmapFrameEncode_WritePixels(iface, prc->Height, stride,
1126             stride*prc->Height, pixeldata);
1127     }
1128
1129     HeapFree(GetProcessHeap(), 0, pixeldata);
1130
1131     return hr;
1132 }
1133
1134 static HRESULT WINAPI PngFrameEncode_Commit(IWICBitmapFrameEncode *iface)
1135 {
1136     PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1137     jmp_buf jmpbuf;
1138     TRACE("(%p)\n", iface);
1139
1140     EnterCriticalSection(&This->lock);
1141
1142     if (!This->info_written || This->lines_written != This->height || This->frame_committed)
1143     {
1144         LeaveCriticalSection(&This->lock);
1145         return WINCODEC_ERR_WRONGSTATE;
1146     }
1147
1148     /* set up setjmp/longjmp error handling */
1149     if (setjmp(jmpbuf))
1150     {
1151         LeaveCriticalSection(&This->lock);
1152         return E_FAIL;
1153     }
1154     ppng_set_error_fn(This->png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
1155
1156     ppng_write_end(This->png_ptr, This->info_ptr);
1157
1158     This->frame_committed = TRUE;
1159
1160     LeaveCriticalSection(&This->lock);
1161
1162     return S_OK;
1163 }
1164
1165 static HRESULT WINAPI PngFrameEncode_GetMetadataQueryWriter(IWICBitmapFrameEncode *iface,
1166     IWICMetadataQueryWriter **ppIMetadataQueryWriter)
1167 {
1168     FIXME("(%p, %p): stub\n", iface, ppIMetadataQueryWriter);
1169     return E_NOTIMPL;
1170 }
1171
1172 static const IWICBitmapFrameEncodeVtbl PngEncoder_FrameVtbl = {
1173     PngFrameEncode_QueryInterface,
1174     PngFrameEncode_AddRef,
1175     PngFrameEncode_Release,
1176     PngFrameEncode_Initialize,
1177     PngFrameEncode_SetSize,
1178     PngFrameEncode_SetResolution,
1179     PngFrameEncode_SetPixelFormat,
1180     PngFrameEncode_SetColorContexts,
1181     PngFrameEncode_SetPalette,
1182     PngFrameEncode_SetThumbnail,
1183     PngFrameEncode_WritePixels,
1184     PngFrameEncode_WriteSource,
1185     PngFrameEncode_Commit,
1186     PngFrameEncode_GetMetadataQueryWriter
1187 };
1188
1189 static HRESULT WINAPI PngEncoder_QueryInterface(IWICBitmapEncoder *iface, REFIID iid,
1190     void **ppv)
1191 {
1192     PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1193     TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);
1194
1195     if (!ppv) return E_INVALIDARG;
1196
1197     if (IsEqualIID(&IID_IUnknown, iid) ||
1198         IsEqualIID(&IID_IWICBitmapEncoder, iid))
1199     {
1200         *ppv = This;
1201     }
1202     else
1203     {
1204         *ppv = NULL;
1205         return E_NOINTERFACE;
1206     }
1207
1208     IUnknown_AddRef((IUnknown*)*ppv);
1209     return S_OK;
1210 }
1211
1212 static ULONG WINAPI PngEncoder_AddRef(IWICBitmapEncoder *iface)
1213 {
1214     PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1215     ULONG ref = InterlockedIncrement(&This->ref);
1216
1217     TRACE("(%p) refcount=%u\n", iface, ref);
1218
1219     return ref;
1220 }
1221
1222 static ULONG WINAPI PngEncoder_Release(IWICBitmapEncoder *iface)
1223 {
1224     PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1225     ULONG ref = InterlockedDecrement(&This->ref);
1226
1227     TRACE("(%p) refcount=%u\n", iface, ref);
1228
1229     if (ref == 0)
1230     {
1231         This->lock.DebugInfo->Spare[0] = 0;
1232         DeleteCriticalSection(&This->lock);
1233         if (This->png_ptr)
1234             ppng_destroy_write_struct(&This->png_ptr, &This->info_ptr);
1235         if (This->stream)
1236             IStream_Release(This->stream);
1237         HeapFree(GetProcessHeap(), 0, This);
1238     }
1239
1240     return ref;
1241 }
1242
1243 static void user_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
1244 {
1245     PngEncoder *This = ppng_get_io_ptr(png_ptr);
1246     HRESULT hr;
1247     ULONG byteswritten;
1248
1249     hr = IStream_Write(This->stream, data, length, &byteswritten);
1250     if (FAILED(hr) || byteswritten != length)
1251     {
1252         ppng_error(png_ptr, "failed writing data");
1253     }
1254 }
1255
1256 static void user_flush(png_structp png_ptr)
1257 {
1258 }
1259
1260 static HRESULT WINAPI PngEncoder_Initialize(IWICBitmapEncoder *iface,
1261     IStream *pIStream, WICBitmapEncoderCacheOption cacheOption)
1262 {
1263     PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1264     jmp_buf jmpbuf;
1265
1266     TRACE("(%p,%p,%u)\n", iface, pIStream, cacheOption);
1267
1268     EnterCriticalSection(&This->lock);
1269
1270     if (This->png_ptr)
1271     {
1272         LeaveCriticalSection(&This->lock);
1273         return WINCODEC_ERR_WRONGSTATE;
1274     }
1275
1276     /* initialize libpng */
1277     This->png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1278     if (!This->png_ptr)
1279     {
1280         LeaveCriticalSection(&This->lock);
1281         return E_FAIL;
1282     }
1283
1284     This->info_ptr = ppng_create_info_struct(This->png_ptr);
1285     if (!This->info_ptr)
1286     {
1287         ppng_destroy_write_struct(&This->png_ptr, NULL);
1288         This->png_ptr = NULL;
1289         LeaveCriticalSection(&This->lock);
1290         return E_FAIL;
1291     }
1292
1293     IStream_AddRef(pIStream);
1294     This->stream = pIStream;
1295
1296     /* set up setjmp/longjmp error handling */
1297     if (setjmp(jmpbuf))
1298     {
1299         ppng_destroy_write_struct(&This->png_ptr, &This->info_ptr);
1300         This->png_ptr = NULL;
1301         IStream_Release(This->stream);
1302         This->stream = NULL;
1303         LeaveCriticalSection(&This->lock);
1304         return E_FAIL;
1305     }
1306     ppng_set_error_fn(This->png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
1307
1308     /* set up custom i/o handling */
1309     ppng_set_write_fn(This->png_ptr, This, user_write_data, user_flush);
1310
1311     LeaveCriticalSection(&This->lock);
1312
1313     return S_OK;
1314 }
1315
1316 static HRESULT WINAPI PngEncoder_GetContainerFormat(IWICBitmapEncoder *iface,
1317     GUID *pguidContainerFormat)
1318 {
1319     FIXME("(%p,%s): stub\n", iface, debugstr_guid(pguidContainerFormat));
1320     return E_NOTIMPL;
1321 }
1322
1323 static HRESULT WINAPI PngEncoder_GetEncoderInfo(IWICBitmapEncoder *iface,
1324     IWICBitmapEncoderInfo **ppIEncoderInfo)
1325 {
1326     FIXME("(%p,%p): stub\n", iface, ppIEncoderInfo);
1327     return E_NOTIMPL;
1328 }
1329
1330 static HRESULT WINAPI PngEncoder_SetColorContexts(IWICBitmapEncoder *iface,
1331     UINT cCount, IWICColorContext **ppIColorContext)
1332 {
1333     FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
1334     return E_NOTIMPL;
1335 }
1336
1337 static HRESULT WINAPI PngEncoder_SetPalette(IWICBitmapEncoder *iface, IWICPalette *pIPalette)
1338 {
1339     TRACE("(%p,%p)\n", iface, pIPalette);
1340     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1341 }
1342
1343 static HRESULT WINAPI PngEncoder_SetThumbnail(IWICBitmapEncoder *iface, IWICBitmapSource *pIThumbnail)
1344 {
1345     TRACE("(%p,%p)\n", iface, pIThumbnail);
1346     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1347 }
1348
1349 static HRESULT WINAPI PngEncoder_SetPreview(IWICBitmapEncoder *iface, IWICBitmapSource *pIPreview)
1350 {
1351     TRACE("(%p,%p)\n", iface, pIPreview);
1352     return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1353 }
1354
1355 static HRESULT WINAPI PngEncoder_CreateNewFrame(IWICBitmapEncoder *iface,
1356     IWICBitmapFrameEncode **ppIFrameEncode, IPropertyBag2 **ppIEncoderOptions)
1357 {
1358     PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1359     HRESULT hr;
1360     TRACE("(%p,%p,%p)\n", iface, ppIFrameEncode, ppIEncoderOptions);
1361
1362     EnterCriticalSection(&This->lock);
1363
1364     if (This->frame_count != 0)
1365     {
1366         LeaveCriticalSection(&This->lock);
1367         return WINCODEC_ERR_UNSUPPORTEDOPERATION;
1368     }
1369
1370     if (!This->stream)
1371     {
1372         LeaveCriticalSection(&This->lock);
1373         return WINCODEC_ERR_NOTINITIALIZED;
1374     }
1375
1376     hr = CreatePropertyBag2(ppIEncoderOptions);
1377     if (FAILED(hr))
1378     {
1379         LeaveCriticalSection(&This->lock);
1380         return hr;
1381     }
1382
1383     This->frame_count = 1;
1384
1385     LeaveCriticalSection(&This->lock);
1386
1387     IWICBitmapEncoder_AddRef(iface);
1388     *ppIFrameEncode = &This->IWICBitmapFrameEncode_iface;
1389
1390     return S_OK;
1391 }
1392
1393 static HRESULT WINAPI PngEncoder_Commit(IWICBitmapEncoder *iface)
1394 {
1395     PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1396     TRACE("(%p)\n", iface);
1397
1398     EnterCriticalSection(&This->lock);
1399
1400     if (!This->frame_committed || This->committed)
1401     {
1402         LeaveCriticalSection(&This->lock);
1403         return WINCODEC_ERR_WRONGSTATE;
1404     }
1405
1406     This->committed = TRUE;
1407
1408     LeaveCriticalSection(&This->lock);
1409
1410     return S_OK;
1411 }
1412
1413 static HRESULT WINAPI PngEncoder_GetMetadataQueryWriter(IWICBitmapEncoder *iface,
1414     IWICMetadataQueryWriter **ppIMetadataQueryWriter)
1415 {
1416     FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryWriter);
1417     return E_NOTIMPL;
1418 }
1419
1420 static const IWICBitmapEncoderVtbl PngEncoder_Vtbl = {
1421     PngEncoder_QueryInterface,
1422     PngEncoder_AddRef,
1423     PngEncoder_Release,
1424     PngEncoder_Initialize,
1425     PngEncoder_GetContainerFormat,
1426     PngEncoder_GetEncoderInfo,
1427     PngEncoder_SetColorContexts,
1428     PngEncoder_SetPalette,
1429     PngEncoder_SetThumbnail,
1430     PngEncoder_SetPreview,
1431     PngEncoder_CreateNewFrame,
1432     PngEncoder_Commit,
1433     PngEncoder_GetMetadataQueryWriter
1434 };
1435
1436 HRESULT PngEncoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
1437 {
1438     PngEncoder *This;
1439     HRESULT ret;
1440
1441     TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);
1442
1443     *ppv = NULL;
1444
1445     if (pUnkOuter) return CLASS_E_NOAGGREGATION;
1446
1447     if (!libpng_handle && !load_libpng())
1448     {
1449         ERR("Failed writing PNG because unable to find %s\n",SONAME_LIBPNG);
1450         return E_FAIL;
1451     }
1452
1453     This = HeapAlloc(GetProcessHeap(), 0, sizeof(PngEncoder));
1454     if (!This) return E_OUTOFMEMORY;
1455
1456     This->IWICBitmapEncoder_iface.lpVtbl = &PngEncoder_Vtbl;
1457     This->IWICBitmapFrameEncode_iface.lpVtbl = &PngEncoder_FrameVtbl;
1458     This->ref = 1;
1459     This->png_ptr = NULL;
1460     This->info_ptr = NULL;
1461     This->stream = NULL;
1462     This->frame_count = 0;
1463     This->frame_initialized = FALSE;
1464     This->format = NULL;
1465     This->info_written = FALSE;
1466     This->width = 0;
1467     This->height = 0;
1468     This->xres = 0.0;
1469     This->yres = 0.0;
1470     This->lines_written = 0;
1471     This->frame_committed = FALSE;
1472     This->committed = FALSE;
1473     InitializeCriticalSection(&This->lock);
1474     This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": PngEncoder.lock");
1475
1476     ret = IUnknown_QueryInterface((IUnknown*)This, iid, ppv);
1477     IUnknown_Release((IUnknown*)This);
1478
1479     return ret;
1480 }
1481
1482 #else /* !HAVE_PNG_H */
1483
1484 HRESULT PngDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
1485 {
1486     ERR("Trying to load PNG picture, but PNG support is not compiled in.\n");
1487     return E_FAIL;
1488 }
1489
1490 HRESULT PngEncoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
1491 {
1492     ERR("Trying to save PNG picture, but PNG support is not compiled in.\n");
1493     return E_FAIL;
1494 }
1495
1496 #endif