1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "build/build_config.h"
6 #include "webkit/support/webkit_support_gfx.h"
11 #include "third_party/libpng/png.h"
12 #include "third_party/zlib/zlib.h"
14 namespace webkit_support
{
16 // Define macro here to make webkit_support_gfx independent of target base.
17 // Note that the NOTREACHED() macro will result in a crash. This is preferable
18 // to calling exit() / abort(), since the latter may not surfce the problem as
19 // crash reports, making it hard to tell where the problem is.
20 #define NOTREACHED(msg) *((volatile int*)0) = 3
21 #define DCHECK(condition) \
22 if (!(condition)) fprintf(stderr, "DCHECK failed: " #condition ".")
24 // The new webkit_support_gfx, used by DumpRenderTree and ImageDiff,
25 // doesn't depend on most other parts of chromium. This could make building
26 // the individual target of ImageDiff fast. It's implemented by duplicating
27 // most code in ui/gfx/codec/png_codec.cc, after removing code related to
32 // 3 bytes per pixel (packed), in RGB order regardless of endianness.
33 // This is the native JPEG format.
36 // 4 bytes per pixel, in RGBA order in memory regardless of endianness.
39 // 4 bytes per pixel, in BGRA order in memory regardless of endianness.
40 // This is the default Windows DIB order.
43 // 4 bytes per pixel, in pre-multiplied kARGB_8888_Config format. For use
44 // with directly writing to a skia bitmap.
48 // Represents a comment in the tEXt ancillary chunk of the png.
50 Comment(const std::string
& k
, const std::string
& t
)
61 // Converts BGRA->RGBA and RGBA->BGRA.
62 void ConvertBetweenBGRAandRGBA(const unsigned char* input
, int pixel_width
,
63 unsigned char* output
, bool* is_opaque
) {
64 for (int x
= 0; x
< pixel_width
; x
++) {
65 const unsigned char* pixel_in
= &input
[x
* 4];
66 unsigned char* pixel_out
= &output
[x
* 4];
67 pixel_out
[0] = pixel_in
[2];
68 pixel_out
[1] = pixel_in
[1];
69 pixel_out
[2] = pixel_in
[0];
70 pixel_out
[3] = pixel_in
[3];
74 void ConvertRGBAtoRGB(const unsigned char* rgba
, int pixel_width
,
75 unsigned char* rgb
, bool* is_opaque
) {
76 for (int x
= 0; x
< pixel_width
; x
++) {
77 const unsigned char* pixel_in
= &rgba
[x
* 4];
78 unsigned char* pixel_out
= &rgb
[x
* 3];
79 pixel_out
[0] = pixel_in
[0];
80 pixel_out
[1] = pixel_in
[1];
81 pixel_out
[2] = pixel_in
[2];
87 // Decoder --------------------------------------------------------------------
89 // This code is based on WebKit libpng interface (PNGImageDecoder), which is
90 // in turn based on the Mozilla png decoder.
94 // Gamma constants: We assume we're on Windows which uses a gamma of 2.2.
95 const double kMaxGamma
= 21474.83; // Maximum gamma accepted by png library.
96 const double kDefaultGamma
= 2.2;
97 const double kInverseGamma
= 1.0 / kDefaultGamma
;
99 class PngDecoderState
{
101 // Output is a vector<unsigned char>.
102 PngDecoderState(ColorFormat ofmt
, std::vector
<unsigned char>* o
)
103 : output_format(ofmt
),
113 ColorFormat output_format
;
116 // Used during the reading of an SkBitmap. Defaults to true until we see a
117 // pixel with anything other than an alpha of 255.
120 // An intermediary buffer for decode output.
121 std::vector
<unsigned char>* output
;
123 // Called to convert a row from the library to the correct output format.
124 // When NULL, no conversion is necessary.
125 void (*row_converter
)(const unsigned char* in
, int w
, unsigned char* out
,
128 // Size of the image, set in the info callback.
132 // Set to true when we've found the end of the data.
136 void ConvertRGBtoRGBA(const unsigned char* rgb
, int pixel_width
,
137 unsigned char* rgba
, bool* is_opaque
) {
138 for (int x
= 0; x
< pixel_width
; x
++) {
139 const unsigned char* pixel_in
= &rgb
[x
* 3];
140 unsigned char* pixel_out
= &rgba
[x
* 4];
141 pixel_out
[0] = pixel_in
[0];
142 pixel_out
[1] = pixel_in
[1];
143 pixel_out
[2] = pixel_in
[2];
148 void ConvertRGBtoBGRA(const unsigned char* rgb
, int pixel_width
,
149 unsigned char* bgra
, bool* is_opaque
) {
150 for (int x
= 0; x
< pixel_width
; x
++) {
151 const unsigned char* pixel_in
= &rgb
[x
* 3];
152 unsigned char* pixel_out
= &bgra
[x
* 4];
153 pixel_out
[0] = pixel_in
[2];
154 pixel_out
[1] = pixel_in
[1];
155 pixel_out
[2] = pixel_in
[0];
160 // Called when the png header has been read. This code is based on the WebKit
162 void DecodeInfoCallback(png_struct
* png_ptr
, png_info
* info_ptr
) {
163 PngDecoderState
* state
= static_cast<PngDecoderState
*>(
164 png_get_progressive_ptr(png_ptr
));
166 int bit_depth
, color_type
, interlace_type
, compression_type
;
167 int filter_type
, channels
;
169 png_get_IHDR(png_ptr
, info_ptr
, &w
, &h
, &bit_depth
, &color_type
,
170 &interlace_type
, &compression_type
, &filter_type
);
172 // Bounds check. When the image is unreasonably big, we'll error out and
173 // end up back at the setjmp call when we set up decoding. "Unreasonably big"
174 // means "big enough that w * h * 32bpp might overflow an int"; we choose this
175 // threshold to match WebKit and because a number of places in code assume
176 // that an image's size (in bytes) fits in a (signed) int.
177 unsigned long long total_size
=
178 static_cast<unsigned long long>(w
) * static_cast<unsigned long long>(h
);
179 if (total_size
> ((1 << 29) - 1))
180 longjmp(png_jmpbuf(png_ptr
), 1);
181 state
->width
= static_cast<int>(w
);
182 state
->height
= static_cast<int>(h
);
184 // Expand to ensure we use 24-bit for RGB and 32-bit for RGBA.
185 if (color_type
== PNG_COLOR_TYPE_PALETTE
||
186 (color_type
== PNG_COLOR_TYPE_GRAY
&& bit_depth
< 8))
187 png_set_expand(png_ptr
);
189 // Transparency for paletted images.
190 if (png_get_valid(png_ptr
, info_ptr
, PNG_INFO_tRNS
))
191 png_set_expand(png_ptr
);
193 // Convert 16-bit to 8-bit.
195 png_set_strip_16(png_ptr
);
197 // Expand grayscale to RGB.
198 if (color_type
== PNG_COLOR_TYPE_GRAY
||
199 color_type
== PNG_COLOR_TYPE_GRAY_ALPHA
)
200 png_set_gray_to_rgb(png_ptr
);
202 // Deal with gamma and keep it under our control.
204 if (png_get_gAMA(png_ptr
, info_ptr
, &gamma
)) {
205 if (gamma
<= 0.0 || gamma
> kMaxGamma
) {
206 gamma
= kInverseGamma
;
207 png_set_gAMA(png_ptr
, info_ptr
, gamma
);
209 png_set_gamma(png_ptr
, kDefaultGamma
, gamma
);
211 png_set_gamma(png_ptr
, kDefaultGamma
, kInverseGamma
);
214 // Tell libpng to send us rows for interlaced pngs.
215 if (interlace_type
== PNG_INTERLACE_ADAM7
)
216 png_set_interlace_handling(png_ptr
);
218 // Update our info now
219 png_read_update_info(png_ptr
, info_ptr
);
220 channels
= png_get_channels(png_ptr
, info_ptr
);
222 // Pick our row format converter necessary for this data.
224 switch (state
->output_format
) {
226 state
->row_converter
= NULL
; // no conversion necessary
227 state
->output_channels
= 3;
230 state
->row_converter
= &ConvertRGBtoRGBA
;
231 state
->output_channels
= 4;
234 state
->row_converter
= &ConvertRGBtoBGRA
;
235 state
->output_channels
= 4;
238 NOTREACHED("Unknown output format");
241 } else if (channels
== 4) {
242 switch (state
->output_format
) {
244 state
->row_converter
= &ConvertRGBAtoRGB
;
245 state
->output_channels
= 3;
248 state
->row_converter
= NULL
; // no conversion necessary
249 state
->output_channels
= 4;
252 state
->row_converter
= &ConvertBetweenBGRAandRGBA
;
253 state
->output_channels
= 4;
256 NOTREACHED("Unknown output format");
260 NOTREACHED("Unknown input channels");
261 longjmp(png_jmpbuf(png_ptr
), 1);
264 state
->output
->resize(
265 state
->width
* state
->output_channels
* state
->height
);
268 void DecodeRowCallback(png_struct
* png_ptr
, png_byte
* new_row
,
269 png_uint_32 row_num
, int pass
) {
270 PngDecoderState
* state
= static_cast<PngDecoderState
*>(
271 png_get_progressive_ptr(png_ptr
));
274 if (static_cast<int>(row_num
) > state
->height
) {
275 NOTREACHED("Invalid row");
279 unsigned char* base
= NULL
;
280 base
= &state
->output
->front();
282 unsigned char* dest
= &base
[state
->width
* state
->output_channels
* row_num
];
283 if (state
->row_converter
)
284 state
->row_converter(new_row
, state
->width
, dest
, &state
->is_opaque
);
286 memcpy(dest
, new_row
, state
->width
* state
->output_channels
);
289 void DecodeEndCallback(png_struct
* png_ptr
, png_info
* info
) {
290 PngDecoderState
* state
= static_cast<PngDecoderState
*>(
291 png_get_progressive_ptr(png_ptr
));
293 // Mark the image as complete, this will tell the Decode function that we
294 // have successfully found the end of the data.
298 // Automatically destroys the given read structs on destruction to make
299 // cleanup and error handling code cleaner.
300 class PngReadStructDestroyer
{
302 PngReadStructDestroyer(png_struct
** ps
, png_info
** pi
) : ps_(ps
), pi_(pi
) {
304 ~PngReadStructDestroyer() {
305 png_destroy_read_struct(ps_
, pi_
, NULL
);
312 bool BuildPNGStruct(const unsigned char* input
, size_t input_size
,
313 png_struct
** png_ptr
, png_info
** info_ptr
) {
315 return false; // Input data too small to be a png
317 // Have libpng check the signature, it likes the first 8 bytes.
318 if (png_sig_cmp(const_cast<unsigned char*>(input
), 0, 8) != 0)
321 *png_ptr
= png_create_read_struct(PNG_LIBPNG_VER_STRING
, NULL
, NULL
, NULL
);
325 *info_ptr
= png_create_info_struct(*png_ptr
);
327 png_destroy_read_struct(png_ptr
, NULL
, NULL
);
337 bool Decode(const unsigned char* input
, size_t input_size
,
338 ColorFormat format
, std::vector
<unsigned char>* output
,
340 png_struct
* png_ptr
= NULL
;
341 png_info
* info_ptr
= NULL
;
342 if (!BuildPNGStruct(input
, input_size
, &png_ptr
, &info_ptr
))
345 PngReadStructDestroyer
destroyer(&png_ptr
, &info_ptr
);
346 if (setjmp(png_jmpbuf(png_ptr
))) {
347 // The destroyer will ensure that the structures are cleaned up in this
348 // case, even though we may get here as a jump from random parts of the
349 // PNG library called below.
353 PngDecoderState
state(format
, output
);
355 png_set_progressive_read_fn(png_ptr
, &state
, &DecodeInfoCallback
,
356 &DecodeRowCallback
, &DecodeEndCallback
);
357 png_process_data(png_ptr
,
359 const_cast<unsigned char*>(input
),
363 // Fed it all the data but the library didn't think we got all the data, so
364 // this file must be truncated.
374 // Encoder --------------------------------------------------------------------
376 // This section of the code is based on nsPNGEncoder.cpp in Mozilla
377 // (Copyright 2005 Google Inc.)
381 // Passed around as the io_ptr in the png structs so our callbacks know where
383 struct PngEncoderState
{
384 explicit PngEncoderState(std::vector
<unsigned char>* o
) : out(o
) {}
385 std::vector
<unsigned char>* out
;
388 // Called by libpng to flush its internal buffer to ours.
389 void EncoderWriteCallback(png_structp png
, png_bytep data
, png_size_t size
) {
390 PngEncoderState
* state
= static_cast<PngEncoderState
*>(png_get_io_ptr(png
));
393 size_t old_size
= state
->out
->size();
394 state
->out
->resize(old_size
+ size
);
395 memcpy(&(*state
->out
)[old_size
], data
, size
);
398 void FakeFlushCallback(png_structp png
) {
399 // We don't need to perform any flushing since we aren't doing real IO, but
400 // we're required to provide this function by libpng.
403 void ConvertBGRAtoRGB(const unsigned char* bgra
, int pixel_width
,
404 unsigned char* rgb
, bool* is_opaque
) {
405 for (int x
= 0; x
< pixel_width
; x
++) {
406 const unsigned char* pixel_in
= &bgra
[x
* 4];
407 unsigned char* pixel_out
= &rgb
[x
* 3];
408 pixel_out
[0] = pixel_in
[2];
409 pixel_out
[1] = pixel_in
[1];
410 pixel_out
[2] = pixel_in
[0];
414 #ifdef PNG_TEXT_SUPPORTED
416 inline char* strdup(const char* str
) {
420 return ::strdup(str
);
424 class CommentWriter
{
426 explicit CommentWriter(const std::vector
<Comment
>& comments
)
427 : comments_(comments
),
428 png_text_(new png_text
[comments
.size()]) {
429 for (size_t i
= 0; i
< comments
.size(); ++i
)
430 AddComment(i
, comments
[i
]);
434 for (size_t i
= 0; i
< comments_
.size(); ++i
) {
435 free(png_text_
[i
].key
);
436 free(png_text_
[i
].text
);
442 return !comments_
.empty();
445 png_text
* get_png_text() {
450 return static_cast<int>(comments_
.size());
454 void AddComment(size_t pos
, const Comment
& comment
) {
455 png_text_
[pos
].compression
= PNG_TEXT_COMPRESSION_NONE
;
456 // A PNG comment's key can only be 79 characters long.
457 DCHECK(comment
.key
.length() < 79);
458 png_text_
[pos
].key
= strdup(comment
.key
.substr(0, 78).c_str());
459 png_text_
[pos
].text
= strdup(comment
.text
.c_str());
460 png_text_
[pos
].text_length
= comment
.text
.length();
461 #ifdef PNG_iTXt_SUPPORTED
462 png_text_
[pos
].itxt_length
= 0;
463 png_text_
[pos
].lang
= 0;
464 png_text_
[pos
].lang_key
= 0;
468 const std::vector
<Comment
> comments_
;
471 #endif // PNG_TEXT_SUPPORTED
473 // The type of functions usable for converting between pixel formats.
474 typedef void (*FormatConverter
)(const unsigned char* in
, int w
,
475 unsigned char* out
, bool* is_opaque
);
477 // libpng uses a wacky setjmp-based API, which makes the compiler nervous.
478 // We constrain all of the calls we make to libpng where the setjmp() is in
479 // place to this function.
480 // Returns true on success.
481 bool DoLibpngWrite(png_struct
* png_ptr
, png_info
* info_ptr
,
482 PngEncoderState
* state
,
483 int width
, int height
, int row_byte_width
,
484 const unsigned char* input
, int compression_level
,
485 int png_output_color_type
, int output_color_components
,
486 FormatConverter converter
,
487 const std::vector
<Comment
>& comments
) {
488 #ifdef PNG_TEXT_SUPPORTED
489 CommentWriter
comment_writer(comments
);
491 unsigned char* row_buffer
= NULL
;
493 // Make sure to not declare any locals here -- locals in the presence
494 // of setjmp() in C++ code makes gcc complain.
496 if (setjmp(png_jmpbuf(png_ptr
))) {
501 png_set_compression_level(png_ptr
, compression_level
);
503 // Set our callback for libpng to give us the data.
504 png_set_write_fn(png_ptr
, state
, EncoderWriteCallback
, FakeFlushCallback
);
506 png_set_IHDR(png_ptr
, info_ptr
, width
, height
, 8, png_output_color_type
,
507 PNG_INTERLACE_NONE
, PNG_COMPRESSION_TYPE_DEFAULT
,
508 PNG_FILTER_TYPE_DEFAULT
);
510 #ifdef PNG_TEXT_SUPPORTED
511 if (comment_writer
.HasComments()) {
512 png_set_text(png_ptr
, info_ptr
, comment_writer
.get_png_text(),
513 comment_writer
.size());
517 png_write_info(png_ptr
, info_ptr
);
520 // No conversion needed, give the data directly to libpng.
521 for (int y
= 0; y
< height
; y
++) {
522 png_write_row(png_ptr
,
523 const_cast<unsigned char*>(&input
[y
* row_byte_width
]));
526 // Needs conversion using a separate buffer.
527 row_buffer
= new unsigned char[width
* output_color_components
];
528 for (int y
= 0; y
< height
; y
++) {
529 converter(&input
[y
* row_byte_width
], width
, row_buffer
, NULL
);
530 png_write_row(png_ptr
, row_buffer
);
535 png_write_end(png_ptr
, info_ptr
);
542 bool EncodeWithCompressionLevel(const unsigned char* input
, ColorFormat format
,
543 const int width
, const int height
,
545 bool discard_transparency
,
546 const std::vector
<Comment
>& comments
,
547 int compression_level
,
548 std::vector
<unsigned char>* output
) {
549 // Run to convert an input row into the output row format, NULL means no
550 // conversion is necessary.
551 FormatConverter converter
= NULL
;
553 int input_color_components
, output_color_components
;
554 int png_output_color_type
;
557 input_color_components
= 3;
558 output_color_components
= 3;
559 png_output_color_type
= PNG_COLOR_TYPE_RGB
;
560 discard_transparency
= false;
564 input_color_components
= 4;
565 if (discard_transparency
) {
566 output_color_components
= 3;
567 png_output_color_type
= PNG_COLOR_TYPE_RGB
;
568 converter
= ConvertRGBAtoRGB
;
570 output_color_components
= 4;
571 png_output_color_type
= PNG_COLOR_TYPE_RGB_ALPHA
;
577 input_color_components
= 4;
578 if (discard_transparency
) {
579 output_color_components
= 3;
580 png_output_color_type
= PNG_COLOR_TYPE_RGB
;
581 converter
= ConvertBGRAtoRGB
;
583 output_color_components
= 4;
584 png_output_color_type
= PNG_COLOR_TYPE_RGB_ALPHA
;
585 converter
= ConvertBetweenBGRAandRGBA
;
590 NOTREACHED("Unknown pixel format");
594 // Row stride should be at least as long as the length of the data.
595 DCHECK(input_color_components
* width
<= row_byte_width
);
597 png_struct
* png_ptr
= png_create_write_struct(PNG_LIBPNG_VER_STRING
,
601 png_info
* info_ptr
= png_create_info_struct(png_ptr
);
603 png_destroy_write_struct(&png_ptr
, NULL
);
607 PngEncoderState
state(output
);
608 bool success
= DoLibpngWrite(png_ptr
, info_ptr
, &state
,
609 width
, height
, row_byte_width
,
610 input
, compression_level
, png_output_color_type
,
611 output_color_components
, converter
, comments
);
612 png_destroy_write_struct(&png_ptr
, &info_ptr
);
618 bool Encode(const unsigned char* input
, ColorFormat format
,
619 const int width
, const int height
, int row_byte_width
,
620 bool discard_transparency
,
621 const std::vector
<Comment
>& comments
,
622 std::vector
<unsigned char>* output
) {
623 return EncodeWithCompressionLevel(input
, format
, width
, height
,
625 discard_transparency
,
626 comments
, Z_DEFAULT_COMPRESSION
,
630 // Decode a PNG into an RGBA pixel array.
631 bool DecodePNG(const unsigned char* input
, size_t input_size
,
632 std::vector
<unsigned char>* output
,
633 int* width
, int* height
) {
634 return Decode(input
, input_size
, FORMAT_RGBA
, output
, width
, height
);
637 // Encode an RGBA pixel array into a PNG.
638 bool EncodeRGBAPNG(const unsigned char* input
,
642 std::vector
<unsigned char>* output
) {
643 return Encode(input
, FORMAT_RGBA
,
644 width
, height
, row_byte_width
, false,
645 std::vector
<Comment
>(), output
);
648 // Encode an BGRA pixel array into a PNG.
649 bool EncodeBGRAPNG(const unsigned char* input
,
653 bool discard_transparency
,
654 std::vector
<unsigned char>* output
) {
655 return Encode(input
, FORMAT_BGRA
,
656 width
, height
, row_byte_width
, discard_transparency
,
657 std::vector
<Comment
>(), output
);
660 bool EncodeBGRAPNGWithChecksum(const unsigned char* input
,
664 bool discard_transparency
,
665 const std::string
& checksum
,
666 std::vector
<unsigned char>* output
) {
667 std::vector
<Comment
> comments
;
668 comments
.push_back(Comment("checksum", checksum
));
669 return Encode(input
, FORMAT_BGRA
,
670 width
, height
, row_byte_width
, discard_transparency
,
674 bool EncodeRGBAPNGWithChecksum(const unsigned char* input
,
678 bool discard_transparency
,
679 const std::string
& checksum
,
680 std::vector
<unsigned char>* output
) {
681 std::vector
<Comment
> comments
;
682 comments
.push_back(Comment("checksum", checksum
));
683 return Encode(input
, FORMAT_RGBA
,
684 width
, height
, row_byte_width
, discard_transparency
,
688 } // namespace webkit_support