1 // Copyright 2013 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 // This is a duplicate of chromium's src/tools/imagediff/image_diff_png.cc
6 // that has been modified to build in a pdfium environment, which itself
7 // was duplicated as follows:
9 // This is a duplicate of ui/gfx/codec/png_codec.cc, after removing code related
10 // to Skia, that we can use when running layout tests with minimal dependencies.
12 #include "image_diff_png.h"
19 #include "../third_party/base/logging.h"
20 #include "../core/src/fxcodec/fx_lpng/include/fx_png.h"
21 #include "../core/src/fxcodec/fx_zlib/include/fx_zlib.h"
23 namespace image_diff_png {
28 // 3 bytes per pixel (packed), in RGB order regardless of endianness.
29 // This is the native JPEG format.
32 // 4 bytes per pixel, in RGBA order in memory regardless of endianness.
35 // 4 bytes per pixel, in BGRA order in memory regardless of endianness.
36 // This is the default Windows DIB order.
40 // Represents a comment in the tEXt ancillary chunk of the png.
46 // Converts BGRA->RGBA and RGBA->BGRA.
47 void ConvertBetweenBGRAandRGBA(const unsigned char* input, int pixel_width,
48 unsigned char* output, bool* is_opaque) {
49 for (int x = 0; x < pixel_width; x++) {
50 const unsigned char* pixel_in = &input[x * 4];
51 unsigned char* pixel_out = &output[x * 4];
52 pixel_out[0] = pixel_in[2];
53 pixel_out[1] = pixel_in[1];
54 pixel_out[2] = pixel_in[0];
55 pixel_out[3] = pixel_in[3];
59 void ConvertRGBAtoRGB(const unsigned char* rgba, int pixel_width,
60 unsigned char* rgb, bool* is_opaque) {
61 for (int x = 0; x < pixel_width; x++) {
62 const unsigned char* pixel_in = &rgba[x * 4];
63 unsigned char* pixel_out = &rgb[x * 3];
64 pixel_out[0] = pixel_in[0];
65 pixel_out[1] = pixel_in[1];
66 pixel_out[2] = pixel_in[2];
72 // Decoder --------------------------------------------------------------------
74 // This code is based on WebKit libpng interface (PNGImageDecoder), which is
75 // in turn based on the Mozilla png decoder.
79 // Gamma constants: We assume we're on Windows which uses a gamma of 2.2.
80 const double kMaxGamma = 21474.83; // Maximum gamma accepted by png library.
81 const double kDefaultGamma = 2.2;
82 const double kInverseGamma = 1.0 / kDefaultGamma;
84 class PngDecoderState {
86 // Output is a vector<unsigned char>.
87 PngDecoderState(ColorFormat ofmt, std::vector<unsigned char>* o)
88 : output_format(ofmt),
98 ColorFormat output_format;
101 // Used during the reading of an SkBitmap. Defaults to true until we see a
102 // pixel with anything other than an alpha of 255.
105 // An intermediary buffer for decode output.
106 std::vector<unsigned char>* output;
108 // Called to convert a row from the library to the correct output format.
109 // When NULL, no conversion is necessary.
110 void (*row_converter)(const unsigned char* in, int w, unsigned char* out,
113 // Size of the image, set in the info callback.
117 // Set to true when we've found the end of the data.
121 void ConvertRGBtoRGBA(const unsigned char* rgb, int pixel_width,
122 unsigned char* rgba, bool* is_opaque) {
123 for (int x = 0; x < pixel_width; x++) {
124 const unsigned char* pixel_in = &rgb[x * 3];
125 unsigned char* pixel_out = &rgba[x * 4];
126 pixel_out[0] = pixel_in[0];
127 pixel_out[1] = pixel_in[1];
128 pixel_out[2] = pixel_in[2];
133 void ConvertRGBtoBGRA(const unsigned char* rgb, int pixel_width,
134 unsigned char* bgra, bool* is_opaque) {
135 for (int x = 0; x < pixel_width; x++) {
136 const unsigned char* pixel_in = &rgb[x * 3];
137 unsigned char* pixel_out = &bgra[x * 4];
138 pixel_out[0] = pixel_in[2];
139 pixel_out[1] = pixel_in[1];
140 pixel_out[2] = pixel_in[0];
145 // Called when the png header has been read. This code is based on the WebKit
147 void DecodeInfoCallback(png_struct* png_ptr, png_info* info_ptr) {
148 PngDecoderState* state = static_cast<PngDecoderState*>(
149 png_get_progressive_ptr(png_ptr));
151 int bit_depth, color_type, interlace_type, compression_type;
152 int filter_type, channels;
154 png_get_IHDR(png_ptr, info_ptr, &w, &h, &bit_depth, &color_type,
155 &interlace_type, &compression_type, &filter_type);
157 // Bounds check. When the image is unreasonably big, we'll error out and
158 // end up back at the setjmp call when we set up decoding. "Unreasonably big"
159 // means "big enough that w * h * 32bpp might overflow an int"; we choose this
160 // threshold to match WebKit and because a number of places in code assume
161 // that an image's size (in bytes) fits in a (signed) int.
162 unsigned long long total_size =
163 static_cast<unsigned long long>(w) * static_cast<unsigned long long>(h);
164 if (total_size > ((1 << 29) - 1))
165 longjmp(png_jmpbuf(png_ptr), 1);
166 state->width = static_cast<int>(w);
167 state->height = static_cast<int>(h);
169 // Expand to ensure we use 24-bit for RGB and 32-bit for RGBA.
170 if (color_type == PNG_COLOR_TYPE_PALETTE ||
171 (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8))
172 png_set_expand(png_ptr);
174 // Transparency for paletted images.
175 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
176 png_set_expand(png_ptr);
178 // Convert 16-bit to 8-bit.
180 png_set_strip_16(png_ptr);
182 // Expand grayscale to RGB.
183 if (color_type == PNG_COLOR_TYPE_GRAY ||
184 color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
185 png_set_gray_to_rgb(png_ptr);
187 // Deal with gamma and keep it under our control.
189 if (png_get_gAMA(png_ptr, info_ptr, &gamma)) {
190 if (gamma <= 0.0 || gamma > kMaxGamma) {
191 gamma = kInverseGamma;
192 png_set_gAMA(png_ptr, info_ptr, gamma);
194 png_set_gamma(png_ptr, kDefaultGamma, gamma);
196 png_set_gamma(png_ptr, kDefaultGamma, kInverseGamma);
199 // Tell libpng to send us rows for interlaced pngs.
200 if (interlace_type == PNG_INTERLACE_ADAM7)
201 png_set_interlace_handling(png_ptr);
203 // Update our info now
204 png_read_update_info(png_ptr, info_ptr);
205 channels = png_get_channels(png_ptr, info_ptr);
207 // Pick our row format converter necessary for this data.
209 switch (state->output_format) {
211 state->row_converter = NULL; // no conversion necessary
212 state->output_channels = 3;
215 state->row_converter = &ConvertRGBtoRGBA;
216 state->output_channels = 4;
219 state->row_converter = &ConvertRGBtoBGRA;
220 state->output_channels = 4;
223 } else if (channels == 4) {
224 switch (state->output_format) {
226 state->row_converter = &ConvertRGBAtoRGB;
227 state->output_channels = 3;
230 state->row_converter = NULL; // no conversion necessary
231 state->output_channels = 4;
234 state->row_converter = &ConvertBetweenBGRAandRGBA;
235 state->output_channels = 4;
240 longjmp(png_jmpbuf(png_ptr), 1);
243 state->output->resize(
244 state->width * state->output_channels * state->height);
247 void DecodeRowCallback(png_struct* png_ptr, png_byte* new_row,
248 png_uint_32 row_num, int pass) {
249 PngDecoderState* state = static_cast<PngDecoderState*>(
250 png_get_progressive_ptr(png_ptr));
252 if (static_cast<int>(row_num) > state->height) {
257 unsigned char* base = NULL;
258 base = &state->output->front();
260 unsigned char* dest = &base[state->width * state->output_channels * row_num];
261 if (state->row_converter)
262 state->row_converter(new_row, state->width, dest, &state->is_opaque);
264 memcpy(dest, new_row, state->width * state->output_channels);
267 void DecodeEndCallback(png_struct* png_ptr, png_info* info) {
268 PngDecoderState* state = static_cast<PngDecoderState*>(
269 png_get_progressive_ptr(png_ptr));
271 // Mark the image as complete, this will tell the Decode function that we
272 // have successfully found the end of the data.
276 // Automatically destroys the given read structs on destruction to make
277 // cleanup and error handling code cleaner.
278 class PngReadStructDestroyer {
280 PngReadStructDestroyer(png_struct** ps, png_info** pi) : ps_(ps), pi_(pi) {
282 ~PngReadStructDestroyer() {
283 png_destroy_read_struct(ps_, pi_, NULL);
290 bool BuildPNGStruct(const unsigned char* input, size_t input_size,
291 png_struct** png_ptr, png_info** info_ptr) {
293 return false; // Input data too small to be a png
295 // Have libpng check the signature, it likes the first 8 bytes.
296 if (png_sig_cmp(const_cast<unsigned char*>(input), 0, 8) != 0)
299 *png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
303 *info_ptr = png_create_info_struct(*png_ptr);
305 png_destroy_read_struct(png_ptr, NULL, NULL);
315 bool Decode(const unsigned char* input, size_t input_size,
316 ColorFormat format, std::vector<unsigned char>* output,
318 png_struct* png_ptr = NULL;
319 png_info* info_ptr = NULL;
320 if (!BuildPNGStruct(input, input_size, &png_ptr, &info_ptr))
323 PngReadStructDestroyer destroyer(&png_ptr, &info_ptr);
324 if (setjmp(png_jmpbuf(png_ptr))) {
325 // The destroyer will ensure that the structures are cleaned up in this
326 // case, even though we may get here as a jump from random parts of the
327 // PNG library called below.
331 PngDecoderState state(format, output);
333 png_set_progressive_read_fn(png_ptr, &state, &DecodeInfoCallback,
334 &DecodeRowCallback, &DecodeEndCallback);
335 png_process_data(png_ptr,
337 const_cast<unsigned char*>(input),
341 // Fed it all the data but the library didn't think we got all the data, so
342 // this file must be truncated.
352 // Encoder --------------------------------------------------------------------
354 // This section of the code is based on nsPNGEncoder.cpp in Mozilla
355 // (Copyright 2005 Google Inc.)
359 // Passed around as the io_ptr in the png structs so our callbacks know where
361 struct PngEncoderState {
362 explicit PngEncoderState(std::vector<unsigned char>* o) : out(o) {}
363 std::vector<unsigned char>* out;
366 // Called by libpng to flush its internal buffer to ours.
367 void EncoderWriteCallback(png_structp png, png_bytep data, png_size_t size) {
368 PngEncoderState* state = static_cast<PngEncoderState*>(png_get_io_ptr(png));
369 size_t old_size = state->out->size();
370 state->out->resize(old_size + size);
371 memcpy(&(*state->out)[old_size], data, size);
374 void FakeFlushCallback(png_structp png) {
375 // We don't need to perform any flushing since we aren't doing real IO, but
376 // we're required to provide this function by libpng.
379 void ConvertBGRAtoRGB(const unsigned char* bgra, int pixel_width,
380 unsigned char* rgb, bool* is_opaque) {
381 for (int x = 0; x < pixel_width; x++) {
382 const unsigned char* pixel_in = &bgra[x * 4];
383 unsigned char* pixel_out = &rgb[x * 3];
384 pixel_out[0] = pixel_in[2];
385 pixel_out[1] = pixel_in[1];
386 pixel_out[2] = pixel_in[0];
390 #ifdef PNG_TEXT_SUPPORTED
392 inline char* strdup(const char* str) {
396 return ::strdup(str);
400 class CommentWriter {
402 explicit CommentWriter(const std::vector<Comment>& comments)
403 : comments_(comments),
404 png_text_(new png_text[comments.size()]) {
405 for (size_t i = 0; i < comments.size(); ++i)
406 AddComment(i, comments[i]);
410 for (size_t i = 0; i < comments_.size(); ++i) {
411 free(png_text_[i].key);
412 free(png_text_[i].text);
418 return !comments_.empty();
421 png_text* get_png_text() {
426 return static_cast<int>(comments_.size());
430 void AddComment(size_t pos, const Comment& comment) {
431 png_text_[pos].compression = PNG_TEXT_COMPRESSION_NONE;
432 // A PNG comment's key can only be 79 characters long.
433 if (comment.key.length() > 79)
435 png_text_[pos].key = strdup(comment.key.substr(0, 78).c_str());
436 png_text_[pos].text = strdup(comment.text.c_str());
437 png_text_[pos].text_length = comment.text.length();
438 #ifdef PNG_iTXt_SUPPORTED
439 png_text_[pos].itxt_length = 0;
440 png_text_[pos].lang = 0;
441 png_text_[pos].lang_key = 0;
445 const std::vector<Comment> comments_;
448 #endif // PNG_TEXT_SUPPORTED
450 // The type of functions usable for converting between pixel formats.
451 typedef void (*FormatConverter)(const unsigned char* in, int w,
452 unsigned char* out, bool* is_opaque);
454 // libpng uses a wacky setjmp-based API, which makes the compiler nervous.
455 // We constrain all of the calls we make to libpng where the setjmp() is in
456 // place to this function.
457 // Returns true on success.
458 bool DoLibpngWrite(png_struct* png_ptr, png_info* info_ptr,
459 PngEncoderState* state,
460 int width, int height, int row_byte_width,
461 const unsigned char* input, int compression_level,
462 int png_output_color_type, int output_color_components,
463 FormatConverter converter,
464 const std::vector<Comment>& comments) {
465 #ifdef PNG_TEXT_SUPPORTED
466 CommentWriter comment_writer(comments);
468 unsigned char* row_buffer = NULL;
470 // Make sure to not declare any locals here -- locals in the presence
471 // of setjmp() in C++ code makes gcc complain.
473 if (setjmp(png_jmpbuf(png_ptr))) {
478 png_set_compression_level(png_ptr, compression_level);
480 // Set our callback for libpng to give us the data.
481 png_set_write_fn(png_ptr, state, EncoderWriteCallback, FakeFlushCallback);
483 png_set_IHDR(png_ptr, info_ptr, width, height, 8, png_output_color_type,
484 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
485 PNG_FILTER_TYPE_DEFAULT);
487 #ifdef PNG_TEXT_SUPPORTED
488 if (comment_writer.HasComments()) {
489 png_set_text(png_ptr, info_ptr, comment_writer.get_png_text(),
490 comment_writer.size());
494 png_write_info(png_ptr, info_ptr);
497 // No conversion needed, give the data directly to libpng.
498 for (int y = 0; y < height; y ++) {
499 png_write_row(png_ptr,
500 const_cast<unsigned char*>(&input[y * row_byte_width]));
503 // Needs conversion using a separate buffer.
504 row_buffer = new unsigned char[width * output_color_components];
505 for (int y = 0; y < height; y ++) {
506 converter(&input[y * row_byte_width], width, row_buffer, NULL);
507 png_write_row(png_ptr, row_buffer);
512 png_write_end(png_ptr, info_ptr);
519 bool EncodeWithCompressionLevel(const unsigned char* input, ColorFormat format,
520 const int width, const int height,
522 bool discard_transparency,
523 const std::vector<Comment>& comments,
524 int compression_level,
525 std::vector<unsigned char>* output) {
526 // Run to convert an input row into the output row format, NULL means no
527 // conversion is necessary.
528 FormatConverter converter = NULL;
530 int input_color_components, output_color_components;
531 int png_output_color_type;
534 input_color_components = 3;
535 output_color_components = 3;
536 png_output_color_type = PNG_COLOR_TYPE_RGB;
537 discard_transparency = false;
541 input_color_components = 4;
542 if (discard_transparency) {
543 output_color_components = 3;
544 png_output_color_type = PNG_COLOR_TYPE_RGB;
545 converter = ConvertRGBAtoRGB;
547 output_color_components = 4;
548 png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
554 input_color_components = 4;
555 if (discard_transparency) {
556 output_color_components = 3;
557 png_output_color_type = PNG_COLOR_TYPE_RGB;
558 converter = ConvertBGRAtoRGB;
560 output_color_components = 4;
561 png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
562 converter = ConvertBetweenBGRAandRGBA;
567 // Row stride should be at least as long as the length of the data.
568 if (input_color_components * width < row_byte_width)
571 png_struct* png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
575 png_info* info_ptr = png_create_info_struct(png_ptr);
577 png_destroy_write_struct(&png_ptr, NULL);
581 PngEncoderState state(output);
582 bool success = DoLibpngWrite(png_ptr, info_ptr, &state,
583 width, height, row_byte_width,
584 input, compression_level, png_output_color_type,
585 output_color_components, converter, comments);
586 png_destroy_write_struct(&png_ptr, &info_ptr);
592 bool Encode(const unsigned char* input, ColorFormat format,
593 const int width, const int height, int row_byte_width,
594 bool discard_transparency,
595 const std::vector<Comment>& comments,
596 std::vector<unsigned char>* output) {
597 return EncodeWithCompressionLevel(input, format, width, height,
599 discard_transparency,
600 comments, Z_DEFAULT_COMPRESSION,
604 // Decode a PNG into an RGBA pixel array.
605 bool DecodePNG(const unsigned char* input, size_t input_size,
606 std::vector<unsigned char>* output,
607 int* width, int* height) {
608 return Decode(input, input_size, FORMAT_RGBA, output, width, height);
611 // Encode an RGBA pixel array into a PNG.
612 bool EncodeRGBAPNG(const unsigned char* input,
616 std::vector<unsigned char>* output) {
617 return Encode(input, FORMAT_RGBA,
618 width, height, row_byte_width, false,
619 std::vector<Comment>(), output);
622 // Encode an BGRA pixel array into a PNG.
623 bool EncodeBGRAPNG(const unsigned char* input,
627 bool discard_transparency,
628 std::vector<unsigned char>* output) {
629 return Encode(input, FORMAT_BGRA,
630 width, height, row_byte_width, discard_transparency,
631 std::vector<Comment>(), output);