pngformat.c 61.4 KB
Newer Older
1 2
/*
 * Copyright 2009 Vincent Povirk for CodeWeavers
3
 * Copyright 2016 Dmitry Timoshkov
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
 *
 * 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

29
#define NONAMELESSUNION
30 31 32 33 34 35 36 37 38 39 40 41 42
#define COBJMACROS

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

#include "wincodecs_private.h"

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

WINE_DEFAULT_DEBUG_CHANNEL(wincodecs);

43 44 45 46 47
static inline ULONG read_ulong_be(BYTE* data)
{
    return data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3];
}

48 49 50 51 52 53 54 55 56 57 58 59 60 61
static HRESULT read_png_chunk(IStream *stream, BYTE *type, BYTE **data, ULONG *data_size)
{
    BYTE header[8];
    HRESULT hr;
    ULONG bytesread;

    hr = IStream_Read(stream, header, 8, &bytesread);
    if (FAILED(hr) || bytesread < 8)
    {
        if (SUCCEEDED(hr))
            hr = E_FAIL;
        return hr;
    }

62
    *data_size = read_ulong_be(&header[0]);
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

    memcpy(type, &header[4], 4);

    if (data)
    {
        *data = HeapAlloc(GetProcessHeap(), 0, *data_size);
        if (!*data)
            return E_OUTOFMEMORY;

        hr = IStream_Read(stream, *data, *data_size, &bytesread);

        if (FAILED(hr) || bytesread < *data_size)
        {
            if (SUCCEEDED(hr))
                hr = E_FAIL;
            HeapFree(GetProcessHeap(), 0, *data);
            *data = NULL;
            return hr;
        }

83
        /* Windows ignores CRC of the chunk */
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    }

    return S_OK;
}

static HRESULT LoadTextMetadata(IStream *stream, const GUID *preferred_vendor,
    DWORD persist_options, MetadataItem **items, DWORD *item_count)
{
    HRESULT hr;
    BYTE type[4];
    BYTE *data;
    ULONG data_size;
    ULONG name_len, value_len;
    BYTE *name_end_ptr;
    LPSTR name, value;
    MetadataItem *result;

    hr = read_png_chunk(stream, type, &data, &data_size);
    if (FAILED(hr)) return hr;

    name_end_ptr = memchr(data, 0, data_size);

    name_len = name_end_ptr - data;

    if (!name_end_ptr || name_len > 79)
    {
        HeapFree(GetProcessHeap(), 0, data);
        return E_FAIL;
    }

    value_len = data_size - name_len - 1;

116
    result = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MetadataItem));
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    name = HeapAlloc(GetProcessHeap(), 0, name_len + 1);
    value = HeapAlloc(GetProcessHeap(), 0, value_len + 1);
    if (!result || !name || !value)
    {
        HeapFree(GetProcessHeap(), 0, data);
        HeapFree(GetProcessHeap(), 0, result);
        HeapFree(GetProcessHeap(), 0, name);
        HeapFree(GetProcessHeap(), 0, value);
        return E_OUTOFMEMORY;
    }

    PropVariantInit(&result[0].schema);
    PropVariantInit(&result[0].id);
    PropVariantInit(&result[0].value);

    memcpy(name, data, name_len + 1);
    memcpy(value, name_end_ptr + 1, value_len);
    value[value_len] = 0;

    result[0].id.vt = VT_LPSTR;
137
    result[0].id.u.pszVal = name;
138
    result[0].value.vt = VT_LPSTR;
139
    result[0].value.u.pszVal = value;
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

    *items = result;
    *item_count = 1;

    HeapFree(GetProcessHeap(), 0, data);

    return S_OK;
}

static const MetadataHandlerVtbl TextReader_Vtbl = {
    0,
    &CLSID_WICPngTextMetadataReader,
    LoadTextMetadata
};

155
HRESULT PngTextReader_CreateInstance(REFIID iid, void** ppv)
156
{
157
    return MetadataReader_Create(&TextReader_Vtbl, iid, ppv);
158 159
}

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
static HRESULT LoadGamaMetadata(IStream *stream, const GUID *preferred_vendor,
    DWORD persist_options, MetadataItem **items, DWORD *item_count)
{
    HRESULT hr;
    BYTE type[4];
    BYTE *data;
    ULONG data_size;
    ULONG gamma;
    static const WCHAR ImageGamma[] = {'I','m','a','g','e','G','a','m','m','a',0};
    LPWSTR name;
    MetadataItem *result;

    hr = read_png_chunk(stream, type, &data, &data_size);
    if (FAILED(hr)) return hr;

    if (data_size < 4)
    {
        HeapFree(GetProcessHeap(), 0, data);
        return E_FAIL;
    }

    gamma = read_ulong_be(data);

    HeapFree(GetProcessHeap(), 0, data);

    result = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MetadataItem));
    name = HeapAlloc(GetProcessHeap(), 0, sizeof(ImageGamma));
    if (!result || !name)
    {
        HeapFree(GetProcessHeap(), 0, result);
        HeapFree(GetProcessHeap(), 0, name);
        return E_OUTOFMEMORY;
    }

    PropVariantInit(&result[0].schema);
    PropVariantInit(&result[0].id);
    PropVariantInit(&result[0].value);

    memcpy(name, ImageGamma, sizeof(ImageGamma));

    result[0].id.vt = VT_LPWSTR;
    result[0].id.u.pwszVal = name;
    result[0].value.vt = VT_UI4;
    result[0].value.u.ulVal = gamma;

    *items = result;
    *item_count = 1;

    return S_OK;
}

static const MetadataHandlerVtbl GamaReader_Vtbl = {
    0,
    &CLSID_WICPngGamaMetadataReader,
    LoadGamaMetadata
};

HRESULT PngGamaReader_CreateInstance(REFIID iid, void** ppv)
{
    return MetadataReader_Create(&GamaReader_Vtbl, iid, ppv);
}

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
static HRESULT LoadChrmMetadata(IStream *stream, const GUID *preferred_vendor,
    DWORD persist_options, MetadataItem **items, DWORD *item_count)
{
    HRESULT hr;
    BYTE type[4];
    BYTE *data;
    ULONG data_size;
    static const WCHAR names[8][12] = {
        {'W','h','i','t','e','P','o','i','n','t','X',0},
        {'W','h','i','t','e','P','o','i','n','t','Y',0},
        {'R','e','d','X',0},
        {'R','e','d','Y',0},
        {'G','r','e','e','n','X',0},
        {'G','r','e','e','n','Y',0},
        {'B','l','u','e','X',0},
        {'B','l','u','e','Y',0},
    };
    LPWSTR dyn_names[8] = {0};
    MetadataItem *result;
    int i;

    hr = read_png_chunk(stream, type, &data, &data_size);
    if (FAILED(hr)) return hr;

    if (data_size < 32)
    {
        HeapFree(GetProcessHeap(), 0, data);
        return E_FAIL;
    }

    result = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MetadataItem)*8);
    for (i=0; i<8; i++)
    {
        dyn_names[i] = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR)*(lstrlenW(names[i])+1));
        if (!dyn_names[i]) break;
    }
    if (!result || i < 8)
    {
        HeapFree(GetProcessHeap(), 0, result);
        for (i=0; i<8; i++)
            HeapFree(GetProcessHeap(), 0, dyn_names[i]);
        HeapFree(GetProcessHeap(), 0, data);
        return E_OUTOFMEMORY;
    }

    for (i=0; i<8; i++)
    {
        PropVariantInit(&result[i].schema);

        PropVariantInit(&result[i].id);
        result[i].id.vt = VT_LPWSTR;
        result[i].id.u.pwszVal = dyn_names[i];
        lstrcpyW(dyn_names[i], names[i]);

        PropVariantInit(&result[i].value);
        result[i].value.vt = VT_UI4;
        result[i].value.u.ulVal = read_ulong_be(&data[i*4]);
    }

    *items = result;
    *item_count = 8;

    HeapFree(GetProcessHeap(), 0, data);

    return S_OK;
}

static const MetadataHandlerVtbl ChrmReader_Vtbl = {
    0,
    &CLSID_WICPngChrmMetadataReader,
    LoadChrmMetadata
};

HRESULT PngChrmReader_CreateInstance(REFIID iid, void** ppv)
{
    return MetadataReader_Create(&ChrmReader_Vtbl, iid, ppv);
}

300 301 302 303 304 305
#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);
306
MAKE_FUNCPTR(png_create_write_struct);
307
MAKE_FUNCPTR(png_destroy_read_struct);
308
MAKE_FUNCPTR(png_destroy_write_struct);
309 310 311
MAKE_FUNCPTR(png_error);
MAKE_FUNCPTR(png_get_bit_depth);
MAKE_FUNCPTR(png_get_color_type);
312
MAKE_FUNCPTR(png_get_error_ptr);
313
MAKE_FUNCPTR(png_get_iCCP);
314 315 316
MAKE_FUNCPTR(png_get_image_height);
MAKE_FUNCPTR(png_get_image_width);
MAKE_FUNCPTR(png_get_io_ptr);
317
MAKE_FUNCPTR(png_get_pHYs);
318 319
MAKE_FUNCPTR(png_get_PLTE);
MAKE_FUNCPTR(png_get_tRNS);
320
MAKE_FUNCPTR(png_set_bgr);
321
MAKE_FUNCPTR(png_set_crc_action);
322
MAKE_FUNCPTR(png_set_error_fn);
323
MAKE_FUNCPTR(png_set_filler);
324
MAKE_FUNCPTR(png_set_filter);
325
MAKE_FUNCPTR(png_set_gray_to_rgb);
326
MAKE_FUNCPTR(png_set_interlace_handling);
327 328
MAKE_FUNCPTR(png_set_IHDR);
MAKE_FUNCPTR(png_set_pHYs);
329
MAKE_FUNCPTR(png_set_PLTE);
330
MAKE_FUNCPTR(png_set_read_fn);
331
MAKE_FUNCPTR(png_set_strip_16);
332
MAKE_FUNCPTR(png_set_tRNS);
333
MAKE_FUNCPTR(png_set_tRNS_to_alpha);
334
MAKE_FUNCPTR(png_set_write_fn);
335 336 337
MAKE_FUNCPTR(png_read_end);
MAKE_FUNCPTR(png_read_image);
MAKE_FUNCPTR(png_read_info);
338
MAKE_FUNCPTR(png_write_end);
339 340
MAKE_FUNCPTR(png_write_info);
MAKE_FUNCPTR(png_write_rows);
341 342
#undef MAKE_FUNCPTR

343 344 345 346 347 348 349 350 351 352
static CRITICAL_SECTION init_png_cs;
static CRITICAL_SECTION_DEBUG init_png_cs_debug =
{
    0, 0, &init_png_cs,
    { &init_png_cs_debug.ProcessLocksList,
      &init_png_cs_debug.ProcessLocksList },
    0, 0, { (DWORD_PTR)(__FILE__ ": init_png_cs") }
};
static CRITICAL_SECTION init_png_cs = { &init_png_cs_debug, -1, 0, 0, 0, 0 };

353 354 355
static const WCHAR wszPngInterlaceOption[] = {'I','n','t','e','r','l','a','c','e','O','p','t','i','o','n',0};
static const WCHAR wszPngFilterOption[] = {'F','i','l','t','e','r','O','p','t','i','o','n',0};

356 357
static void *load_libpng(void)
{
358 359 360 361 362
    void *result;

    EnterCriticalSection(&init_png_cs);

    if(!libpng_handle && (libpng_handle = wine_dlopen(SONAME_LIBPNG, RTLD_NOW, NULL, 0)) != NULL) {
363 364 365 366

#define LOAD_FUNCPTR(f) \
    if((p##f = wine_dlsym(libpng_handle, #f, NULL, 0)) == NULL) { \
        libpng_handle = NULL; \
367
        LeaveCriticalSection(&init_png_cs); \
368 369 370 371
        return NULL; \
    }
        LOAD_FUNCPTR(png_create_read_struct);
        LOAD_FUNCPTR(png_create_info_struct);
372
        LOAD_FUNCPTR(png_create_write_struct);
373
        LOAD_FUNCPTR(png_destroy_read_struct);
374
        LOAD_FUNCPTR(png_destroy_write_struct);
375 376 377
        LOAD_FUNCPTR(png_error);
        LOAD_FUNCPTR(png_get_bit_depth);
        LOAD_FUNCPTR(png_get_color_type);
378
        LOAD_FUNCPTR(png_get_error_ptr);
379
        LOAD_FUNCPTR(png_get_iCCP);
380 381 382
        LOAD_FUNCPTR(png_get_image_height);
        LOAD_FUNCPTR(png_get_image_width);
        LOAD_FUNCPTR(png_get_io_ptr);
383
        LOAD_FUNCPTR(png_get_pHYs);
384 385
        LOAD_FUNCPTR(png_get_PLTE);
        LOAD_FUNCPTR(png_get_tRNS);
386
        LOAD_FUNCPTR(png_set_bgr);
387
        LOAD_FUNCPTR(png_set_crc_action);
388
        LOAD_FUNCPTR(png_set_error_fn);
389
        LOAD_FUNCPTR(png_set_filler);
390
        LOAD_FUNCPTR(png_set_filter);
391
        LOAD_FUNCPTR(png_set_gray_to_rgb);
392
        LOAD_FUNCPTR(png_set_interlace_handling);
393 394
        LOAD_FUNCPTR(png_set_IHDR);
        LOAD_FUNCPTR(png_set_pHYs);
395
        LOAD_FUNCPTR(png_set_PLTE);
396
        LOAD_FUNCPTR(png_set_read_fn);
397
        LOAD_FUNCPTR(png_set_strip_16);
398
        LOAD_FUNCPTR(png_set_tRNS);
399
        LOAD_FUNCPTR(png_set_tRNS_to_alpha);
400
        LOAD_FUNCPTR(png_set_write_fn);
401 402 403
        LOAD_FUNCPTR(png_read_end);
        LOAD_FUNCPTR(png_read_image);
        LOAD_FUNCPTR(png_read_info);
404
        LOAD_FUNCPTR(png_write_end);
405 406
        LOAD_FUNCPTR(png_write_info);
        LOAD_FUNCPTR(png_write_rows);
407 408 409

#undef LOAD_FUNCPTR
    }
410 411 412 413 414 415

    result = libpng_handle;

    LeaveCriticalSection(&init_png_cs);

    return result;
416 417
}

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
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));
}

435 436 437 438 439
typedef struct {
    ULARGE_INTEGER ofs, len;
    IWICMetadataReader* reader;
} metadata_block_info;

440
typedef struct {
441 442
    IWICBitmapDecoder IWICBitmapDecoder_iface;
    IWICBitmapFrameDecode IWICBitmapFrameDecode_iface;
443
    IWICMetadataBlockReader IWICMetadataBlockReader_iface;
444
    LONG ref;
445
    IStream *stream;
446 447
    png_structp png_ptr;
    png_infop info_ptr;
448
    png_infop end_info;
449 450 451 452 453 454
    BOOL initialized;
    int bpp;
    int width, height;
    UINT stride;
    const WICPixelFormatGUID *format;
    BYTE *image_bits;
455
    CRITICAL_SECTION lock; /* must be held when png structures are accessed or initialized is set */
456 457
    ULONG metadata_count;
    metadata_block_info* metadata_blocks;
458 459
} PngDecoder;

460
static inline PngDecoder *impl_from_IWICBitmapDecoder(IWICBitmapDecoder *iface)
461
{
462 463 464 465 466 467
    return CONTAINING_RECORD(iface, PngDecoder, IWICBitmapDecoder_iface);
}

static inline PngDecoder *impl_from_IWICBitmapFrameDecode(IWICBitmapFrameDecode *iface)
{
    return CONTAINING_RECORD(iface, PngDecoder, IWICBitmapFrameDecode_iface);
468 469
}

470 471 472 473 474
static inline PngDecoder *impl_from_IWICMetadataBlockReader(IWICMetadataBlockReader *iface)
{
    return CONTAINING_RECORD(iface, PngDecoder, IWICMetadataBlockReader_iface);
}

475 476
static const IWICBitmapFrameDecodeVtbl PngDecoder_FrameVtbl;

477 478 479
static HRESULT WINAPI PngDecoder_QueryInterface(IWICBitmapDecoder *iface, REFIID iid,
    void **ppv)
{
480
    PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
481 482 483 484 485 486
    TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);

    if (!ppv) return E_INVALIDARG;

    if (IsEqualIID(&IID_IUnknown, iid) || IsEqualIID(&IID_IWICBitmapDecoder, iid))
    {
487
        *ppv = &This->IWICBitmapDecoder_iface;
488 489 490 491 492 493 494 495 496 497 498 499 500
    }
    else
    {
        *ppv = NULL;
        return E_NOINTERFACE;
    }

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

static ULONG WINAPI PngDecoder_AddRef(IWICBitmapDecoder *iface)
{
501
    PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
502 503 504 505 506 507 508 509 510
    ULONG ref = InterlockedIncrement(&This->ref);

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

    return ref;
}

static ULONG WINAPI PngDecoder_Release(IWICBitmapDecoder *iface)
{
511
    PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
512
    ULONG ref = InterlockedDecrement(&This->ref);
513
    ULONG i;
514 515 516 517 518

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

    if (ref == 0)
    {
519 520
        if (This->stream)
            IStream_Release(This->stream);
521
        if (This->png_ptr)
522
            ppng_destroy_read_struct(&This->png_ptr, &This->info_ptr, &This->end_info);
523 524
        This->lock.DebugInfo->Spare[0] = 0;
        DeleteCriticalSection(&This->lock);
525
        HeapFree(GetProcessHeap(), 0, This->image_bits);
526 527 528 529 530 531
        for (i=0; i<This->metadata_count; i++)
        {
            if (This->metadata_blocks[i].reader)
                IWICMetadataReader_Release(This->metadata_blocks[i].reader);
        }
        HeapFree(GetProcessHeap(), 0, This->metadata_blocks);
532 533 534 535 536 537
        HeapFree(GetProcessHeap(), 0, This);
    }

    return ref;
}

538 539
static HRESULT WINAPI PngDecoder_QueryCapability(IWICBitmapDecoder *iface, IStream *stream,
    DWORD *capability)
540
{
541 542 543 544 545 546 547 548 549 550 551 552 553
    HRESULT hr;

    TRACE("(%p,%p,%p)\n", iface, stream, capability);

    if (!stream || !capability) return E_INVALIDARG;

    hr = IWICBitmapDecoder_Initialize(iface, stream, WICDecodeMetadataCacheOnDemand);
    if (hr != S_OK) return hr;

    *capability = WICBitmapDecoderCapabilityCanDecodeAllImages |
                  WICBitmapDecoderCapabilityCanDecodeSomeImages;
    /* FIXME: WICBitmapDecoderCapabilityCanEnumerateMetadata */
    return S_OK;
554 555
}

556
static void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
557
{
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
    IStream *stream = ppng_get_io_ptr(png_ptr);
    HRESULT hr;
    ULONG bytesread;

    hr = IStream_Read(stream, data, length, &bytesread);
    if (FAILED(hr) || bytesread != length)
    {
        ppng_error(png_ptr, "failed reading data");
    }
}

static HRESULT WINAPI PngDecoder_Initialize(IWICBitmapDecoder *iface, IStream *pIStream,
    WICDecodeOptions cacheOptions)
{
    PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
    LARGE_INTEGER seek;
    HRESULT hr=S_OK;
    png_bytep *row_pointers=NULL;
    UINT image_size;
    UINT i;
578
    int color_type, bit_depth;
579 580 581 582
    png_bytep trans;
    int num_trans;
    png_uint_32 transparency;
    png_color_16p trans_values;
583
    jmp_buf jmpbuf;
584 585 586 587
    BYTE chunk_type[4];
    ULONG chunk_size;
    ULARGE_INTEGER chunk_start;
    ULONG metadata_blocks_size = 0;
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610

    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)
    {
        hr = E_FAIL;
        goto end;
    }

    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;
    }

    This->end_info = ppng_create_info_struct(This->png_ptr);
611
    if (!This->end_info)
612 613 614 615 616 617
    {
        ppng_destroy_read_struct(&This->png_ptr, &This->info_ptr, NULL);
        This->png_ptr = NULL;
        hr = E_FAIL;
        goto end;
    }
618

619 620 621 622 623 624 625 626 627
    /* set up setjmp/longjmp error handling */
    if (setjmp(jmpbuf))
    {
        ppng_destroy_read_struct(&This->png_ptr, &This->info_ptr, &This->end_info);
        HeapFree(GetProcessHeap(), 0, row_pointers);
        This->png_ptr = NULL;
        hr = E_FAIL;
        goto end;
    }
628
    ppng_set_error_fn(This->png_ptr, jmpbuf, user_error_fn, user_warning_fn);
629
    ppng_set_crc_action(This->png_ptr, PNG_CRC_QUIET_USE, PNG_CRC_QUIET_USE);
630 631 632 633 634 635 636 637 638 639 640

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

    /* set up custom i/o handling */
    ppng_set_read_fn(This->png_ptr, pIStream, user_read_data);

    /* read the header */
    ppng_read_info(This->png_ptr, This->info_ptr);
641 642 643 644 645

    /* 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);

646 647 648
    /* check for color-keyed alpha */
    transparency = ppng_get_tRNS(This->png_ptr, This->info_ptr, &trans, &num_trans, &trans_values);

649 650
    if (transparency && (color_type == PNG_COLOR_TYPE_RGB ||
        (color_type == PNG_COLOR_TYPE_GRAY && bit_depth == 16)))
651 652 653 654 655 656 657 658
    {
        /* expand to RGBA */
        if (color_type == PNG_COLOR_TYPE_GRAY)
            ppng_set_gray_to_rgb(This->png_ptr);
        ppng_set_tRNS_to_alpha(This->png_ptr);
        color_type = PNG_COLOR_TYPE_RGB_ALPHA;
    }

659 660 661 662 663
    switch (color_type)
    {
    case PNG_COLOR_TYPE_GRAY_ALPHA:
        /* WIC does not support grayscale alpha formats so use RGBA */
        ppng_set_gray_to_rgb(This->png_ptr);
664
        /* fall through */
665 666 667 668 669 670 671 672 673 674 675
    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);
676 677
            hr = E_FAIL;
            goto end;
678 679
        }
        break;
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
    case PNG_COLOR_TYPE_GRAY:
        This->bpp = bit_depth;
        if (!transparency)
        {
            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);
                hr = E_FAIL;
                goto end;
            }
            break;
        }
        /* else fall through */
699 700 701 702 703 704 705 706 707 708
    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);
709 710
            hr = E_FAIL;
            goto end;
711 712 713 714 715 716 717 718 719 720 721 722 723
        }
        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);
724 725
            hr = E_FAIL;
            goto end;
726 727 728 729
        }
        break;
    default:
        ERR("invalid color type %i\n", color_type);
730 731
        hr = E_FAIL;
        goto end;
732 733
    }

734
    /* read the image data */
735 736
    This->width = ppng_get_image_width(This->png_ptr, This->info_ptr);
    This->height = ppng_get_image_height(This->png_ptr, This->info_ptr);
737
    This->stride = (This->width * This->bpp + 7) / 8;
738 739 740
    image_size = This->stride * This->height;

    This->image_bits = HeapAlloc(GetProcessHeap(), 0, image_size);
741 742 743 744 745
    if (!This->image_bits)
    {
        hr = E_OUTOFMEMORY;
        goto end;
    }
746

747 748
    row_pointers = HeapAlloc(GetProcessHeap(), 0, sizeof(png_bytep)*This->height);
    if (!row_pointers)
749
    {
750
        hr = E_OUTOFMEMORY;
751 752
        goto end;
    }
753

754 755
    for (i=0; i<This->height; i++)
        row_pointers[i] = This->image_bits + i * This->stride;
756

757
    ppng_read_image(This->png_ptr, row_pointers);
758

759 760
    HeapFree(GetProcessHeap(), 0, row_pointers);
    row_pointers = NULL;
761

762
    ppng_read_end(This->png_ptr, This->end_info);
763

764 765 766 767 768
    /* Find the metadata chunks in the file. */
    seek.QuadPart = 8;

    do
    {
769 770 771
        hr = IStream_Seek(pIStream, seek, STREAM_SEEK_SET, &chunk_start);
        if (FAILED(hr)) goto end;

772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
        hr = read_png_chunk(pIStream, chunk_type, NULL, &chunk_size);
        if (FAILED(hr)) goto end;

        if (chunk_type[0] >= 'a' && chunk_type[0] <= 'z' &&
            memcmp(chunk_type, "tRNS", 4) && memcmp(chunk_type, "pHYs", 4))
        {
            /* This chunk is considered metadata. */
            if (This->metadata_count == metadata_blocks_size)
            {
                metadata_block_info* new_metadata_blocks;
                ULONG new_metadata_blocks_size;

                new_metadata_blocks_size = 4 + metadata_blocks_size * 2;
                new_metadata_blocks = HeapAlloc(GetProcessHeap(), 0,
                    new_metadata_blocks_size * sizeof(*new_metadata_blocks));

                if (!new_metadata_blocks)
                {
                    hr = E_OUTOFMEMORY;
                    goto end;
                }

                memcpy(new_metadata_blocks, This->metadata_blocks,
                    This->metadata_count * sizeof(*new_metadata_blocks));

                HeapFree(GetProcessHeap(), 0, This->metadata_blocks);
                This->metadata_blocks = new_metadata_blocks;
                metadata_blocks_size = new_metadata_blocks_size;
            }

            This->metadata_blocks[This->metadata_count].ofs = chunk_start;
            This->metadata_blocks[This->metadata_count].len.QuadPart = chunk_size + 12;
            This->metadata_blocks[This->metadata_count].reader = NULL;
            This->metadata_count++;
        }

        seek.QuadPart = chunk_start.QuadPart + chunk_size + 12; /* skip data and CRC */
    } while (memcmp(chunk_type, "IEND", 4));

811 812 813
    This->stream = pIStream;
    IStream_AddRef(This->stream);

814
    This->initialized = TRUE;
815

816 817 818 819
end:
    LeaveCriticalSection(&This->lock);

    return hr;
820 821 822 823 824
}

static HRESULT WINAPI PngDecoder_GetContainerFormat(IWICBitmapDecoder *iface,
    GUID *pguidContainerFormat)
{
825 826
    memcpy(pguidContainerFormat, &GUID_ContainerFormatPng, sizeof(GUID));
    return S_OK;
827 828 829 830 831
}

static HRESULT WINAPI PngDecoder_GetDecoderInfo(IWICBitmapDecoder *iface,
    IWICBitmapDecoderInfo **ppIDecoderInfo)
{
832 833
    TRACE("(%p,%p)\n", iface, ppIDecoderInfo);

834
    return get_decoder_info(&CLSID_WICPngDecoder, ppIDecoderInfo);
835 836 837
}

static HRESULT WINAPI PngDecoder_CopyPalette(IWICBitmapDecoder *iface,
838
    IWICPalette *palette)
839
{
840 841
    TRACE("(%p,%p)\n", iface, palette);
    return WINCODEC_ERR_PALETTEUNAVAILABLE;
842 843 844 845 846 847 848 849 850 851 852 853
}

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)
{
854 855 856 857 858 859
    TRACE("(%p,%p)\n", iface, ppIBitmapSource);

    if (!ppIBitmapSource) return E_INVALIDARG;

    *ppIBitmapSource = NULL;
    return WINCODEC_ERR_UNSUPPORTEDOPERATION;
860 861 862 863 864
}

static HRESULT WINAPI PngDecoder_GetColorContexts(IWICBitmapDecoder *iface,
    UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
{
865
    TRACE("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);
866
    return WINCODEC_ERR_UNSUPPORTEDOPERATION;
867 868 869 870 871 872
}

static HRESULT WINAPI PngDecoder_GetThumbnail(IWICBitmapDecoder *iface,
    IWICBitmapSource **ppIThumbnail)
{
    TRACE("(%p,%p)\n", iface, ppIThumbnail);
873 874 875 876

    if (!ppIThumbnail) return E_INVALIDARG;

    *ppIThumbnail = NULL;
877 878 879 880 881 882
    return WINCODEC_ERR_CODECNOTHUMBNAIL;
}

static HRESULT WINAPI PngDecoder_GetFrameCount(IWICBitmapDecoder *iface,
    UINT *pCount)
{
883 884
    if (!pCount) return E_INVALIDARG;

885 886
    *pCount = 1;
    return S_OK;
887 888 889 890 891
}

static HRESULT WINAPI PngDecoder_GetFrame(IWICBitmapDecoder *iface,
    UINT index, IWICBitmapFrameDecode **ppIBitmapFrame)
{
892
    PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
893 894
    TRACE("(%p,%u,%p)\n", iface, index, ppIBitmapFrame);

895
    if (!This->initialized) return WINCODEC_ERR_FRAMEMISSING;
896 897 898 899 900

    if (index != 0) return E_INVALIDARG;

    IWICBitmapDecoder_AddRef(iface);

901
    *ppIBitmapFrame = &This->IWICBitmapFrameDecode_iface;
902 903

    return S_OK;
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
}

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
};

923 924 925
static HRESULT WINAPI PngDecoder_Frame_QueryInterface(IWICBitmapFrameDecode *iface, REFIID iid,
    void **ppv)
{
926
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
927 928 929 930 931 932
    if (!ppv) return E_INVALIDARG;

    if (IsEqualIID(&IID_IUnknown, iid) ||
        IsEqualIID(&IID_IWICBitmapSource, iid) ||
        IsEqualIID(&IID_IWICBitmapFrameDecode, iid))
    {
933
        *ppv = &This->IWICBitmapFrameDecode_iface;
934
    }
935 936
    else if (IsEqualIID(&IID_IWICMetadataBlockReader, iid))
    {
937
        *ppv = &This->IWICMetadataBlockReader_iface;
938
    }
939 940 941 942 943 944 945 946 947 948 949 950
    else
    {
        *ppv = NULL;
        return E_NOINTERFACE;
    }

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

static ULONG WINAPI PngDecoder_Frame_AddRef(IWICBitmapFrameDecode *iface)
{
951
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
952
    return IWICBitmapDecoder_AddRef(&This->IWICBitmapDecoder_iface);
953 954 955 956
}

static ULONG WINAPI PngDecoder_Frame_Release(IWICBitmapFrameDecode *iface)
{
957
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
958
    return IWICBitmapDecoder_Release(&This->IWICBitmapDecoder_iface);
959 960 961 962 963
}

static HRESULT WINAPI PngDecoder_Frame_GetSize(IWICBitmapFrameDecode *iface,
    UINT *puiWidth, UINT *puiHeight)
{
964
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
965 966 967 968
    *puiWidth = This->width;
    *puiHeight = This->height;
    TRACE("(%p)->(%u,%u)\n", iface, *puiWidth, *puiHeight);
    return S_OK;
969 970 971 972 973
}

static HRESULT WINAPI PngDecoder_Frame_GetPixelFormat(IWICBitmapFrameDecode *iface,
    WICPixelFormatGUID *pPixelFormat)
{
974
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
975 976 977 978 979
    TRACE("(%p,%p)\n", iface, pPixelFormat);

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

    return S_OK;
980 981 982 983 984
}

static HRESULT WINAPI PngDecoder_Frame_GetResolution(IWICBitmapFrameDecode *iface,
    double *pDpiX, double *pDpiY)
{
985
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
986 987 988
    png_uint_32 ret, xres, yres;
    int unit_type;

989 990
    EnterCriticalSection(&This->lock);

991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
    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;
    }

1004 1005
    LeaveCriticalSection(&This->lock);

1006 1007 1008
    TRACE("(%p)->(%0.2f,%0.2f)\n", iface, *pDpiX, *pDpiY);

    return S_OK;
1009 1010 1011 1012 1013
}

static HRESULT WINAPI PngDecoder_Frame_CopyPalette(IWICBitmapFrameDecode *iface,
    IWICPalette *pIPalette)
{
1014
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
1015
    png_uint_32 ret, color_type, bit_depth;
1016 1017 1018
    png_colorp png_palette;
    int num_palette;
    WICColor palette[256];
1019
    png_bytep trans_alpha;
1020 1021 1022
    int num_trans;
    png_color_16p trans_values;
    int i;
1023
    HRESULT hr=S_OK;
1024 1025 1026

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

1027 1028
    EnterCriticalSection(&This->lock);

1029 1030
    color_type = ppng_get_color_type(This->png_ptr, This->info_ptr);
    bit_depth = ppng_get_bit_depth(This->png_ptr, This->info_ptr);
1031

1032
    if (color_type == PNG_COLOR_TYPE_PALETTE)
1033
    {
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
        ret = ppng_get_PLTE(This->png_ptr, This->info_ptr, &png_palette, &num_palette);
        if (!ret)
        {
            hr = WINCODEC_ERR_PALETTEUNAVAILABLE;
            goto end;
        }

        if (num_palette > 256)
        {
            ERR("palette has %i colors?!\n", num_palette);
            hr = E_FAIL;
            goto end;
        }

        ret = ppng_get_tRNS(This->png_ptr, This->info_ptr, &trans_alpha, &num_trans, &trans_values);
        if (!ret) num_trans = 0;

        for (i=0; i<num_palette; i++)
        {
            BYTE alpha = (i < num_trans) ? trans_alpha[i] : 0xff;
            palette[i] = (alpha << 24 |
                          png_palette[i].red << 16|
                          png_palette[i].green << 8|
                          png_palette[i].blue);
        }
1059
    }
1060 1061
    else if (color_type == PNG_COLOR_TYPE_GRAY) {
        ret = ppng_get_tRNS(This->png_ptr, This->info_ptr, &trans_alpha, &num_trans, &trans_values);
1062

1063 1064 1065 1066 1067
        if (!ret)
        {
            hr = WINCODEC_ERR_PALETTEUNAVAILABLE;
            goto end;
        }
1068

1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
        num_palette = 1 << bit_depth;

        for (i=0; i<num_palette; i++)
        {
            BYTE alpha = (i == trans_values[0].gray) ? 0 : 0xff;
            BYTE val = i * 255 / (num_palette - 1);
            palette[i] = (alpha << 24 | val << 16 | val << 8 | val);
        }
    }
    else
1079
    {
1080
        hr = WINCODEC_ERR_PALETTEUNAVAILABLE;
1081 1082
    }

1083 1084 1085 1086 1087 1088 1089 1090
end:

    LeaveCriticalSection(&This->lock);

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

    return hr;
1091 1092 1093 1094 1095
}

static HRESULT WINAPI PngDecoder_Frame_CopyPixels(IWICBitmapFrameDecode *iface,
    const WICRect *prc, UINT cbStride, UINT cbBufferSize, BYTE *pbBuffer)
{
1096
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
1097 1098 1099 1100 1101
    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);
1102 1103 1104 1105 1106
}

static HRESULT WINAPI PngDecoder_Frame_GetMetadataQueryReader(IWICBitmapFrameDecode *iface,
    IWICMetadataQueryReader **ppIMetadataQueryReader)
{
1107 1108 1109 1110 1111 1112 1113
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);

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

    if (!ppIMetadataQueryReader)
        return E_INVALIDARG;

1114
    return MetadataQueryReader_CreateInstance(&This->IWICMetadataBlockReader_iface, NULL, ppIMetadataQueryReader);
1115 1116 1117 1118 1119
}

static HRESULT WINAPI PngDecoder_Frame_GetColorContexts(IWICBitmapFrameDecode *iface,
    UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
{
1120
    PngDecoder *This = impl_from_IWICBitmapFrameDecode(iface);
1121 1122
    png_charp name;
    BYTE *profile;
1123 1124 1125 1126 1127 1128
    png_uint_32 len;
    int compression_type;
    HRESULT hr;

    TRACE("(%p,%u,%p,%p)\n", iface, cCount, ppIColorContexts, pcActualCount);

1129 1130
    if (!pcActualCount) return E_INVALIDARG;

1131 1132
    EnterCriticalSection(&This->lock);

1133
    if (ppng_get_iCCP(This->png_ptr, This->info_ptr, &name, &compression_type, (void *)&profile, &len))
1134 1135 1136
    {
        if (cCount && ppIColorContexts)
        {
1137
            hr = IWICColorContext_InitializeFromMemory(*ppIColorContexts, profile, len);
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
            if (FAILED(hr))
            {
                LeaveCriticalSection(&This->lock);
                return hr;
            }
        }
        *pcActualCount = 1;
    }
    else
        *pcActualCount = 0;

    LeaveCriticalSection(&This->lock);

    return S_OK;
1152 1153 1154 1155 1156
}

static HRESULT WINAPI PngDecoder_Frame_GetThumbnail(IWICBitmapFrameDecode *iface,
    IWICBitmapSource **ppIThumbnail)
{
1157 1158 1159 1160 1161 1162
    TRACE("(%p,%p)\n", iface, ppIThumbnail);

    if (!ppIThumbnail) return E_INVALIDARG;

    *ppIThumbnail = NULL;
    return WINCODEC_ERR_CODECNOTHUMBNAIL;
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
}

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
};

1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
static HRESULT WINAPI PngDecoder_Block_QueryInterface(IWICMetadataBlockReader *iface, REFIID iid,
    void **ppv)
{
    PngDecoder *This = impl_from_IWICMetadataBlockReader(iface);
    return IWICBitmapFrameDecode_QueryInterface(&This->IWICBitmapFrameDecode_iface, iid, ppv);
}

static ULONG WINAPI PngDecoder_Block_AddRef(IWICMetadataBlockReader *iface)
{
    PngDecoder *This = impl_from_IWICMetadataBlockReader(iface);
1189
    return IWICBitmapDecoder_AddRef(&This->IWICBitmapDecoder_iface);
1190 1191 1192 1193 1194
}

static ULONG WINAPI PngDecoder_Block_Release(IWICMetadataBlockReader *iface)
{
    PngDecoder *This = impl_from_IWICMetadataBlockReader(iface);
1195
    return IWICBitmapDecoder_Release(&This->IWICBitmapDecoder_iface);
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
}

static HRESULT WINAPI PngDecoder_Block_GetContainerFormat(IWICMetadataBlockReader *iface,
    GUID *pguidContainerFormat)
{
    if (!pguidContainerFormat) return E_INVALIDARG;
    memcpy(pguidContainerFormat, &GUID_ContainerFormatPng, sizeof(GUID));
    return S_OK;
}

static HRESULT WINAPI PngDecoder_Block_GetCount(IWICMetadataBlockReader *iface,
    UINT *pcCount)
{
1209 1210
    PngDecoder *This = impl_from_IWICMetadataBlockReader(iface);

1211
    TRACE("%p,%p\n", iface, pcCount);
1212 1213 1214 1215 1216 1217

    if (!pcCount) return E_INVALIDARG;

    *pcCount = This->metadata_count;

    return S_OK;
1218 1219 1220 1221 1222
}

static HRESULT WINAPI PngDecoder_Block_GetReaderByIndex(IWICMetadataBlockReader *iface,
    UINT nIndex, IWICMetadataReader **ppIMetadataReader)
{
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
    PngDecoder *This = impl_from_IWICMetadataBlockReader(iface);
    HRESULT hr;
    IWICComponentFactory* factory;
    IWICStream* stream;

    TRACE("%p,%d,%p\n", iface, nIndex, ppIMetadataReader);

    if (nIndex >= This->metadata_count || !ppIMetadataReader)
        return E_INVALIDARG;

    if (!This->metadata_blocks[nIndex].reader)
    {
        hr = StreamImpl_Create(&stream);

        if (SUCCEEDED(hr))
        {
            hr = IWICStream_InitializeFromIStreamRegion(stream, This->stream,
                This->metadata_blocks[nIndex].ofs, This->metadata_blocks[nIndex].len);

            if (SUCCEEDED(hr))
                hr = ComponentFactory_CreateInstance(&IID_IWICComponentFactory, (void**)&factory);

            if (SUCCEEDED(hr))
            {
                hr = IWICComponentFactory_CreateMetadataReaderFromContainer(factory,
                    &GUID_ContainerFormatPng, NULL, WICMetadataCreationAllowUnknown,
                    (IStream*)stream, &This->metadata_blocks[nIndex].reader);

                IWICComponentFactory_Release(factory);
            }

            IWICStream_Release(stream);
        }

        if (FAILED(hr))
        {
            *ppIMetadataReader = NULL;
            return hr;
        }
    }

    *ppIMetadataReader = This->metadata_blocks[nIndex].reader;
    IWICMetadataReader_AddRef(*ppIMetadataReader);

    return S_OK;
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
}

static HRESULT WINAPI PngDecoder_Block_GetEnumerator(IWICMetadataBlockReader *iface,
    IEnumUnknown **ppIEnumMetadata)
{
    FIXME("%p,%p\n", iface, ppIEnumMetadata);
    return E_NOTIMPL;
}

static const IWICMetadataBlockReaderVtbl PngDecoder_BlockVtbl = {
    PngDecoder_Block_QueryInterface,
    PngDecoder_Block_AddRef,
    PngDecoder_Block_Release,
    PngDecoder_Block_GetContainerFormat,
    PngDecoder_Block_GetCount,
    PngDecoder_Block_GetReaderByIndex,
    PngDecoder_Block_GetEnumerator,
};

1287
HRESULT PngDecoder_CreateInstance(REFIID iid, void** ppv)
1288 1289 1290 1291
{
    PngDecoder *This;
    HRESULT ret;

1292
    TRACE("(%s,%p)\n", debugstr_guid(iid), ppv);
1293 1294 1295

    *ppv = NULL;

1296
    if (!load_libpng())
1297 1298 1299 1300 1301 1302 1303 1304
    {
        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;

1305 1306
    This->IWICBitmapDecoder_iface.lpVtbl = &PngDecoder_Vtbl;
    This->IWICBitmapFrameDecode_iface.lpVtbl = &PngDecoder_FrameVtbl;
1307
    This->IWICMetadataBlockReader_iface.lpVtbl = &PngDecoder_BlockVtbl;
1308
    This->ref = 1;
1309 1310
    This->png_ptr = NULL;
    This->info_ptr = NULL;
1311
    This->end_info = NULL;
1312
    This->stream = NULL;
1313 1314
    This->initialized = FALSE;
    This->image_bits = NULL;
1315 1316
    InitializeCriticalSection(&This->lock);
    This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": PngDecoder.lock");
1317 1318
    This->metadata_count = 0;
    This->metadata_blocks = NULL;
1319

1320 1321
    ret = IWICBitmapDecoder_QueryInterface(&This->IWICBitmapDecoder_iface, iid, ppv);
    IWICBitmapDecoder_Release(&This->IWICBitmapDecoder_iface);
1322 1323 1324 1325

    return ret;
}

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
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[] = {
1336
    {&GUID_WICPixelFormat32bppBGRA, 32, 8, PNG_COLOR_TYPE_RGB_ALPHA, 0, 1},
1337 1338 1339 1340 1341 1342 1343 1344 1345
    {&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_WICPixelFormat48bppRGB, 48, 16, PNG_COLOR_TYPE_RGB, 0, 0},
    {&GUID_WICPixelFormat64bppRGBA, 64, 16, PNG_COLOR_TYPE_RGB_ALPHA, 0, 0},
1346 1347 1348 1349
    {&GUID_WICPixelFormat1bppIndexed, 1, 1, PNG_COLOR_TYPE_PALETTE, 0, 0},
    {&GUID_WICPixelFormat2bppIndexed, 2, 2, PNG_COLOR_TYPE_PALETTE, 0, 0},
    {&GUID_WICPixelFormat4bppIndexed, 4, 4, PNG_COLOR_TYPE_PALETTE, 0, 0},
    {&GUID_WICPixelFormat8bppIndexed, 8, 8, PNG_COLOR_TYPE_PALETTE, 0, 0},
1350 1351 1352
    {NULL},
};

1353
typedef struct PngEncoder {
1354 1355
    IWICBitmapEncoder IWICBitmapEncoder_iface;
    IWICBitmapFrameEncode IWICBitmapFrameEncode_iface;
1356
    LONG ref;
1357 1358 1359
    IStream *stream;
    png_structp png_ptr;
    png_infop info_ptr;
1360
    UINT frame_count;
1361
    BOOL frame_initialized;
1362 1363
    const struct png_pixelformat *format;
    BOOL info_written;
1364
    UINT width, height;
1365
    double xres, yres;
1366
    UINT lines_written;
1367
    BOOL frame_committed;
1368
    BOOL committed;
1369
    CRITICAL_SECTION lock;
1370
    BOOL interlace;
1371
    WICPngFilterOption filter;
1372 1373 1374
    BYTE *data;
    UINT stride;
    UINT passes;
1375 1376
    WICColor palette[256];
    UINT colors;
1377 1378
} PngEncoder;

1379
static inline PngEncoder *impl_from_IWICBitmapEncoder(IWICBitmapEncoder *iface)
1380
{
1381 1382 1383 1384 1385 1386
    return CONTAINING_RECORD(iface, PngEncoder, IWICBitmapEncoder_iface);
}

static inline PngEncoder *impl_from_IWICBitmapFrameEncode(IWICBitmapFrameEncode *iface)
{
    return CONTAINING_RECORD(iface, PngEncoder, IWICBitmapFrameEncode_iface);
1387 1388 1389 1390 1391
}

static HRESULT WINAPI PngFrameEncode_QueryInterface(IWICBitmapFrameEncode *iface, REFIID iid,
    void **ppv)
{
1392
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1393 1394 1395 1396 1397 1398 1399
    TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);

    if (!ppv) return E_INVALIDARG;

    if (IsEqualIID(&IID_IUnknown, iid) ||
        IsEqualIID(&IID_IWICBitmapFrameEncode, iid))
    {
1400
        *ppv = &This->IWICBitmapFrameEncode_iface;
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
    }
    else
    {
        *ppv = NULL;
        return E_NOINTERFACE;
    }

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

static ULONG WINAPI PngFrameEncode_AddRef(IWICBitmapFrameEncode *iface)
{
1414
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1415
    return IWICBitmapEncoder_AddRef(&This->IWICBitmapEncoder_iface);
1416 1417 1418 1419
}

static ULONG WINAPI PngFrameEncode_Release(IWICBitmapFrameEncode *iface)
{
1420
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1421
    return IWICBitmapEncoder_Release(&This->IWICBitmapEncoder_iface);
1422 1423 1424 1425 1426
}

static HRESULT WINAPI PngFrameEncode_Initialize(IWICBitmapFrameEncode *iface,
    IPropertyBag2 *pIEncoderOptions)
{
1427
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1428
    WICPngFilterOption filter;
1429
    BOOL interlace;
1430 1431 1432
    PROPBAG2 opts[2]= {{0}};
    VARIANT opt_values[2];
    HRESULT opt_hres[2];
1433 1434
    HRESULT hr;

1435 1436
    TRACE("(%p,%p)\n", iface, pIEncoderOptions);

1437 1438
    opts[0].pstrName = (LPOLESTR)wszPngInterlaceOption;
    opts[0].vt = VT_BOOL;
1439 1440
    opts[1].pstrName = (LPOLESTR)wszPngFilterOption;
    opts[1].vt = VT_UI1;
1441 1442 1443

    if (pIEncoderOptions)
    {
1444
        hr = IPropertyBag2_Read(pIEncoderOptions, ARRAY_SIZE(opts), opts, NULL, opt_values, opt_hres);
1445 1446 1447

        if (FAILED(hr))
            return hr;
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459

        if (V_VT(&opt_values[0]) == VT_EMPTY)
            interlace = FALSE;
        else
            interlace = (V_BOOL(&opt_values[0]) != 0);

        filter = V_UI1(&opt_values[1]);
        if (filter > WICPngFilterAdaptive)
        {
            WARN("Unrecognized filter option value %u.\n", filter);
            filter = WICPngFilterUnspecified;
        }
1460 1461
    }
    else
1462
    {
1463
        interlace = FALSE;
1464 1465
        filter = WICPngFilterUnspecified;
    }
1466

1467 1468 1469 1470 1471 1472 1473
    EnterCriticalSection(&This->lock);

    if (This->frame_initialized)
    {
        LeaveCriticalSection(&This->lock);
        return WINCODEC_ERR_WRONGSTATE;
    }
1474

1475
    This->interlace = interlace;
1476
    This->filter = filter;
1477

1478 1479
    This->frame_initialized = TRUE;

1480 1481
    LeaveCriticalSection(&This->lock);

1482
    return S_OK;
1483 1484 1485 1486 1487
}

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

1491 1492 1493 1494 1495 1496 1497
    EnterCriticalSection(&This->lock);

    if (!This->frame_initialized || This->info_written)
    {
        LeaveCriticalSection(&This->lock);
        return WINCODEC_ERR_WRONGSTATE;
    }
1498 1499 1500 1501

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

1502 1503
    LeaveCriticalSection(&This->lock);

1504
    return S_OK;
1505 1506 1507 1508 1509
}

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

1513 1514 1515 1516 1517 1518 1519
    EnterCriticalSection(&This->lock);

    if (!This->frame_initialized || This->info_written)
    {
        LeaveCriticalSection(&This->lock);
        return WINCODEC_ERR_WRONGSTATE;
    }
1520 1521 1522 1523

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

1524 1525
    LeaveCriticalSection(&This->lock);

1526
    return S_OK;
1527 1528 1529 1530 1531
}

static HRESULT WINAPI PngFrameEncode_SetPixelFormat(IWICBitmapFrameEncode *iface,
    WICPixelFormatGUID *pPixelFormat)
{
1532
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1533 1534 1535
    int i;
    TRACE("(%p,%s)\n", iface, debugstr_guid(pPixelFormat));

1536 1537 1538 1539 1540 1541 1542
    EnterCriticalSection(&This->lock);

    if (!This->frame_initialized || This->info_written)
    {
        LeaveCriticalSection(&This->lock);
        return WINCODEC_ERR_WRONGSTATE;
    }
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554

    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));

1555 1556
    LeaveCriticalSection(&This->lock);

1557
    return S_OK;
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
}

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,
1568
    IWICPalette *palette)
1569
{
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
    HRESULT hr;

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

    if (!palette) return E_INVALIDARG;

    EnterCriticalSection(&This->lock);

    if (This->frame_initialized)
        hr = IWICPalette_GetColors(palette, 256, This->palette, &This->colors);
    else
        hr = WINCODEC_ERR_NOTINITIALIZED;

    LeaveCriticalSection(&This->lock);
    return hr;
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
}

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)
{
1598
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1599 1600
    png_byte **row_pointers=NULL;
    UINT i;
1601
    jmp_buf jmpbuf;
1602 1603
    TRACE("(%p,%u,%u,%u,%p)\n", iface, lineCount, cbStride, cbBufferSize, pbPixels);

1604 1605
    EnterCriticalSection(&This->lock);

1606
    if (!This->frame_initialized || !This->width || !This->height || !This->format)
1607 1608
    {
        LeaveCriticalSection(&This->lock);
1609
        return WINCODEC_ERR_WRONGSTATE;
1610
    }
1611 1612

    if (lineCount == 0 || lineCount + This->lines_written > This->height)
1613 1614
    {
        LeaveCriticalSection(&This->lock);
1615
        return E_INVALIDARG;
1616
    }
1617 1618

    /* set up setjmp/longjmp error handling */
1619
    if (setjmp(jmpbuf))
1620
    {
1621
        LeaveCriticalSection(&This->lock);
1622
        HeapFree(GetProcessHeap(), 0, row_pointers);
1623 1624
        return E_FAIL;
    }
1625
    ppng_set_error_fn(This->png_ptr, jmpbuf, user_error_fn, user_warning_fn);
1626 1627 1628

    if (!This->info_written)
    {
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
        if (This->interlace)
        {
            /* libpng requires us to write all data multiple times in this case. */
            This->stride = (This->format->bpp * This->width + 7)/8;
            This->data = HeapAlloc(GetProcessHeap(), 0, This->height * This->stride);
            if (!This->data)
            {
                LeaveCriticalSection(&This->lock);
                return E_OUTOFMEMORY;
            }
        }

1641
        ppng_set_IHDR(This->png_ptr, This->info_ptr, This->width, This->height,
1642 1643
            This->format->bit_depth, This->format->color_type,
            This->interlace ? PNG_INTERLACE_ADAM7 : PNG_INTERLACE_NONE,
1644 1645 1646 1647 1648 1649 1650 1651
            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);
        }

1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
        if (This->format->color_type == PNG_COLOR_TYPE_PALETTE && This->colors)
        {
            png_color png_palette[256];
            png_byte trans[256];
            UINT i, num_trans = 0, colors;

            /* Newer libpng versions don't accept larger palettes than the declared
             * bit depth, so we need to generate the palette of the correct length.
             */
            colors = min(This->colors, 1 << This->format->bit_depth);

            for (i = 0; i < colors; i++)
            {
                png_palette[i].red = (This->palette[i] >> 16) & 0xff;
                png_palette[i].green = (This->palette[i] >> 8) & 0xff;
                png_palette[i].blue = This->palette[i] & 0xff;
                trans[i] = (This->palette[i] >> 24) & 0xff;
                if (trans[i] != 0xff)
                    num_trans = i+1;
            }

            ppng_set_PLTE(This->png_ptr, This->info_ptr, png_palette, colors);

            if (num_trans)
                ppng_set_tRNS(This->png_ptr, This->info_ptr, trans, num_trans, NULL);
        }

1679 1680 1681 1682 1683 1684 1685 1686
        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);

1687 1688 1689
        if (This->interlace)
            This->passes = ppng_set_interlace_handling(This->png_ptr);

1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
        if (This->filter != WICPngFilterUnspecified)
        {
            static const int png_filter_map[] =
            {
                /* WICPngFilterUnspecified */ PNG_NO_FILTERS,
                /* WICPngFilterNone */        PNG_FILTER_NONE,
                /* WICPngFilterSub */         PNG_FILTER_SUB,
                /* WICPngFilterUp */          PNG_FILTER_UP,
                /* WICPngFilterAverage */     PNG_FILTER_AVG,
                /* WICPngFilterPaeth */       PNG_FILTER_PAETH,
                /* WICPngFilterAdaptive */    PNG_ALL_FILTERS,
            };

            ppng_set_filter(This->png_ptr, 0, png_filter_map[This->filter]);
        }

1706 1707 1708
        This->info_written = TRUE;
    }

1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
    if (This->interlace)
    {
        /* Just store the data so we can write it in multiple passes in Commit. */
        for (i=0; i<lineCount; i++)
            memcpy(This->data + This->stride * (This->lines_written + i),
                   pbPixels + cbStride * i,
                   This->stride);

        This->lines_written += lineCount;

        LeaveCriticalSection(&This->lock);
        return S_OK;
    }

1723 1724
    row_pointers = HeapAlloc(GetProcessHeap(), 0, lineCount * sizeof(png_byte*));
    if (!row_pointers)
1725 1726
    {
        LeaveCriticalSection(&This->lock);
1727
        return E_OUTOFMEMORY;
1728
    }
1729 1730 1731 1732 1733 1734 1735

    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;

1736 1737
    LeaveCriticalSection(&This->lock);

1738 1739 1740
    HeapFree(GetProcessHeap(), 0, row_pointers);

    return S_OK;
1741 1742 1743 1744 1745
}

static HRESULT WINAPI PngFrameEncode_WriteSource(IWICBitmapFrameEncode *iface,
    IWICBitmapSource *pIBitmapSource, WICRect *prc)
{
1746
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1747 1748 1749
    HRESULT hr;
    TRACE("(%p,%p,%p)\n", iface, pIBitmapSource, prc);

1750
    if (!This->frame_initialized)
1751 1752
        return WINCODEC_ERR_WRONGSTATE;

1753 1754 1755
    hr = configure_write_source(iface, pIBitmapSource, prc,
        This->format ? This->format->guid : NULL, This->width, This->height,
        This->xres, This->yres);
1756 1757 1758

    if (SUCCEEDED(hr))
    {
1759 1760
        hr = write_source(iface, pIBitmapSource, prc,
            This->format->guid, This->format->bpp, This->width, This->height);
1761 1762 1763
    }

    return hr;
1764 1765 1766 1767
}

static HRESULT WINAPI PngFrameEncode_Commit(IWICBitmapFrameEncode *iface)
{
1768
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
1769
    png_byte **row_pointers=NULL;
1770
    jmp_buf jmpbuf;
1771 1772
    TRACE("(%p)\n", iface);

1773 1774
    EnterCriticalSection(&This->lock);

1775
    if (!This->info_written || This->lines_written != This->height || This->frame_committed)
1776 1777
    {
        LeaveCriticalSection(&This->lock);
1778
        return WINCODEC_ERR_WRONGSTATE;
1779
    }
1780 1781

    /* set up setjmp/longjmp error handling */
1782
    if (setjmp(jmpbuf))
1783
    {
1784
        LeaveCriticalSection(&This->lock);
1785
        HeapFree(GetProcessHeap(), 0, row_pointers);
1786 1787
        return E_FAIL;
    }
1788
    ppng_set_error_fn(This->png_ptr, jmpbuf, user_error_fn, user_warning_fn);
1789

1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
    if (This->interlace)
    {
        int i;

        row_pointers = HeapAlloc(GetProcessHeap(), 0, This->height * sizeof(png_byte*));
        if (!row_pointers)
        {
            LeaveCriticalSection(&This->lock);
            return E_OUTOFMEMORY;
        }

        for (i=0; i<This->height; i++)
            row_pointers[i] = This->data + This->stride * i;

        for (i=0; i<This->passes; i++)
            ppng_write_rows(This->png_ptr, row_pointers, This->height);
    }

1808 1809 1810 1811
    ppng_write_end(This->png_ptr, This->info_ptr);

    This->frame_committed = TRUE;

1812 1813
    HeapFree(GetProcessHeap(), 0, row_pointers);

1814 1815
    LeaveCriticalSection(&This->lock);

1816
    return S_OK;
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
}

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
};

1843 1844 1845
static HRESULT WINAPI PngEncoder_QueryInterface(IWICBitmapEncoder *iface, REFIID iid,
    void **ppv)
{
1846
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1847 1848 1849 1850 1851 1852 1853
    TRACE("(%p,%s,%p)\n", iface, debugstr_guid(iid), ppv);

    if (!ppv) return E_INVALIDARG;

    if (IsEqualIID(&IID_IUnknown, iid) ||
        IsEqualIID(&IID_IWICBitmapEncoder, iid))
    {
1854
        *ppv = &This->IWICBitmapEncoder_iface;
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
    }
    else
    {
        *ppv = NULL;
        return E_NOINTERFACE;
    }

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

static ULONG WINAPI PngEncoder_AddRef(IWICBitmapEncoder *iface)
{
1868
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1869 1870 1871 1872 1873 1874 1875 1876 1877
    ULONG ref = InterlockedIncrement(&This->ref);

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

    return ref;
}

static ULONG WINAPI PngEncoder_Release(IWICBitmapEncoder *iface)
{
1878
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1879 1880 1881 1882 1883 1884
    ULONG ref = InterlockedDecrement(&This->ref);

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

    if (ref == 0)
    {
1885 1886
        This->lock.DebugInfo->Spare[0] = 0;
        DeleteCriticalSection(&This->lock);
1887 1888 1889 1890
        if (This->png_ptr)
            ppng_destroy_write_struct(&This->png_ptr, &This->info_ptr);
        if (This->stream)
            IStream_Release(This->stream);
1891
        HeapFree(GetProcessHeap(), 0, This->data);
1892 1893 1894 1895 1896 1897
        HeapFree(GetProcessHeap(), 0, This);
    }

    return ref;
}

1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
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)
{
}

1915 1916 1917
static HRESULT WINAPI PngEncoder_Initialize(IWICBitmapEncoder *iface,
    IStream *pIStream, WICBitmapEncoderCacheOption cacheOption)
{
1918
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
1919
    jmp_buf jmpbuf;
1920 1921 1922

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

1923 1924
    EnterCriticalSection(&This->lock);

1925
    if (This->png_ptr)
1926 1927
    {
        LeaveCriticalSection(&This->lock);
1928
        return WINCODEC_ERR_WRONGSTATE;
1929
    }
1930 1931 1932 1933

    /* initialize libpng */
    This->png_ptr = ppng_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (!This->png_ptr)
1934 1935
    {
        LeaveCriticalSection(&This->lock);
1936
        return E_FAIL;
1937
    }
1938 1939 1940 1941

    This->info_ptr = ppng_create_info_struct(This->png_ptr);
    if (!This->info_ptr)
    {
1942
        ppng_destroy_write_struct(&This->png_ptr, NULL);
1943
        This->png_ptr = NULL;
1944
        LeaveCriticalSection(&This->lock);
1945 1946 1947 1948 1949 1950 1951
        return E_FAIL;
    }

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

    /* set up setjmp/longjmp error handling */
1952
    if (setjmp(jmpbuf))
1953 1954 1955 1956 1957
    {
        ppng_destroy_write_struct(&This->png_ptr, &This->info_ptr);
        This->png_ptr = NULL;
        IStream_Release(This->stream);
        This->stream = NULL;
1958
        LeaveCriticalSection(&This->lock);
1959 1960
        return E_FAIL;
    }
1961
    ppng_set_error_fn(This->png_ptr, jmpbuf, user_error_fn, user_warning_fn);
1962 1963 1964 1965

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

1966 1967
    LeaveCriticalSection(&This->lock);

1968
    return S_OK;
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991
}

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;
}

1992
static HRESULT WINAPI PngEncoder_SetPalette(IWICBitmapEncoder *iface, IWICPalette *palette)
1993
{
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
    HRESULT hr;

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

    EnterCriticalSection(&This->lock);

    hr = This->stream ? WINCODEC_ERR_UNSUPPORTEDOPERATION : WINCODEC_ERR_NOTINITIALIZED;

    LeaveCriticalSection(&This->lock);

    return hr;
2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
}

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)
{
2023
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
2024
    HRESULT hr;
2025 2026 2027 2028 2029
    static const PROPBAG2 opts[2] =
    {
        { PROPBAG2_TYPE_DATA, VT_BOOL, 0, 0, (LPOLESTR)wszPngInterlaceOption },
        { PROPBAG2_TYPE_DATA, VT_UI1,  0, 0, (LPOLESTR)wszPngFilterOption },
    };
2030

2031 2032
    TRACE("(%p,%p,%p)\n", iface, ppIFrameEncode, ppIEncoderOptions);

2033 2034
    EnterCriticalSection(&This->lock);

2035
    if (This->frame_count != 0)
2036 2037
    {
        LeaveCriticalSection(&This->lock);
2038
        return WINCODEC_ERR_UNSUPPORTEDOPERATION;
2039
    }
2040 2041

    if (!This->stream)
2042 2043
    {
        LeaveCriticalSection(&This->lock);
2044
        return WINCODEC_ERR_NOTINITIALIZED;
2045
    }
2046

2047
    if (ppIEncoderOptions)
2048
    {
2049
        hr = CreatePropertyBag2(opts, ARRAY_SIZE(opts), ppIEncoderOptions);
2050 2051 2052 2053 2054
        if (FAILED(hr))
        {
            LeaveCriticalSection(&This->lock);
            return hr;
        }
2055
    }
2056 2057 2058

    This->frame_count = 1;

2059 2060
    LeaveCriticalSection(&This->lock);

2061
    IWICBitmapEncoder_AddRef(iface);
2062
    *ppIFrameEncode = &This->IWICBitmapFrameEncode_iface;
2063 2064

    return S_OK;
2065 2066 2067 2068
}

static HRESULT WINAPI PngEncoder_Commit(IWICBitmapEncoder *iface)
{
2069
    PngEncoder *This = impl_from_IWICBitmapEncoder(iface);
2070 2071
    TRACE("(%p)\n", iface);

2072 2073
    EnterCriticalSection(&This->lock);

2074
    if (!This->frame_committed || This->committed)
2075 2076
    {
        LeaveCriticalSection(&This->lock);
2077
        return WINCODEC_ERR_WRONGSTATE;
2078
    }
2079 2080 2081

    This->committed = TRUE;

2082
    LeaveCriticalSection(&This->lock);
2083

2084
    return S_OK;
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
}

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
};

2110
HRESULT PngEncoder_CreateInstance(REFIID iid, void** ppv)
2111 2112 2113 2114
{
    PngEncoder *This;
    HRESULT ret;

2115
    TRACE("(%s,%p)\n", debugstr_guid(iid), ppv);
2116 2117 2118

    *ppv = NULL;

2119
    if (!load_libpng())
2120 2121 2122 2123 2124 2125 2126 2127
    {
        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;

2128 2129
    This->IWICBitmapEncoder_iface.lpVtbl = &PngEncoder_Vtbl;
    This->IWICBitmapFrameEncode_iface.lpVtbl = &PngEncoder_FrameVtbl;
2130
    This->ref = 1;
2131 2132 2133
    This->png_ptr = NULL;
    This->info_ptr = NULL;
    This->stream = NULL;
2134
    This->frame_count = 0;
2135
    This->frame_initialized = FALSE;
2136 2137
    This->format = NULL;
    This->info_written = FALSE;
2138 2139
    This->width = 0;
    This->height = 0;
2140 2141
    This->xres = 0.0;
    This->yres = 0.0;
2142
    This->lines_written = 0;
2143
    This->frame_committed = FALSE;
2144
    This->committed = FALSE;
2145
    This->data = NULL;
2146
    This->colors = 0;
2147 2148
    InitializeCriticalSection(&This->lock);
    This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": PngEncoder.lock");
2149

2150 2151
    ret = IWICBitmapEncoder_QueryInterface(&This->IWICBitmapEncoder_iface, iid, ppv);
    IWICBitmapEncoder_Release(&This->IWICBitmapEncoder_iface);
2152 2153 2154 2155

    return ret;
}

2156 2157
#else /* !HAVE_PNG_H */

2158
HRESULT PngDecoder_CreateInstance(REFIID iid, void** ppv)
2159
{
2160
    ERR("Trying to load PNG picture, but PNG support is not compiled in.\n");
2161 2162 2163
    return E_FAIL;
}

2164
HRESULT PngEncoder_CreateInstance(REFIID iid, void** ppv)
2165
{
2166
    ERR("Trying to save PNG picture, but PNG support is not compiled in.\n");
2167 2168 2169
    return E_FAIL;
}

2170
#endif