1/*
2 * Copyright (c) 2010, Google Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 *     * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *     * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 *     * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31#include "config.h"
32#include "platform/image-encoders/skia/PNGImageEncoder.h"
33
34#include "SkBitmap.h"
35#include "SkColorPriv.h"
36#include "SkUnPreMultiply.h"
37#include "platform/geometry/IntSize.h"
38#include "platform/graphics/ImageBuffer.h"
39extern "C" {
40#include "png.h"
41}
42
43namespace blink {
44
45static void writeOutput(png_structp png, png_bytep data, png_size_t size)
46{
47    static_cast<Vector<unsigned char>*>(png_get_io_ptr(png))->append(data, size);
48}
49
50static void preMultipliedBGRAtoRGBA(const void* pixels, int pixelCount, unsigned char* output)
51{
52    static const SkUnPreMultiply::Scale* scale = SkUnPreMultiply::GetScaleTable();
53    const SkPMColor* input = static_cast<const SkPMColor*>(pixels);
54
55    for (; pixelCount-- > 0; ++input) {
56        const unsigned alpha = SkGetPackedA32(*input);
57        if ((alpha != 0) && (alpha != 255)) {
58            *output++ = SkUnPreMultiply::ApplyScale(scale[alpha], SkGetPackedR32(*input));
59            *output++ = SkUnPreMultiply::ApplyScale(scale[alpha], SkGetPackedG32(*input));
60            *output++ = SkUnPreMultiply::ApplyScale(scale[alpha], SkGetPackedB32(*input));
61            *output++ = alpha;
62        } else {
63            *output++ = SkGetPackedR32(*input);
64            *output++ = SkGetPackedG32(*input);
65            *output++ = SkGetPackedB32(*input);
66            *output++ = alpha;
67        }
68    }
69}
70
71static bool encodePixels(IntSize imageSize, unsigned char* inputPixels, bool premultiplied, Vector<unsigned char>* output)
72{
73    imageSize.clampNegativeToZero();
74    Vector<unsigned char> row;
75
76    png_struct* png = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
77    png_info* info = png_create_info_struct(png);
78    if (!png || !info || setjmp(png_jmpbuf(png))) {
79        png_destroy_write_struct(png ? &png : 0, info ? &info : 0);
80        return false;
81    }
82
83    // Optimize compression for speed.
84    // The parameters are the same as what libpng uses by default for RGB and RGBA images, except:
85    // - the zlib compression level is 3 instead of 6, to avoid the lazy Ziv-Lempel match searching;
86    // - the delta filter is 1 ("sub") instead of 5 ("all"), to reduce the filter computations.
87    // The zlib memory level (8) and strategy (Z_FILTERED) will be set inside libpng.
88    //
89    // Avoid the zlib strategies Z_HUFFMAN_ONLY or Z_RLE.
90    // Although they are the fastest for poorly-compressible images (e.g. photographs),
91    // they are very slow for highly-compressible images (e.g. text, drawings or business graphics).
92    png_set_compression_level(png, 3);
93    png_set_filter(png, PNG_FILTER_TYPE_BASE, PNG_FILTER_SUB);
94
95    png_set_write_fn(png, output, writeOutput, 0);
96    png_set_IHDR(png, info, imageSize.width(), imageSize.height(),
97                 8, PNG_COLOR_TYPE_RGB_ALPHA, 0, 0, 0);
98    png_write_info(png, info);
99
100    unsigned char* pixels = inputPixels;
101    row.resize(imageSize.width() * sizeof(SkPMColor));
102    const size_t pixelRowStride = imageSize.width() * 4;
103    for (int y = 0; y < imageSize.height(); ++y) {
104        if (premultiplied) {
105            preMultipliedBGRAtoRGBA(pixels, imageSize.width(), row.data());
106            png_write_row(png, row.data());
107        } else
108            png_write_row(png, pixels);
109        pixels += pixelRowStride;
110    }
111
112    png_write_end(png, info);
113    png_destroy_write_struct(&png, &info);
114    return true;
115}
116
117bool PNGImageEncoder::encode(const SkBitmap& bitmap, Vector<unsigned char>* output)
118{
119    SkAutoLockPixels bitmapLock(bitmap);
120
121    if (bitmap.colorType() != kN32_SkColorType || !bitmap.getPixels())
122        return false; // Only support 32 bit/pixel skia bitmaps.
123
124    return encodePixels(IntSize(bitmap.width(), bitmap.height()), static_cast<unsigned char*>(bitmap.getPixels()), true, output);
125}
126
127bool PNGImageEncoder::encode(const ImageDataBuffer& imageData, Vector<unsigned char>* output)
128{
129    return encodePixels(imageData.size(), imageData.data(), false, output);
130}
131
132} // namespace blink
133