pngformat.c 41.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
/*
 * Copyright 2009 Vincent Povirk for CodeWeavers
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "config.h"
#include "wine/port.h"

#include <stdarg.h>

#ifdef HAVE_PNG_H
#include <png.h>
#endif

#define COBJMACROS

#include "windef.h"
#include "winbase.h"
#include "objbase.h"
#include "wincodec.h"

#include "wincodecs_private.h"

#include "wine/debug.h"
#include "wine/library.h"

WINE_DEFAULT_DEBUG_CHANNEL(wincodecs);

#ifdef SONAME_LIBPNG

static void *libpng_handle;
#define MAKE_FUNCPTR(f) static typeof(f) * p##f
MAKE_FUNCPTR(png_create_read_struct);
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 52 53
MAKE_FUNCPTR(png_error);
MAKE_FUNCPTR(png_get_bit_depth);
MAKE_FUNCPTR(png_get_color_type);
54
MAKE_FUNCPTR(png_get_error_ptr);
55 56 57
MAKE_FUNCPTR(png_get_image_height);
MAKE_FUNCPTR(png_get_image_width);
MAKE_FUNCPTR(png_get_io_ptr);
58
MAKE_FUNCPTR(png_get_pHYs);
59
MAKE_FUNCPTR(png_get_progressive_ptr);
60 61
MAKE_FUNCPTR(png_get_PLTE);
MAKE_FUNCPTR(png_get_tRNS);
62 63
MAKE_FUNCPTR(png_process_data);
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 69 70
#else
MAKE_FUNCPTR(png_set_gray_1_2_4_to_8);
#endif
71
MAKE_FUNCPTR(png_set_filler);
72
MAKE_FUNCPTR(png_set_gray_to_rgb);
73 74
MAKE_FUNCPTR(png_set_IHDR);
MAKE_FUNCPTR(png_set_pHYs);
75
MAKE_FUNCPTR(png_set_progressive_read_fn);
76
MAKE_FUNCPTR(png_set_read_fn);
77 78
MAKE_FUNCPTR(png_set_strip_16);
MAKE_FUNCPTR(png_set_tRNS_to_alpha);
79
MAKE_FUNCPTR(png_set_write_fn);
80 81 82
MAKE_FUNCPTR(png_read_end);
MAKE_FUNCPTR(png_read_image);
MAKE_FUNCPTR(png_read_info);
83
MAKE_FUNCPTR(png_read_update_info);
84
MAKE_FUNCPTR(png_write_end);
85 86
MAKE_FUNCPTR(png_write_info);
MAKE_FUNCPTR(png_write_rows);
87 88 89 90 91 92 93 94 95 96 97 98 99
#undef MAKE_FUNCPTR

static void *load_libpng(void)
{
    if((libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL) {

#define LOAD_FUNCPTR(f) \
    if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
        libpng_handle = NULL; \
        return NULL; \
    }
        LOAD_FUNCPTR(png_create_read_struct);
        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 104 105
        LOAD_FUNCPTR(png_error);
        LOAD_FUNCPTR(png_get_bit_depth);
        LOAD_FUNCPTR(png_get_color_type);
106
        LOAD_FUNCPTR(png_get_error_ptr);
107 108 109
        LOAD_FUNCPTR(png_get_image_height);
        LOAD_FUNCPTR(png_get_image_width);
        LOAD_FUNCPTR(png_get_io_ptr);
110
        LOAD_FUNCPTR(png_get_pHYs);
111
        LOAD_FUNCPTR(png_get_progressive_ptr);
112 113
        LOAD_FUNCPTR(png_get_PLTE);
        LOAD_FUNCPTR(png_get_tRNS);
114 115
        LOAD_FUNCPTR(png_process_data);
        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 121 122
#else
        LOAD_FUNCPTR(png_set_gray_1_2_4_to_8);
#endif
123
        LOAD_FUNCPTR(png_set_filler);
124
        LOAD_FUNCPTR(png_set_gray_to_rgb);
125 126
        LOAD_FUNCPTR(png_set_IHDR);
        LOAD_FUNCPTR(png_set_pHYs);
127
        LOAD_FUNCPTR(png_set_progressive_read_fn);
128
        LOAD_FUNCPTR(png_set_read_fn);
129 130
        LOAD_FUNCPTR(png_set_strip_16);
        LOAD_FUNCPTR(png_set_tRNS_to_alpha);
131
        LOAD_FUNCPTR(png_set_write_fn);
132 133 134
        LOAD_FUNCPTR(png_read_end);
        LOAD_FUNCPTR(png_read_image);
        LOAD_FUNCPTR(png_read_info);
135
        LOAD_FUNCPTR(png_read_update_info);
136
        LOAD_FUNCPTR(png_write_end);
137 138
        LOAD_FUNCPTR(png_write_info);
        LOAD_FUNCPTR(png_write_rows);
139 140 141 142 143 144

#undef LOAD_FUNCPTR
    }
    return libpng_handle;
}

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
static void user_error_fn(png_structp png_ptr, png_const_charp error_message)
{
    jmp_buf *pjmpbuf;

    /* This uses setjmp/longjmp just like the default. We can't use the
     * default because there's no way to access the jmp buffer in the png_struct
     * that works in 1.2 and 1.4 and allows us to dynamically load libpng. */
    WARN("PNG error: %s\n", debugstr_a(error_message));
    pjmpbuf = ppng_get_error_ptr(png_ptr);
    longjmp(*pjmpbuf, 1);
}

static void user_warning_fn(png_structp png_ptr, png_const_charp warning_message)
{
    WARN("PNG warning: %s\n", debugstr_a(warning_message));
}

162
typedef struct {
163 164
    IWICBitmapDecoder IWICBitmapDecoder_iface;
    IWICBitmapFrameDecode IWICBitmapFrameDecode_iface;
165
    LONG ref;
166 167 168 169 170 171 172 173
    png_structp png_ptr;
    png_infop info_ptr;
    BOOL initialized;
    int bpp;
    int width, height;
    UINT stride;
    const WICPixelFormatGUID *format;
    BYTE *image_bits;
174
    CRITICAL_SECTION lock; /* must be held when png structures are accessed or initialized is set */
175 176
} PngDecoder;

177
static inline PngDecoder *impl_from_IWICBitmapDecoder(IWICBitmapDecoder *iface)
178
{
179 180 181 182 183 184
    return CONTAINING_RECORD(iface, PngDecoder, IWICBitmapDecoder_iface);
}

static inline PngDecoder *impl_from_IWICBitmapFrameDecode(IWICBitmapFrameDecode *iface)
{
    return CONTAINING_RECORD(iface, PngDecoder, IWICBitmapFrameDecode_iface);
185 186 187 188
}

static const IWICBitmapFrameDecodeVtbl PngDecoder_FrameVtbl;

189 190 191
static HRESULT WINAPI PngDecoder_QueryInterface(IWICBitmapDecoder *iface, REFIID iid,
    void **ppv)
{
192
    PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);

    if (!ppv) return E_INVALIDARG;

    if (IsEqualIID(&IID_IUnknown, iid) || IsEqualIID(&IID_IWICBitmapDecoder, iid))
    {
        *ppv = This;
    }
    else
    {
        *ppv = NULL;
        return E_NOINTERFACE;
    }

    IUnknown_AddRef((IUnknown*)*ppv);
    return S_OK;
}

static ULONG WINAPI PngDecoder_AddRef(IWICBitmapDecoder *iface)
{
213
    PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
214 215 216 217 218 219 220 221 222
    ULONG ref = InterlockedIncrement(&This->ref);

    TRACE("(%p) refcount=%u\n", iface, ref);

    return ref;
}

static ULONG WINAPI PngDecoder_Release(IWICBitmapDecoder *iface)
{
223
    PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
224 225 226 227 228 229
    ULONG ref = InterlockedDecrement(&This->ref);

    TRACE("(%p) refcount=%u\n", iface, ref);

    if (ref == 0)
    {
230
        if (This->png_ptr)
231
            ppng_destroy_read_struct(&This->png_ptr, &This->info_ptr, NULL);
232 233
        This->lock.DebugInfo->Spare[0] = 0;
        DeleteCriticalSection(&This->lock);
234
        HeapFree(GetProcessHeap(), 0, This->image_bits);
235 236 237 238 239 240 241 242 243 244 245 246 247
        HeapFree(GetProcessHeap(), 0, This);
    }

    return ref;
}

static HRESULT WINAPI PngDecoder_QueryCapability(IWICBitmapDecoder *iface, IStream *pIStream,
    DWORD *pdwCapability)
{
    FIXME("(%p,%p,%p): stub\n", iface, pIStream, pdwCapability);
    return E_NOTIMPL;
}

248
static void info_callback(png_structp png_ptr, png_infop info)
249 250
{
    int color_type, bit_depth;
251 252 253 254
    png_bytep trans;
    int num_trans;
    png_uint_32 transparency;
    png_color_16p trans_values;
255 256 257
    UINT image_size;
    HRESULT hr = S_OK;
    PngDecoder *This;
258

259
    This = (PngDecoder*) ppng_get_progressive_ptr(png_ptr);
260 261 262 263 264

    /* choose a pixel format */
    color_type = ppng_get_color_type(This->png_ptr, This->info_ptr);
    bit_depth = ppng_get_bit_depth(This->png_ptr, This->info_ptr);

265 266 267 268 269 270 271 272 273 274
    /* check for color-keyed alpha */
    transparency = ppng_get_tRNS(This->png_ptr, This->info_ptr, &trans, &num_trans, &trans_values);

    if (transparency && color_type != PNG_COLOR_TYPE_PALETTE)
    {
        /* expand to RGBA */
        if (color_type == PNG_COLOR_TYPE_GRAY)
        {
            if (bit_depth < 8)
            {
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 278 279
#else
                ppng_set_gray_1_2_4_to_8(This->png_ptr);
#endif
280 281 282 283 284 285 286 287
                bit_depth = 8;
            }
            ppng_set_gray_to_rgb(This->png_ptr);
        }
        ppng_set_tRNS_to_alpha(This->png_ptr);
        color_type = PNG_COLOR_TYPE_RGB_ALPHA;
    }

288 289 290 291 292 293 294 295 296 297 298 299 300
    switch (color_type)
    {
    case PNG_COLOR_TYPE_GRAY:
        This->bpp = bit_depth;
        switch (bit_depth)
        {
        case 1: This->format = &GUID_WICPixelFormatBlackWhite; break;
        case 2: This->format = &GUID_WICPixelFormat2bppGray; break;
        case 4: This->format = &GUID_WICPixelFormat4bppGray; break;
        case 8: This->format = &GUID_WICPixelFormat8bppGray; break;
        case 16: This->format = &GUID_WICPixelFormat16bppGray; break;
        default:
            ERR("invalid grayscale bit depth: %i\n", bit_depth);
301 302
            hr = E_FAIL;
            goto end;
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
        }
        break;
    case PNG_COLOR_TYPE_GRAY_ALPHA:
        /* WIC does not support grayscale alpha formats so use RGBA */
        ppng_set_gray_to_rgb(This->png_ptr);
    case PNG_COLOR_TYPE_RGB_ALPHA:
        This->bpp = bit_depth * 4;
        switch (bit_depth)
        {
        case 8:
            ppng_set_bgr(This->png_ptr);
            This->format = &GUID_WICPixelFormat32bppBGRA;
            break;
        case 16: This->format = &GUID_WICPixelFormat64bppRGBA; break;
        default:
            ERR("invalid RGBA bit depth: %i\n", bit_depth);
319 320
            hr = E_FAIL;
            goto end;
321 322 323 324 325 326 327 328 329 330 331 332
        }
        break;
    case PNG_COLOR_TYPE_PALETTE:
        This->bpp = bit_depth;
        switch (bit_depth)
        {
        case 1: This->format = &GUID_WICPixelFormat1bppIndexed; break;
        case 2: This->format = &GUID_WICPixelFormat2bppIndexed; break;
        case 4: This->format = &GUID_WICPixelFormat4bppIndexed; break;
        case 8: This->format = &GUID_WICPixelFormat8bppIndexed; break;
        default:
            ERR("invalid indexed color bit depth: %i\n", bit_depth);
333 334
            hr = E_FAIL;
            goto end;
335 336 337 338 339 340 341 342 343 344 345 346 347
        }
        break;
    case PNG_COLOR_TYPE_RGB:
        This->bpp = bit_depth * 3;
        switch (bit_depth)
        {
        case 8:
            ppng_set_bgr(This->png_ptr);
            This->format = &GUID_WICPixelFormat24bppBGR;
            break;
        case 16: This->format = &GUID_WICPixelFormat48bppRGB; break;
        default:
            ERR("invalid RGB color bit depth: %i\n", bit_depth);
348 349
            hr = E_FAIL;
            goto end;
350 351 352 353
        }
        break;
    default:
        ERR("invalid color type %i\n", color_type);
354 355
        hr = E_FAIL;
        goto end;
356 357 358 359 360 361 362 363
    }

    This->width = ppng_get_image_width(This->png_ptr, This->info_ptr);
    This->height = ppng_get_image_height(This->png_ptr, This->info_ptr);
    This->stride = This->width * This->bpp;
    image_size = This->stride * This->height;

    This->image_bits = HeapAlloc(GetProcessHeap(), 0, image_size);
364 365 366 367 368
    if (!This->image_bits)
    {
        hr = E_OUTOFMEMORY;
        goto end;
    }
369

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    ppng_read_update_info(This->png_ptr, This->info_ptr);
    This->initialized = TRUE;

end:
    if (FAILED(hr))
        ERR("PNG info parsing failed, hr=0x%08X\n", hr);
}

static void row_callback(png_structp png_ptr, png_bytep new_row,
                         png_uint_32 row_num, int pass)
{
    png_bytep old_row;
    PngDecoder *This;

    This = (PngDecoder*) ppng_get_progressive_ptr(png_ptr);
    if (!This->initialized)
        return;

    old_row = ((png_bytep)This->image_bits) + row_num*This->stride;
    ppng_progressive_combine_row(png_ptr, old_row, new_row);
}

static void end_callback(png_structp png_ptr, png_infop info)
{
}

static HRESULT WINAPI PngDecoder_Initialize(IWICBitmapDecoder *iface, IStream *pIStream,
    WICDecodeOptions cacheOptions)
{
399
    PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
400 401 402 403 404 405 406 407 408 409 410 411 412 413
    LARGE_INTEGER seek;
    HRESULT hr=S_OK;
    png_bytep *row_pointers=NULL;
    jmp_buf jmpbuf;
    BYTE buffer[8096];
    ULONG bytesRead = 0;

    TRACE("(%p,%p,%x)\n", iface, pIStream, cacheOptions);

    EnterCriticalSection(&This->lock);

    /* initialize libpng */
    This->png_ptr = ppng_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (!This->png_ptr)
414
    {
415
        hr = E_FAIL;
416 417
        goto end;
    }
418

419 420 421 422 423 424 425 426
    This->info_ptr = ppng_create_info_struct(This->png_ptr);
    if (!This->info_ptr)
    {
        ppng_destroy_read_struct(&This->png_ptr, NULL, NULL);
        This->png_ptr = NULL;
        hr = E_FAIL;
        goto end;
    }
427

428 429 430 431 432 433 434 435 436 437
    /* set up setjmp/longjmp error handling */
    if (setjmp(jmpbuf))
    {
        ppng_destroy_read_struct(&This->png_ptr, &This->info_ptr, NULL);
        HeapFree(GetProcessHeap(), 0, row_pointers);
        This->png_ptr = NULL;
        hr = E_FAIL;
        goto end;
    }
    ppng_set_error_fn(This->png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
438

439 440 441 442
    /* seek to the start of the stream */
    seek.QuadPart = 0;
    hr = IStream_Seek(pIStream, seek, STREAM_SEEK_SET, NULL);
    if (FAILED(hr)) goto end;
443

444 445 446
    /* set up progressive loading */
    ppng_set_progressive_read_fn(This->png_ptr, (void*)This,
        info_callback, row_callback, end_callback);
447

448 449 450 451 452 453 454 455 456 457 458 459
    do
    {
        hr = IStream_Read(pIStream, buffer, sizeof(buffer), &bytesRead);
        if (SUCCEEDED(hr))
            ppng_process_data(This->png_ptr, This->info_ptr, buffer, bytesRead);
    } while (bytesRead == sizeof(buffer));
    if (hr == S_FALSE)
        hr = S_OK;
    if (FAILED(hr))
        ERR("reading PNG file failed, error 0x%08X\n", hr);
    if (!This->initialized)
        hr = E_FAIL;
460

461 462 463 464 465
end:

    LeaveCriticalSection(&This->lock);

    return hr;
466 467 468 469 470
}

static HRESULT WINAPI PngDecoder_GetContainerFormat(IWICBitmapDecoder *iface,
    GUID *pguidContainerFormat)
{
471 472
    memcpy(pguidContainerFormat, &GUID_ContainerFormatPng, sizeof(GUID));
    return S_OK;
473 474 475 476 477
}

static HRESULT WINAPI PngDecoder_GetDecoderInfo(IWICBitmapDecoder *iface,
    IWICBitmapDecoderInfo **ppIDecoderInfo)
{
478 479 480 481 482 483 484 485 486 487 488 489 490 491
    HRESULT hr;
    IWICComponentInfo *compinfo;

    TRACE("(%p,%p)\n", iface, ppIDecoderInfo);

    hr = CreateComponentInfo(&CLSID_WICPngDecoder, &compinfo);
    if (FAILED(hr)) return hr;

    hr = IWICComponentInfo_QueryInterface(compinfo, &IID_IWICBitmapDecoderInfo,
        (void**)ppIDecoderInfo);

    IWICComponentInfo_Release(compinfo);

    return hr;
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
}

static HRESULT WINAPI PngDecoder_CopyPalette(IWICBitmapDecoder *iface,
    IWICPalette *pIPalette)
{
    FIXME("(%p,%p): stub\n", iface, pIPalette);
    return E_NOTIMPL;
}

static HRESULT WINAPI PngDecoder_GetMetadataQueryReader(IWICBitmapDecoder *iface,
    IWICMetadataQueryReader **ppIMetadataQueryReader)
{
    FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
    return E_NOTIMPL;
}

static HRESULT WINAPI PngDecoder_GetPreview(IWICBitmapDecoder *iface,
    IWICBitmapSource **ppIBitmapSource)
{
    FIXME("(%p,%p): stub\n", iface, ppIBitmapSource);
    return E_NOTIMPL;
}

static HRESULT WINAPI PngDecoder_GetColorContexts(IWICBitmapDecoder *iface,
    UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
{
    FIXME("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);
    return E_NOTIMPL;
}

static HRESULT WINAPI PngDecoder_GetThumbnail(IWICBitmapDecoder *iface,
    IWICBitmapSource **ppIThumbnail)
{
    TRACE("(%p,%p)\n", iface, ppIThumbnail);
    return WINCODEC_ERR_CODECNOTHUMBNAIL;
}

static HRESULT WINAPI PngDecoder_GetFrameCount(IWICBitmapDecoder *iface,
    UINT *pCount)
{
532 533
    *pCount = 1;
    return S_OK;
534 535 536 537 538
}

static HRESULT WINAPI PngDecoder_GetFrame(IWICBitmapDecoder *iface,
    UINT index, IWICBitmapFrameDecode **ppIBitmapFrame)
{
539
    PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
540 541 542 543 544 545 546 547
    TRACE("(%p,%u,%p)\n", iface, index, ppIBitmapFrame);

    if (!This->initialized) return WINCODEC_ERR_NOTINITIALIZED;

    if (index != 0) return E_INVALIDARG;

    IWICBitmapDecoder_AddRef(iface);

548
    *ppIBitmapFrame = &This->IWICBitmapFrameDecode_iface;
549 550

    return S_OK;
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
}

static const IWICBitmapDecoderVtbl PngDecoder_Vtbl = {
    PngDecoder_QueryInterface,
    PngDecoder_AddRef,
    PngDecoder_Release,
    PngDecoder_QueryCapability,
    PngDecoder_Initialize,
    PngDecoder_GetContainerFormat,
    PngDecoder_GetDecoderInfo,
    PngDecoder_CopyPalette,
    PngDecoder_GetMetadataQueryReader,
    PngDecoder_GetPreview,
    PngDecoder_GetColorContexts,
    PngDecoder_GetThumbnail,
    PngDecoder_GetFrameCount,
    PngDecoder_GetFrame
};

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
static HRESULT WINAPI PngDecoder_Frame_QueryInterface(IWICBitmapFrameDecode *iface, REFIID iid,
    void **ppv)
{
    if (!ppv) return E_INVALIDARG;

    if (IsEqualIID(&IID_IUnknown, iid) ||
        IsEqualIID(&IID_IWICBitmapSource, iid) ||
        IsEqualIID(&IID_IWICBitmapFrameDecode, iid))
    {
        *ppv = iface;
    }
    else
    {
        *ppv = NULL;
        return E_NOINTERFACE;
    }

    IUnknown_AddRef((IUnknown*)*ppv);
    return S_OK;
}

static ULONG WINAPI PngDecoder_Frame_AddRef(IWICBitmapFrameDecode *iface)
{
593
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
594 595 596 597 598
    return IUnknown_AddRef((IUnknown*)This);
}

static ULONG WINAPI PngDecoder_Frame_Release(IWICBitmapFrameDecode *iface)
{
599
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
600 601 602 603 604 605
    return IUnknown_Release((IUnknown*)This);
}

static HRESULT WINAPI PngDecoder_Frame_GetSize(IWICBitmapFrameDecode *iface,
    UINT *puiWidth, UINT *puiHeight)
{
606
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
607 608 609 610
    *puiWidth = This->width;
    *puiHeight = This->height;
    TRACE("(%p)->(%u,%u)\n", iface, *puiWidth, *puiHeight);
    return S_OK;
611 612 613 614 615
}

static HRESULT WINAPI PngDecoder_Frame_GetPixelFormat(IWICBitmapFrameDecode *iface,
    WICPixelFormatGUID *pPixelFormat)
{
616
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
617 618 619 620 621
    TRACE("(%p,%p)\n", iface, pPixelFormat);

    memcpy(pPixelFormat, This->format, sizeof(GUID));

    return S_OK;
622 623 624 625 626
}

static HRESULT WINAPI PngDecoder_Frame_GetResolution(IWICBitmapFrameDecode *iface,
    double *pDpiX, double *pDpiY)
{
627
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
628 629 630
    png_uint_32 ret, xres, yres;
    int unit_type;

631 632
    EnterCriticalSection(&This->lock);

633 634 635 636 637 638 639 640 641 642 643 644 645
    ret = ppng_get_pHYs(This->png_ptr, This->info_ptr, &xres, &yres, &unit_type);

    if (ret && unit_type == PNG_RESOLUTION_METER)
    {
        *pDpiX = xres * 0.0254;
        *pDpiY = yres * 0.0254;
    }
    else
    {
        WARN("no pHYs block present\n");
        *pDpiX = *pDpiY = 96.0;
    }

646 647
    LeaveCriticalSection(&This->lock);

648 649 650
    TRACE("(%p)->(%0.2f,%0.2f)\n", iface, *pDpiX, *pDpiY);

    return S_OK;
651 652 653 654 655
}

static HRESULT WINAPI PngDecoder_Frame_CopyPalette(IWICBitmapFrameDecode *iface,
    IWICPalette *pIPalette)
{
656
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
657 658 659 660 661 662 663 664
    png_uint_32 ret;
    png_colorp png_palette;
    int num_palette;
    WICColor palette[256];
    png_bytep trans;
    int num_trans;
    png_color_16p trans_values;
    int i;
665
    HRESULT hr=S_OK;
666 667 668

    TRACE("(%p,%p)\n", iface, pIPalette);

669 670
    EnterCriticalSection(&This->lock);

671
    ret = ppng_get_PLTE(This->png_ptr, This->info_ptr, &png_palette, &num_palette);
672 673 674 675 676
    if (!ret)
    {
        hr = WINCODEC_ERR_PALETTEUNAVAILABLE;
        goto end;
    }
677 678 679 680

    if (num_palette > 256)
    {
        ERR("palette has %i colors?!\n", num_palette);
681 682
        hr = E_FAIL;
        goto end;
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
    }

    for (i=0; i<num_palette; i++)
    {
        palette[i] = (0xff000000|
                      png_palette[i].red << 16|
                      png_palette[i].green << 8|
                      png_palette[i].blue);
    }

    ret = ppng_get_tRNS(This->png_ptr, This->info_ptr, &trans, &num_trans, &trans_values);
    if (ret)
    {
        for (i=0; i<num_trans; i++)
        {
            palette[trans[i]] = 0x00000000;
        }
    }

702 703 704 705 706 707 708 709
end:

    LeaveCriticalSection(&This->lock);

    if (SUCCEEDED(hr))
        hr = IWICPalette_InitializeCustom(pIPalette, palette, num_palette);

    return hr;
710 711 712 713 714
}

static HRESULT WINAPI PngDecoder_Frame_CopyPixels(IWICBitmapFrameDecode *iface,
    const WICRect *prc, UINT cbStride, UINT cbBufferSize, BYTE *pbBuffer)
{
715
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
716 717 718 719 720
    TRACE("(%p,%p,%u,%u,%p)\n", iface, prc, cbStride, cbBufferSize, pbBuffer);

    return copy_pixels(This->bpp, This->image_bits,
        This->width, This->height, This->stride,
        prc, cbStride, cbBufferSize, pbBuffer);
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
}

static HRESULT WINAPI PngDecoder_Frame_GetMetadataQueryReader(IWICBitmapFrameDecode *iface,
    IWICMetadataQueryReader **ppIMetadataQueryReader)
{
    FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryReader);
    return E_NOTIMPL;
}

static HRESULT WINAPI PngDecoder_Frame_GetColorContexts(IWICBitmapFrameDecode *iface,
    UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
{
    FIXME("(%p,%u,%p,%p): stub\n", iface, cCount, ppIColorContexts, pcActualCount);
    return E_NOTIMPL;
}

static HRESULT WINAPI PngDecoder_Frame_GetThumbnail(IWICBitmapFrameDecode *iface,
    IWICBitmapSource **ppIThumbnail)
{
    FIXME("(%p,%p): stub\n", iface, ppIThumbnail);
    return E_NOTIMPL;
}

static const IWICBitmapFrameDecodeVtbl PngDecoder_FrameVtbl = {
    PngDecoder_Frame_QueryInterface,
    PngDecoder_Frame_AddRef,
    PngDecoder_Frame_Release,
    PngDecoder_Frame_GetSize,
    PngDecoder_Frame_GetPixelFormat,
    PngDecoder_Frame_GetResolution,
    PngDecoder_Frame_CopyPalette,
    PngDecoder_Frame_CopyPixels,
    PngDecoder_Frame_GetMetadataQueryReader,
    PngDecoder_Frame_GetColorContexts,
    PngDecoder_Frame_GetThumbnail
};

758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
HRESULT PngDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
{
    PngDecoder *This;
    HRESULT ret;

    TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);

    *ppv = NULL;

    if (pUnkOuter) return CLASS_E_NOAGGREGATION;

    if (!libpng_handle && !load_libpng())
    {
        ERR("Failed reading PNG because unable to find %s\n",SONAME_LIBPNG);
        return E_FAIL;
    }

    This = HeapAlloc(GetProcessHeap(), 0, sizeof(PngDecoder));
    if (!This) return E_OUTOFMEMORY;

778 779
    This->IWICBitmapDecoder_iface.lpVtbl = &PngDecoder_Vtbl;
    This->IWICBitmapFrameDecode_iface.lpVtbl = &PngDecoder_FrameVtbl;
780
    This->ref = 1;
781 782 783 784
    This->png_ptr = NULL;
    This->info_ptr = NULL;
    This->initialized = FALSE;
    This->image_bits = NULL;
785 786
    InitializeCriticalSection(&This->lock);
    This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": PngDecoder.lock");
787 788 789 790 791 792 793

    ret = IUnknown_QueryInterface((IUnknown*)This, iid, ppv);
    IUnknown_Release((IUnknown*)This);

    return ret;
}

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
struct png_pixelformat {
    const WICPixelFormatGUID *guid;
    UINT bpp;
    int bit_depth;
    int color_type;
    BOOL remove_filler;
    BOOL swap_rgb;
};

static const struct png_pixelformat formats[] = {
    {&GUID_WICPixelFormat24bppBGR, 24, 8, PNG_COLOR_TYPE_RGB, 0, 1},
    {&GUID_WICPixelFormatBlackWhite, 1, 1, PNG_COLOR_TYPE_GRAY, 0, 0},
    {&GUID_WICPixelFormat2bppGray, 2, 2, PNG_COLOR_TYPE_GRAY, 0, 0},
    {&GUID_WICPixelFormat4bppGray, 4, 4, PNG_COLOR_TYPE_GRAY, 0, 0},
    {&GUID_WICPixelFormat8bppGray, 8, 8, PNG_COLOR_TYPE_GRAY, 0, 0},
    {&GUID_WICPixelFormat16bppGray, 16, 16, PNG_COLOR_TYPE_GRAY, 0, 0},
    {&GUID_WICPixelFormat32bppBGR, 32, 8, PNG_COLOR_TYPE_RGB, 1, 1},
    {&GUID_WICPixelFormat32bppBGRA, 32, 8, PNG_COLOR_TYPE_RGB_ALPHA, 0, 1},
    {&GUID_WICPixelFormat48bppRGB, 48, 16, PNG_COLOR_TYPE_RGB, 0, 0},
    {&GUID_WICPixelFormat64bppRGBA, 64, 16, PNG_COLOR_TYPE_RGB_ALPHA, 0, 0},
    {NULL},
};

817
typedef struct PngEncoder {
818 819
    IWICBitmapEncoder IWICBitmapEncoder_iface;
    IWICBitmapFrameEncode IWICBitmapFrameEncode_iface;
820
    LONG ref;
821 822 823
    IStream *stream;
    png_structp png_ptr;
    png_infop info_ptr;
824
    UINT frame_count;
825
    BOOL frame_initialized;
826 827
    const struct png_pixelformat *format;
    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 835
} PngEncoder;

836
static inline PngEncoder *impl_from_IWICBitmapEncoder(IWICBitmapEncoder *iface)
837
{
838 839 840 841 842 843
    return CONTAINING_RECORD(iface, PngEncoder, IWICBitmapEncoder_iface);
}

static inline PngEncoder *impl_from_IWICBitmapFrameEncode(IWICBitmapFrameEncode *iface)
{
    return CONTAINING_RECORD(iface, PngEncoder, IWICBitmapFrameEncode_iface);
844 845 846 847 848
}

static HRESULT WINAPI PngFrameEncode_QueryInterface(IWICBitmapFrameEncode *iface, REFIID iid,
    void **ppv)
{
849
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
850 851 852 853 854 855 856
    TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);

    if (!ppv) return E_INVALIDARG;

    if (IsEqualIID(&IID_IUnknown, iid) ||
        IsEqualIID(&IID_IWICBitmapFrameEncode, iid))
    {
857
        *ppv = &This->IWICBitmapFrameEncode_iface;
858 859 860 861 862 863 864 865 866 867 868 869 870
    }
    else
    {
        *ppv = NULL;
        return E_NOINTERFACE;
    }

    IUnknown_AddRef((IUnknown*)*ppv);
    return S_OK;
}

static ULONG WINAPI PngFrameEncode_AddRef(IWICBitmapFrameEncode *iface)
{
871
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
872 873 874 875 876
    return IUnknown_AddRef((IUnknown*)This);
}

static ULONG WINAPI PngFrameEncode_Release(IWICBitmapFrameEncode *iface)
{
877
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
878 879 880 881 882 883
    return IUnknown_Release((IUnknown*)This);
}

static HRESULT WINAPI PngFrameEncode_Initialize(IWICBitmapFrameEncode *iface,
    IPropertyBag2 *pIEncoderOptions)
{
884
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
885 886
    TRACE("(%p,%p)\n", iface, pIEncoderOptions);

887 888 889 890 891 892 893
    EnterCriticalSection(&This->lock);

    if (This->frame_initialized)
    {
        LeaveCriticalSection(&This->lock);
        return WINCODEC_ERR_WRONGSTATE;
    }
894 895 896

    This->frame_initialized = TRUE;

897 898
    LeaveCriticalSection(&This->lock);

899
    return S_OK;
900 901 902 903 904
}

static HRESULT WINAPI PngFrameEncode_SetSize(IWICBitmapFrameEncode *iface,
    UINT uiWidth, UINT uiHeight)
{
905
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
906 907
    TRACE("(%p,%u,%u)\n", iface, uiWidth, uiHeight);

908 909 910 911 912 913 914
    EnterCriticalSection(&This->lock);

    if (!This->frame_initialized || This->info_written)
    {
        LeaveCriticalSection(&This->lock);
        return WINCODEC_ERR_WRONGSTATE;
    }
915 916 917 918

    This->width = uiWidth;
    This->height = uiHeight;

919 920
    LeaveCriticalSection(&This->lock);

921
    return S_OK;
922 923 924 925 926
}

static HRESULT WINAPI PngFrameEncode_SetResolution(IWICBitmapFrameEncode *iface,
    double dpiX, double dpiY)
{
927
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
928 929
    TRACE("(%p,%0.2f,%0.2f)\n", iface, dpiX, dpiY);

930 931 932 933 934 935 936
    EnterCriticalSection(&This->lock);

    if (!This->frame_initialized || This->info_written)
    {
        LeaveCriticalSection(&This->lock);
        return WINCODEC_ERR_WRONGSTATE;
    }
937 938 939 940

    This->xres = dpiX;
    This->yres = dpiY;

941 942
    LeaveCriticalSection(&This->lock);

943
    return S_OK;
944 945 946 947 948
}

static HRESULT WINAPI PngFrameEncode_SetPixelFormat(IWICBitmapFrameEncode *iface,
    WICPixelFormatGUID *pPixelFormat)
{
949
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
950 951 952
    int i;
    TRACE("(%p,%s)\n", iface, debugstr_guid(pPixelFormat));

953 954 955 956 957 958 959
    EnterCriticalSection(&This->lock);

    if (!This->frame_initialized || This->info_written)
    {
        LeaveCriticalSection(&This->lock);
        return WINCODEC_ERR_WRONGSTATE;
    }
960 961 962 963 964 965 966 967 968 969 970 971

    for (i=0; formats[i].guid; i++)
    {
        if (memcmp(formats[i].guid, pPixelFormat, sizeof(GUID)) == 0)
            break;
    }

    if (!formats[i].guid) i = 0;

    This->format = &formats[i];
    memcpy(pPixelFormat, This->format->guid, sizeof(GUID));

972 973
    LeaveCriticalSection(&This->lock);

974
    return S_OK;
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
}

static HRESULT WINAPI PngFrameEncode_SetColorContexts(IWICBitmapFrameEncode *iface,
    UINT cCount, IWICColorContext **ppIColorContext)
{
    FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
    return E_NOTIMPL;
}

static HRESULT WINAPI PngFrameEncode_SetPalette(IWICBitmapFrameEncode *iface,
    IWICPalette *pIPalette)
{
    FIXME("(%p,%p): stub\n", iface, pIPalette);
    return WINCODEC_ERR_UNSUPPORTEDOPERATION;
}

static HRESULT WINAPI PngFrameEncode_SetThumbnail(IWICBitmapFrameEncode *iface,
    IWICBitmapSource *pIThumbnail)
{
    FIXME("(%p,%p): stub\n", iface, pIThumbnail);
    return WINCODEC_ERR_UNSUPPORTEDOPERATION;
}

static HRESULT WINAPI PngFrameEncode_WritePixels(IWICBitmapFrameEncode *iface,
    UINT lineCount, UINT cbStride, UINT cbBufferSize, BYTE *pbPixels)
{
1001
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1002 1003
    png_byte **row_pointers=NULL;
    UINT i;
1004
    jmp_buf jmpbuf;
1005 1006
    TRACE("(%p,%u,%u,%u,%p)\n", iface, lineCount, cbStride, cbBufferSize, pbPixels);

1007 1008
    EnterCriticalSection(&This->lock);

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 1027
        return E_FAIL;
    }
1028
    ppng_set_error_fn(This->png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054

    if (!This->info_written)
    {
        ppng_set_IHDR(This->png_ptr, This->info_ptr, This->width, This->height,
            This->format->bit_depth, This->format->color_type, PNG_INTERLACE_NONE,
            PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

        if (This->xres != 0.0 && This->yres != 0.0)
        {
            ppng_set_pHYs(This->png_ptr, This->info_ptr, (This->xres+0.0127) / 0.0254,
                (This->yres+0.0127) / 0.0254, PNG_RESOLUTION_METER);
        }

        ppng_write_info(This->png_ptr, This->info_ptr);

        if (This->format->remove_filler)
            ppng_set_filler(This->png_ptr, 0, PNG_FILLER_AFTER);

        if (This->format->swap_rgb)
            ppng_set_bgr(This->png_ptr);

        This->info_written = TRUE;
    }

    row_pointers = HeapAlloc(GetProcessHeap(), 0, lineCount * sizeof(png_byte*));
    if (!row_pointers)
1055 1056
    {
        LeaveCriticalSection(&This->lock);
1057
        return E_OUTOFMEMORY;
1058
    }
1059 1060 1061 1062 1063 1064 1065

    for (i=0; i<lineCount; i++)
        row_pointers[i] = pbPixels + cbStride * i;

    ppng_write_rows(This->png_ptr, row_pointers, lineCount);
    This->lines_written += lineCount;

1066 1067
    LeaveCriticalSection(&This->lock);

1068 1069 1070
    HeapFree(GetProcessHeap(), 0, row_pointers);

    return S_OK;
1071 1072 1073 1074 1075
}

static HRESULT WINAPI PngFrameEncode_WriteSource(IWICBitmapFrameEncode *iface,
    IWICBitmapSource *pIBitmapSource, WICRect *prc)
{
1076
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
    HRESULT hr;
    WICRect rc;
    WICPixelFormatGUID guid;
    UINT stride;
    BYTE *pixeldata;
    TRACE("(%p,%p,%p)\n", iface, pIBitmapSource, prc);

    if (!This->frame_initialized || !This->width || !This->height)
        return WINCODEC_ERR_WRONGSTATE;

    if (!This->format)
    {
        hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
        if (FAILED(hr)) return hr;
        hr = IWICBitmapFrameEncode_SetPixelFormat(iface, &guid);
        if (FAILED(hr)) return hr;
    }

    hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
    if (FAILED(hr)) return hr;
    if (memcmp(&guid, This->format->guid, sizeof(GUID)) != 0)
    {
        /* FIXME: should use WICConvertBitmapSource to convert */
        ERR("format %s unsupported\n", debugstr_guid(&guid));
        return E_FAIL;
    }

    if (This->xres == 0.0 || This->yres == 0.0)
    {
        double xres, yres;
        hr = IWICBitmapSource_GetResolution(pIBitmapSource, &xres, &yres);
        if (FAILED(hr)) return hr;
        hr = IWICBitmapFrameEncode_SetResolution(iface, xres, yres);
        if (FAILED(hr)) return hr;
    }

    if (!prc)
    {
        UINT width, height;
        hr = IWICBitmapSource_GetSize(pIBitmapSource, &width, &height);
        if (FAILED(hr)) return hr;
        rc.X = 0;
        rc.Y = 0;
        rc.Width = width;
        rc.Height = height;
        prc = &rc;
    }

    if (prc->Width != This->width) return E_INVALIDARG;

    stride = (This->format->bpp * This->width + 7)/8;

    pixeldata = HeapAlloc(GetProcessHeap(), 0, stride * prc->Height);
    if (!pixeldata) return E_OUTOFMEMORY;

    hr = IWICBitmapSource_CopyPixels(pIBitmapSource, prc, stride,
        stride*prc->Height, pixeldata);

    if (SUCCEEDED(hr))
    {
        hr = IWICBitmapFrameEncode_WritePixels(iface, prc->Height, stride,
            stride*prc->Height, pixeldata);
    }

    HeapFree(GetProcessHeap(), 0, pixeldata);

    return hr;
1144 1145 1146 1147
}

static HRESULT WINAPI PngFrameEncode_Commit(IWICBitmapFrameEncode *iface)
{
1148
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1149
    jmp_buf jmpbuf;
1150 1151
    TRACE("(%p)\n", iface);

1152 1153
    EnterCriticalSection(&This->lock);

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 1165
        return E_FAIL;
    }
1166
    ppng_set_error_fn(This->png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
1167 1168 1169 1170 1171

    ppng_write_end(This->png_ptr, This->info_ptr);

    This->frame_committed = TRUE;

1172 1173
    LeaveCriticalSection(&This->lock);

1174
    return S_OK;
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
}

static HRESULT WINAPI PngFrameEncode_GetMetadataQueryWriter(IWICBitmapFrameEncode *iface,
    IWICMetadataQueryWriter **ppIMetadataQueryWriter)
{
    FIXME("(%p, %p): stub\n", iface, ppIMetadataQueryWriter);
    return E_NOTIMPL;
}

static const IWICBitmapFrameEncodeVtbl PngEncoder_FrameVtbl = {
    PngFrameEncode_QueryInterface,
    PngFrameEncode_AddRef,
    PngFrameEncode_Release,
    PngFrameEncode_Initialize,
    PngFrameEncode_SetSize,
    PngFrameEncode_SetResolution,
    PngFrameEncode_SetPixelFormat,
    PngFrameEncode_SetColorContexts,
    PngFrameEncode_SetPalette,
    PngFrameEncode_SetThumbnail,
    PngFrameEncode_WritePixels,
    PngFrameEncode_WriteSource,
    PngFrameEncode_Commit,
    PngFrameEncode_GetMetadataQueryWriter
};

1201 1202 1203
static HRESULT WINAPI PngEncoder_QueryInterface(IWICBitmapEncoder *iface, REFIID iid,
    void **ppv)
{
1204
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
    TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);

    if (!ppv) return E_INVALIDARG;

    if (IsEqualIID(&IID_IUnknown, iid) ||
        IsEqualIID(&IID_IWICBitmapEncoder, iid))
    {
        *ppv = This;
    }
    else
    {
        *ppv = NULL;
        return E_NOINTERFACE;
    }

    IUnknown_AddRef((IUnknown*)*ppv);
    return S_OK;
}

static ULONG WINAPI PngEncoder_AddRef(IWICBitmapEncoder *iface)
{
1226
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1227 1228 1229 1230 1231 1232 1233 1234 1235
    ULONG ref = InterlockedIncrement(&This->ref);

    TRACE("(%p) refcount=%u\n", iface, ref);

    return ref;
}

static ULONG WINAPI PngEncoder_Release(IWICBitmapEncoder *iface)
{
1236
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1237 1238 1239 1240 1241 1242
    ULONG ref = InterlockedDecrement(&This->ref);

    TRACE("(%p) refcount=%u\n", iface, ref);

    if (ref == 0)
    {
1243 1244
        This->lock.DebugInfo->Spare[0] = 0;
        DeleteCriticalSection(&This->lock);
1245 1246 1247 1248
        if (This->png_ptr)
            ppng_destroy_write_struct(&This->png_ptr, &This->info_ptr);
        if (This->stream)
            IStream_Release(This->stream);
1249 1250 1251 1252 1253 1254
        HeapFree(GetProcessHeap(), 0, This);
    }

    return ref;
}

1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
static void user_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
    PngEncoder *This = ppng_get_io_ptr(png_ptr);
    HRESULT hr;
    ULONG byteswritten;

    hr = IStream_Write(This->stream, data, length, &byteswritten);
    if (FAILED(hr) || byteswritten != length)
    {
        ppng_error(png_ptr, "failed writing data");
    }
}

static void user_flush(png_structp png_ptr)
{
}

1272 1273 1274
static HRESULT WINAPI PngEncoder_Initialize(IWICBitmapEncoder *iface,
    IStream *pIStream, WICBitmapEncoderCacheOption cacheOption)
{
1275
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1276
    jmp_buf jmpbuf;
1277 1278 1279

    TRACE("(%p,%p,%u)\n", iface, pIStream, cacheOption);

1280 1281
    EnterCriticalSection(&This->lock);

1282
    if (This->png_ptr)
1283 1284
    {
        LeaveCriticalSection(&This->lock);
1285
        return WINCODEC_ERR_WRONGSTATE;
1286
    }
1287 1288 1289 1290

    /* initialize libpng */
    This->png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (!This->png_ptr)
1291 1292
    {
        LeaveCriticalSection(&This->lock);
1293
        return E_FAIL;
1294
    }
1295 1296 1297 1298

    This->info_ptr = ppng_create_info_struct(This->png_ptr);
    if (!This->info_ptr)
    {
1299
        ppng_destroy_write_struct(&This->png_ptr, NULL);
1300
        This->png_ptr = NULL;
1301
        LeaveCriticalSection(&This->lock);
1302 1303 1304 1305 1306 1307 1308
        return E_FAIL;
    }

    IStream_AddRef(pIStream);
    This->stream = pIStream;

    /* set up setjmp/longjmp error handling */
1309
    if (setjmp(jmpbuf))
1310 1311 1312 1313 1314
    {
        ppng_destroy_write_struct(&This->png_ptr, &This->info_ptr);
        This->png_ptr = NULL;
        IStream_Release(This->stream);
        This->stream = NULL;
1315
        LeaveCriticalSection(&This->lock);
1316 1317
        return E_FAIL;
    }
1318
    ppng_set_error_fn(This->png_ptr, &jmpbuf, user_error_fn, user_warning_fn);
1319 1320 1321 1322

    /* set up custom i/o handling */
    ppng_set_write_fn(This->png_ptr, This, user_write_data, user_flush);

1323 1324
    LeaveCriticalSection(&This->lock);

1325
    return S_OK;
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
}

static HRESULT WINAPI PngEncoder_GetContainerFormat(IWICBitmapEncoder *iface,
    GUID *pguidContainerFormat)
{
    FIXME("(%p,%s): stub\n", iface, debugstr_guid(pguidContainerFormat));
    return E_NOTIMPL;
}

static HRESULT WINAPI PngEncoder_GetEncoderInfo(IWICBitmapEncoder *iface,
    IWICBitmapEncoderInfo **ppIEncoderInfo)
{
    FIXME("(%p,%p): stub\n", iface, ppIEncoderInfo);
    return E_NOTIMPL;
}

static HRESULT WINAPI PngEncoder_SetColorContexts(IWICBitmapEncoder *iface,
    UINT cCount, IWICColorContext **ppIColorContext)
{
    FIXME("(%p,%u,%p): stub\n", iface, cCount, ppIColorContext);
    return E_NOTIMPL;
}

static HRESULT WINAPI PngEncoder_SetPalette(IWICBitmapEncoder *iface, IWICPalette *pIPalette)
{
    TRACE("(%p,%p)\n", iface, pIPalette);
    return WINCODEC_ERR_UNSUPPORTEDOPERATION;
}

static HRESULT WINAPI PngEncoder_SetThumbnail(IWICBitmapEncoder *iface, IWICBitmapSource *pIThumbnail)
{
    TRACE("(%p,%p)\n", iface, pIThumbnail);
    return WINCODEC_ERR_UNSUPPORTEDOPERATION;
}

static HRESULT WINAPI PngEncoder_SetPreview(IWICBitmapEncoder *iface, IWICBitmapSource *pIPreview)
{
    TRACE("(%p,%p)\n", iface, pIPreview);
    return WINCODEC_ERR_UNSUPPORTEDOPERATION;
}

static HRESULT WINAPI PngEncoder_CreateNewFrame(IWICBitmapEncoder *iface,
    IWICBitmapFrameEncode **ppIFrameEncode, IPropertyBag2 **ppIEncoderOptions)
{
1370
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1371 1372 1373
    HRESULT hr;
    TRACE("(%p,%p,%p)\n", iface, ppIFrameEncode, ppIEncoderOptions);

1374 1375
    EnterCriticalSection(&This->lock);

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 1390 1391 1392 1393
    if (FAILED(hr))
    {
        LeaveCriticalSection(&This->lock);
        return hr;
    }
1394 1395 1396

    This->frame_count = 1;

1397 1398
    LeaveCriticalSection(&This->lock);

1399
    IWICBitmapEncoder_AddRef(iface);
1400
    *ppIFrameEncode = &This->IWICBitmapFrameEncode_iface;
1401 1402

    return S_OK;
1403 1404 1405 1406
}

static HRESULT WINAPI PngEncoder_Commit(IWICBitmapEncoder *iface)
{
1407
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1408 1409
    TRACE("(%p)\n", iface);

1410 1411
    EnterCriticalSection(&This->lock);

1412
    if (!This->frame_committed || This->committed)
1413 1414
    {
        LeaveCriticalSection(&This->lock);
1415
        return WINCODEC_ERR_WRONGSTATE;
1416
    }
1417 1418 1419

    This->committed = TRUE;

1420
    LeaveCriticalSection(&This->lock);
1421

1422
    return S_OK;
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
}

static HRESULT WINAPI PngEncoder_GetMetadataQueryWriter(IWICBitmapEncoder *iface,
    IWICMetadataQueryWriter **ppIMetadataQueryWriter)
{
    FIXME("(%p,%p): stub\n", iface, ppIMetadataQueryWriter);
    return E_NOTIMPL;
}

static const IWICBitmapEncoderVtbl PngEncoder_Vtbl = {
    PngEncoder_QueryInterface,
    PngEncoder_AddRef,
    PngEncoder_Release,
    PngEncoder_Initialize,
    PngEncoder_GetContainerFormat,
    PngEncoder_GetEncoderInfo,
    PngEncoder_SetColorContexts,
    PngEncoder_SetPalette,
    PngEncoder_SetThumbnail,
    PngEncoder_SetPreview,
    PngEncoder_CreateNewFrame,
    PngEncoder_Commit,
    PngEncoder_GetMetadataQueryWriter
};

HRESULT PngEncoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
{
    PngEncoder *This;
    HRESULT ret;

    TRACE("(%p,%s,%p)\n", pUnkOuter, debugstr_guid(iid), ppv);

    *ppv = NULL;

    if (pUnkOuter) return CLASS_E_NOAGGREGATION;

    if (!libpng_handle && !load_libpng())
    {
        ERR("Failed writing PNG because unable to find %s\n",SONAME_LIBPNG);
        return E_FAIL;
    }

    This = HeapAlloc(GetProcessHeap(), 0, sizeof(PngEncoder));
    if (!This) return E_OUTOFMEMORY;

1468 1469
    This->IWICBitmapEncoder_iface.lpVtbl = &PngEncoder_Vtbl;
    This->IWICBitmapFrameEncode_iface.lpVtbl = &PngEncoder_FrameVtbl;
1470
    This->ref = 1;
1471 1472 1473
    This->png_ptr = NULL;
    This->info_ptr = NULL;
    This->stream = NULL;
1474
    This->frame_count = 0;
1475
    This->frame_initialized = FALSE;
1476 1477
    This->format = NULL;
    This->info_written = FALSE;
1478 1479
    This->width = 0;
    This->height = 0;
1480 1481
    This->xres = 0.0;
    This->yres = 0.0;
1482
    This->lines_written = 0;
1483
    This->frame_committed = FALSE;
1484
    This->committed = FALSE;
1485 1486
    InitializeCriticalSection(&This->lock);
    This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": PngEncoder.lock");
1487 1488 1489 1490 1491 1492 1493

    ret = IUnknown_QueryInterface((IUnknown*)This, iid, ppv);
    IUnknown_Release((IUnknown*)This);

    return ret;
}

1494 1495 1496 1497
#else /* !HAVE_PNG_H */

HRESULT PngDecoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
{
1498
    ERR("Trying to load PNG picture, but PNG support is not compiled in.\n");
1499 1500 1501
    return E_FAIL;
}

1502 1503
HRESULT PngEncoder_CreateInstance(IUnknown *pUnkOuter, REFIID iid, void** ppv)
{
1504
    ERR("Trying to save PNG picture, but PNG support is not compiled in.\n");
1505 1506 1507
    return E_FAIL;
}

1508
#endif