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 "core/platform/image-encoders/skia/JPEGImageEncoder.h"
33
34#include "SkBitmap.h"
35#include "SkColorPriv.h"
36#include "core/html/ImageData.h"
37#include "core/platform/graphics/IntSize.h"
38extern "C" {
39#include <setjmp.h>
40#include <stdio.h> // jpeglib.h needs stdio.h FILE
41#include "jpeglib.h"
42}
43
44namespace WebCore {
45
46struct JPEGOutputBuffer : public jpeg_destination_mgr {
47    Vector<unsigned char>* output;
48    Vector<unsigned char> buffer;
49};
50
51static void prepareOutput(j_compress_ptr cinfo)
52{
53    JPEGOutputBuffer* out = static_cast<JPEGOutputBuffer*>(cinfo->dest);
54    const size_t internalBufferSize = 8192;
55    out->buffer.resize(internalBufferSize);
56    out->next_output_byte = out->buffer.data();
57    out->free_in_buffer = out->buffer.size();
58}
59
60static boolean writeOutput(j_compress_ptr cinfo)
61{
62    JPEGOutputBuffer* out = static_cast<JPEGOutputBuffer*>(cinfo->dest);
63    out->output->append(out->buffer.data(), out->buffer.size());
64    out->next_output_byte = out->buffer.data();
65    out->free_in_buffer = out->buffer.size();
66    return TRUE;
67}
68
69static void finishOutput(j_compress_ptr cinfo)
70{
71    JPEGOutputBuffer* out = static_cast<JPEGOutputBuffer*>(cinfo->dest);
72    const size_t size = out->buffer.size() - out->free_in_buffer;
73    out->output->append(out->buffer.data(), size);
74}
75
76static void handleError(j_common_ptr common)
77{
78    jmp_buf* jumpBufferPtr = static_cast<jmp_buf*>(common->client_data);
79    longjmp(*jumpBufferPtr, -1);
80}
81
82static void preMultipliedBGRAtoRGB(const unsigned char* pixels, unsigned int pixelCount, unsigned char* output)
83{
84    const SkPMColor* input = reinterpret_cast_ptr<const SkPMColor*>(pixels);
85    for (; pixelCount-- > 0; ++input) {
86        *output++ = SkGetPackedR32(*input);
87        *output++ = SkGetPackedG32(*input);
88        *output++ = SkGetPackedB32(*input);
89    }
90}
91
92static void RGBAtoRGB(const unsigned char* pixels, unsigned int pixelCount, unsigned char* output)
93{
94    for (; pixelCount-- > 0; pixels += 4) {
95        // Do source-over composition on black.
96        unsigned char alpha = pixels[3];
97        if (alpha != 255) {
98            *output++ = SkMulDiv255Round(pixels[0], alpha);
99            *output++ = SkMulDiv255Round(pixels[1], alpha);
100            *output++ = SkMulDiv255Round(pixels[2], alpha);
101        } else {
102            *output++ = pixels[0];
103            *output++ = pixels[1];
104            *output++ = pixels[2];
105        }
106    }
107}
108
109static bool encodePixels(IntSize imageSize, unsigned char* inputPixels, bool premultiplied, int quality, Vector<unsigned char>* output)
110{
111    JPEGOutputBuffer destination;
112    destination.output = output;
113    Vector<JSAMPLE> row;
114
115    jpeg_compress_struct cinfo;
116    jpeg_error_mgr error;
117    cinfo.err = jpeg_std_error(&error);
118    error.error_exit = handleError;
119    jmp_buf jumpBuffer;
120    cinfo.client_data = &jumpBuffer;
121
122    if (setjmp(jumpBuffer)) {
123        jpeg_destroy_compress(&cinfo);
124        return false;
125    }
126
127    jpeg_create_compress(&cinfo);
128    cinfo.dest = &destination;
129    cinfo.dest->init_destination = prepareOutput;
130    cinfo.dest->empty_output_buffer = writeOutput;
131    cinfo.dest->term_destination = finishOutput;
132
133    imageSize.clampNegativeToZero();
134    cinfo.image_height = imageSize.height();
135    cinfo.image_width = imageSize.width();
136
137#if defined(JCS_EXTENSIONS)
138    if (premultiplied) {
139        cinfo.in_color_space = SK_B32_SHIFT ? JCS_EXT_RGBX : JCS_EXT_BGRX;
140
141        cinfo.input_components = 4;
142
143        jpeg_set_defaults(&cinfo);
144        jpeg_set_quality(&cinfo, quality, TRUE);
145        jpeg_start_compress(&cinfo, TRUE);
146
147        unsigned char* pixels = inputPixels;
148        const size_t pixelRowStride = cinfo.image_width * 4;
149        while (cinfo.next_scanline < cinfo.image_height) {
150            jpeg_write_scanlines(&cinfo, &pixels, 1);
151            pixels += pixelRowStride;
152        }
153
154        jpeg_finish_compress(&cinfo);
155        jpeg_destroy_compress(&cinfo);
156        return true;
157    }
158#endif
159
160    cinfo.in_color_space = JCS_RGB;
161    cinfo.input_components = 3;
162
163    void (*extractRowRGB)(const unsigned char*, unsigned int, unsigned char* output);
164    extractRowRGB = &RGBAtoRGB;
165    if (premultiplied)
166        extractRowRGB = &preMultipliedBGRAtoRGB;
167
168    jpeg_set_defaults(&cinfo);
169    jpeg_set_quality(&cinfo, quality, TRUE);
170    jpeg_start_compress(&cinfo, TRUE);
171
172    unsigned char* pixels = inputPixels;
173    row.resize(cinfo.image_width * cinfo.input_components);
174    const size_t pixelRowStride = cinfo.image_width * 4;
175    while (cinfo.next_scanline < cinfo.image_height) {
176        JSAMPLE* rowData = row.data();
177        extractRowRGB(pixels, cinfo.image_width, rowData);
178        jpeg_write_scanlines(&cinfo, &rowData, 1);
179        pixels += pixelRowStride;
180    }
181
182    jpeg_finish_compress(&cinfo);
183    jpeg_destroy_compress(&cinfo);
184    return true;
185}
186
187bool JPEGImageEncoder::encode(const SkBitmap& bitmap, int quality, Vector<unsigned char>* output)
188{
189    SkAutoLockPixels bitmapLock(bitmap);
190
191    if (bitmap.config() != SkBitmap::kARGB_8888_Config || !bitmap.getPixels())
192        return false; // Only support 32 bit/pixel skia bitmaps.
193
194    return encodePixels(IntSize(bitmap.width(), bitmap.height()), static_cast<unsigned char *>(bitmap.getPixels()), true, quality, output);
195}
196
197bool JPEGImageEncoder::encode(const ImageData& imageData, int quality, Vector<unsigned char>* output)
198{
199    return encodePixels(imageData.size(), imageData.data()->data(), false, quality, output);
200}
201
202} // namespace WebCore
203