Pass CreateDirectory errors up to IndexedDB.
[chromium-blink-merge.git] / tools / imagediff / image_diff.cc
blobff6269e4cdd51fa9e8f7e18a0540db3aa8c4ee4a
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.
11 #include <algorithm>
12 #include <iostream>
13 #include <string>
14 #include <vector>
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"
29 #if defined(OS_WIN)
30 #include "windows.h"
31 #endif
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;
43 // Color codes.
44 static const uint32 RGBA_RED = 0x000000ff;
45 static const uint32 RGBA_ALPHA = 0xff000000;
47 class Image {
48 public:
49 Image() : w_(0), h_(0) {
52 Image(const Image& image)
53 : w_(image.w_),
54 h_(image.h_),
55 data_(image.data_) {
58 bool has_image() const {
59 return w_ > 0 && h_ > 0;
62 int w() const {
63 return w_;
66 int h() const {
67 return h_;
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) {
77 if (byte_length == 0)
78 return false;
80 scoped_ptr<unsigned char[]> source(new unsigned char[byte_length]);
81 if (fread(source.get(), 1, byte_length, stdin) != byte_length)
82 return false;
84 if (!gfx::PNGCodec::Decode(source.get(), byte_length,
85 gfx::PNGCodec::FORMAT_RGBA,
86 &data_, &w_, &h_)) {
87 Clear();
88 return false;
90 return true;
93 // Creates the image from the given filename on disk, and returns true on
94 // success.
95 bool CreateFromFilename(const base::FilePath& path) {
96 FILE* f = file_util::OpenFile(path, "rb");
97 if (!f)
98 return false;
100 std::vector<unsigned char> compressed;
101 const int buf_size = 1024;
102 unsigned char buf[buf_size];
103 size_t num_read = 0;
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_)) {
112 Clear();
113 return false;
115 return true;
118 void Clear() {
119 w_ = h_ = 0;
120 data_.clear();
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;
137 private:
138 // pixel dimensions of the image
139 int w_, h_;
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))
153 pixels_different++;
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;
176 void PrintHelp() {
177 fprintf(stderr,
178 "Usage:\n"
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)
188 "\n"
189 " image_diff -s\n"
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) {
198 Image actual_image;
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());
204 return kStatusError;
206 if (!baseline_image.CreateFromFilename(file2)) {
207 fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n",
208 file2.value().c_str());
209 return kStatusError;
212 float percent = PercentageDifferent(actual_image, baseline_image);
213 if (percent > 0.0) {
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;
220 // success
221 printf("diff: %01.2f%% passed\n", percent);
222 return kStatusSame;
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
227 char buffer[2048];
228 while (fgets(buffer, sizeof(buffer), stdin)) {
230 if (strncmp("Content-length: ", buffer, 16) == 0) {
231 char* context;
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);
239 return 1;
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);
244 return 1;
246 } else {
247 fputs("Error, image size must be specified.\n", stderr);
248 return 1;
252 if (actual_image.has_image() && baseline_image.has_image()) {
253 float percent = PercentageDifferent(actual_image, baseline_image);
254 if (percent > 0.0) {
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);
258 } else {
259 // success
260 printf("diff: %01.2f%% passed\n", percent);
262 actual_image.Clear();
263 baseline_image.Clear();
266 fflush(stdout);
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
278 // are different.
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);
285 same = false;
286 } else {
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);
295 return same;
298 int DiffImages(const base::FilePath& file1, const base::FilePath& file2,
299 const base::FilePath& out_file) {
300 Image actual_image;
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());
306 return kStatusError;
308 if (!baseline_image.CreateFromFilename(file2)) {
309 fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n",
310 file2.value().c_str());
311 return kStatusError;
314 Image diff_image;
315 bool same = CreateImageDiff(baseline_image, actual_image, &diff_image);
316 if (same)
317 return kStatusSame;
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)
327 return kStatusError;
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) {
336 #if defined(OS_WIN)
337 return base::FilePath(ASCIIToWide(str));
338 #else
339 return base::FilePath(str);
340 #endif
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())
353 continue;
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)
359 printf("error\n");
360 fflush(stdout);
361 filename1 = base::FilePath();
362 } else {
363 // Save the first filename in another buffer and wait for the second
364 // filename to arrive via stdin.
365 filename1 = FilePathFromASCII(stdin_buffer);
368 return 0;
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]));
382 PrintHelp();
383 return kStatusError;