1 // Copyright (c) 2011 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 file input format is based loosely on
6 // Tools/DumpRenderTree/ImageDiff.m
8 // The exact format of this tool's output to stdout is important, to match
9 // what the run-webkit-tests script expects.
16 #include "base/basictypes.h"
17 #include "base/command_line.h"
18 #include "base/file_util.h"
19 #include "base/files/file_path.h"
20 #include "base/logging.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/process_util.h"
23 #include "base/safe_numerics.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "ui/gfx/codec/png_codec.h"
27 #include "ui/gfx/size.h"
33 // Causes the app to remain open, waiting for pairs of filenames on stdin.
34 // The caller is then responsible for terminating this app.
35 static const char kOptionPollStdin
[] = "use-stdin";
36 static const char kOptionGenerateDiff
[] = "diff";
38 // Return codes used by this utility.
39 static const int kStatusSame
= 0;
40 static const int kStatusDifferent
= 1;
41 static const int kStatusError
= 2;
44 static const uint32 RGBA_RED
= 0x000000ff;
45 static const uint32 RGBA_ALPHA
= 0xff000000;
49 Image() : w_(0), h_(0) {
52 Image(const Image
& image
)
58 bool has_image() const {
59 return w_
> 0 && h_
> 0;
70 const unsigned char* data() const {
71 return &data_
.front();
74 // Creates the image from stdin with the given data length. On success, it
75 // will return true. On failure, no other methods should be accessed.
76 bool CreateFromStdin(size_t byte_length
) {
80 scoped_ptr
<unsigned char[]> source(new unsigned char[byte_length
]);
81 if (fread(source
.get(), 1, byte_length
, stdin
) != byte_length
)
84 if (!gfx::PNGCodec::Decode(source
.get(), byte_length
,
85 gfx::PNGCodec::FORMAT_RGBA
,
93 // Creates the image from the given filename on disk, and returns true on
95 bool CreateFromFilename(const base::FilePath
& path
) {
96 FILE* f
= file_util::OpenFile(path
, "rb");
100 std::vector
<unsigned char> compressed
;
101 const int buf_size
= 1024;
102 unsigned char buf
[buf_size
];
104 while ((num_read
= fread(buf
, 1, buf_size
, f
)) > 0) {
105 compressed
.insert(compressed
.end(), buf
, buf
+ num_read
);
108 file_util::CloseFile(f
);
110 if (!gfx::PNGCodec::Decode(&compressed
[0], compressed
.size(),
111 gfx::PNGCodec::FORMAT_RGBA
, &data_
, &w_
, &h_
)) {
123 // Returns the RGBA value of the pixel at the given location
124 uint32
pixel_at(int x
, int y
) const {
125 DCHECK(x
>= 0 && x
< w_
);
126 DCHECK(y
>= 0 && y
< h_
);
127 return *reinterpret_cast<const uint32
*>(&(data_
[(y
* w_
+ x
) * 4]));
130 void set_pixel_at(int x
, int y
, uint32 color
) const {
131 DCHECK(x
>= 0 && x
< w_
);
132 DCHECK(y
>= 0 && y
< h_
);
133 void* addr
= &const_cast<unsigned char*>(&data_
.front())[(y
* w_
+ x
) * 4];
134 *reinterpret_cast<uint32
*>(addr
) = color
;
138 // pixel dimensions of the image
141 std::vector
<unsigned char> data_
;
144 float PercentageDifferent(const Image
& baseline
, const Image
& actual
) {
145 int w
= std::min(baseline
.w(), actual
.w());
146 int h
= std::min(baseline
.h(), actual
.h());
148 // compute pixels different in the overlap
149 int pixels_different
= 0;
150 for (int y
= 0; y
< h
; y
++) {
151 for (int x
= 0; x
< w
; x
++) {
152 if (baseline
.pixel_at(x
, y
) != actual
.pixel_at(x
, y
))
157 // count pixels that are a difference in size as also being different
158 int max_w
= std::max(baseline
.w(), actual
.w());
159 int max_h
= std::max(baseline
.h(), actual
.h());
161 // ...pixels off the right side, but not including the lower right corner
162 pixels_different
+= (max_w
- w
) * h
;
164 // ...pixels along the bottom, including the lower right corner
165 pixels_different
+= (max_h
- h
) * max_w
;
167 // Like the WebKit ImageDiff tool, we define percentage different in terms
168 // of the size of the 'actual' bitmap.
169 float total_pixels
= static_cast<float>(actual
.w()) *
170 static_cast<float>(actual
.h());
171 if (total_pixels
== 0)
172 return 100.0f
; // when the bitmap is empty, they are 100% different
173 return static_cast<float>(pixels_different
) / total_pixels
* 100;
179 " image_diff <compare file> <reference file>\n"
180 " Compares two files on disk, returning 0 when they are the same\n"
181 " image_diff --use-stdin\n"
182 " Stays open reading pairs of filenames from stdin, comparing them,\n"
183 " and sending 0 to stdout when they are the same\n"
184 " image_diff --diff <compare file> <reference file> <output file>\n"
185 " Compares two files on disk, outputs an image that visualizes the"
186 " difference to <output file>\n");
187 /* For unfinished webkit-like-mode (see below)
190 " Reads stream input from stdin, should be EXACTLY of the format\n"
191 " \"Content-length: <byte length> <data>Content-length: ...\n"
192 " it will take as many file pairs as given, and will compare them as\n"
193 " (cmp_file, reference_file) pairs\n");
197 int CompareImages(const base::FilePath
& file1
, const base::FilePath
& file2
) {
199 Image baseline_image
;
201 if (!actual_image
.CreateFromFilename(file1
)) {
202 fprintf(stderr
, "image_diff: Unable to open file \"%" PRFilePath
"\"\n",
203 file1
.value().c_str());
206 if (!baseline_image
.CreateFromFilename(file2
)) {
207 fprintf(stderr
, "image_diff: Unable to open file \"%" PRFilePath
"\"\n",
208 file2
.value().c_str());
212 float percent
= PercentageDifferent(actual_image
, baseline_image
);
214 // failure: The WebKit version also writes the difference image to
215 // stdout, which seems excessive for our needs.
216 printf("diff: %01.2f%% failed\n", percent
);
217 return kStatusDifferent
;
221 printf("diff: %01.2f%% passed\n", percent
);
224 /* Untested mode that acts like WebKit's image comparator. I wrote this but
225 decided it's too complicated. We may use it in the future if it looks useful
228 while (fgets(buffer, sizeof(buffer), stdin)) {
230 if (strncmp("Content-length: ", buffer, 16) == 0) {
232 strtok_s(buffer, " ", &context);
233 int image_size = strtol(strtok_s(NULL, " ", &context), NULL, 10);
235 bool success = false;
236 if (image_size > 0 && actual_image.has_image() == 0) {
237 if (!actual_image.CreateFromStdin(image_size)) {
238 fputs("Error, input image can't be decoded.\n", stderr);
241 } else if (image_size > 0 && baseline_image.has_image() == 0) {
242 if (!baseline_image.CreateFromStdin(image_size)) {
243 fputs("Error, baseline image can't be decoded.\n", stderr);
247 fputs("Error, image size must be specified.\n", stderr);
252 if (actual_image.has_image() && baseline_image.has_image()) {
253 float percent = PercentageDifferent(actual_image, baseline_image);
255 // failure: The WebKit version also writes the difference image to
256 // stdout, which seems excessive for our needs.
257 printf("diff: %01.2f%% failed\n", percent);
260 printf("diff: %01.2f%% passed\n", percent);
262 actual_image.Clear();
263 baseline_image.Clear();
271 bool CreateImageDiff(const Image
& image1
, const Image
& image2
, Image
* out
) {
272 int w
= std::min(image1
.w(), image2
.w());
273 int h
= std::min(image1
.h(), image2
.h());
274 *out
= Image(image1
);
275 bool same
= (image1
.w() == image2
.w()) && (image1
.h() == image2
.h());
277 // TODO(estade): do something with the extra pixels if the image sizes
279 for (int y
= 0; y
< h
; y
++) {
280 for (int x
= 0; x
< w
; x
++) {
281 uint32 base_pixel
= image1
.pixel_at(x
, y
);
282 if (base_pixel
!= image2
.pixel_at(x
, y
)) {
283 // Set differing pixels red.
284 out
->set_pixel_at(x
, y
, RGBA_RED
| RGBA_ALPHA
);
287 // Set same pixels as faded.
288 uint32 alpha
= base_pixel
& RGBA_ALPHA
;
289 uint32 new_pixel
= base_pixel
- ((alpha
/ 2) & RGBA_ALPHA
);
290 out
->set_pixel_at(x
, y
, new_pixel
);
298 int DiffImages(const base::FilePath
& file1
, const base::FilePath
& file2
,
299 const base::FilePath
& out_file
) {
301 Image baseline_image
;
303 if (!actual_image
.CreateFromFilename(file1
)) {
304 fprintf(stderr
, "image_diff: Unable to open file \"%" PRFilePath
"\"\n",
305 file1
.value().c_str());
308 if (!baseline_image
.CreateFromFilename(file2
)) {
309 fprintf(stderr
, "image_diff: Unable to open file \"%" PRFilePath
"\"\n",
310 file2
.value().c_str());
315 bool same
= CreateImageDiff(baseline_image
, actual_image
, &diff_image
);
319 std::vector
<unsigned char> png_encoding
;
320 gfx::PNGCodec::Encode(diff_image
.data(), gfx::PNGCodec::FORMAT_RGBA
,
321 gfx::Size(diff_image
.w(), diff_image
.h()),
322 diff_image
.w() * 4, false,
323 std::vector
<gfx::PNGCodec::Comment
>(), &png_encoding
);
324 if (file_util::WriteFile(out_file
,
325 reinterpret_cast<char*>(&png_encoding
.front()),
326 base::checked_numeric_cast
<int>(png_encoding
.size())) < 0)
329 return kStatusDifferent
;
332 // It isn't strictly correct to only support ASCII paths, but this
333 // program reads paths on stdin and the program that spawns it outputs
334 // paths as non-wide strings anyway.
335 base::FilePath
FilePathFromASCII(const std::string
& str
) {
337 return base::FilePath(ASCIIToWide(str
));
339 return base::FilePath(str
);
343 int main(int argc
, const char* argv
[]) {
344 base::EnableTerminationOnHeapCorruption();
345 CommandLine::Init(argc
, argv
);
346 const CommandLine
& parsed_command_line
= *CommandLine::ForCurrentProcess();
347 if (parsed_command_line
.HasSwitch(kOptionPollStdin
)) {
348 // Watch stdin for filenames.
349 std::string stdin_buffer
;
350 base::FilePath filename1
;
351 while (std::getline(std::cin
, stdin_buffer
)) {
352 if (stdin_buffer
.empty())
355 if (!filename1
.empty()) {
356 // CompareImages writes results to stdout unless an error occurred.
357 base::FilePath filename2
= FilePathFromASCII(stdin_buffer
);
358 if (CompareImages(filename1
, filename2
) == kStatusError
)
361 filename1
= base::FilePath();
363 // Save the first filename in another buffer and wait for the second
364 // filename to arrive via stdin.
365 filename1
= FilePathFromASCII(stdin_buffer
);
371 const CommandLine::StringVector
& args
= parsed_command_line
.GetArgs();
372 if (parsed_command_line
.HasSwitch(kOptionGenerateDiff
)) {
373 if (args
.size() == 3) {
374 return DiffImages(base::FilePath(args
[0]),
375 base::FilePath(args
[1]),
376 base::FilePath(args
[2]));
378 } else if (args
.size() == 2) {
379 return CompareImages(base::FilePath(args
[0]), base::FilePath(args
[1]));