xref: /aosp_15_r20/external/pdfium/testing/image_diff/image_diff.cpp (revision 3ac0a46f773bac49fa9476ec2b1cf3f8da5ec3a4)
1 // Copyright 2011 The PDFium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // This file input format is based loosely on
6 // Tools/DumpRenderTree/ImageDiff.m
7 
8 // The exact format of this tool's output to stdout is important, to match
9 // what the run-webkit-tests script expects.
10 
11 #include <stdint.h>
12 #include <stdio.h>
13 #include <string.h>
14 
15 #include <algorithm>
16 #include <cmath>
17 #include <map>
18 #include <string>
19 #include <vector>
20 
21 #include "core/fxcrt/fx_memory.h"
22 #include "testing/image_diff/image_diff_png.h"
23 #include "testing/utils/path_service.h"
24 #include "third_party/base/numerics/safe_conversions.h"
25 
26 #if BUILDFLAG(IS_WIN)
27 #include <windows.h>
28 #endif
29 
30 // Return codes used by this utility.
31 constexpr int kStatusSame = 0;
32 constexpr int kStatusDifferent = 1;
33 constexpr int kStatusError = 2;
34 
35 // Color codes.
36 constexpr uint32_t RGBA_RED = 0x000000ff;
37 constexpr uint32_t RGBA_ALPHA = 0xff000000;
38 
39 class Image {
40  public:
41   Image() = default;
42   Image(const Image& image) = default;
43   Image& operator=(const Image& other) = default;
44 
has_image() const45   bool has_image() const { return w_ > 0 && h_ > 0; }
w() const46   int w() const { return w_; }
h() const47   int h() const { return h_; }
span() const48   pdfium::span<const uint8_t> span() const { return data_; }
49 
50   // Creates the image from the given filename on disk, and returns true on
51   // success.
CreateFromFilename(const std::string & path)52   bool CreateFromFilename(const std::string& path) {
53     return CreateFromFilenameImpl(path, /*reverse_byte_order=*/false);
54   }
55 
56   // Same as CreateFromFilename(), but with BGRA instead of RGBA ordering.
CreateFromFilenameWithReverseByteOrder(const std::string & path)57   bool CreateFromFilenameWithReverseByteOrder(const std::string& path) {
58     return CreateFromFilenameImpl(path, /*reverse_byte_order=*/true);
59   }
60 
Clear()61   void Clear() {
62     w_ = h_ = 0;
63     data_.clear();
64   }
65 
66   // Returns the RGBA value of the pixel at the given location
pixel_at(int x,int y) const67   uint32_t pixel_at(int x, int y) const {
68     if (!pixel_in_bounds(x, y))
69       return 0;
70     return *reinterpret_cast<const uint32_t*>(&(data_[pixel_address(x, y)]));
71   }
72 
set_pixel_at(int x,int y,uint32_t color)73   void set_pixel_at(int x, int y, uint32_t color) {
74     if (!pixel_in_bounds(x, y))
75       return;
76 
77     void* addr = &data_[pixel_address(x, y)];
78     *reinterpret_cast<uint32_t*>(addr) = color;
79   }
80 
81  private:
CreateFromFilenameImpl(const std::string & path,bool reverse_byte_order)82   bool CreateFromFilenameImpl(const std::string& path,
83                               bool reverse_byte_order) {
84     FILE* f = fopen(path.c_str(), "rb");
85     if (!f)
86       return false;
87 
88     std::vector<uint8_t> compressed;
89     const size_t kBufSize = 1024;
90     uint8_t buf[kBufSize];
91     size_t num_read = 0;
92     while ((num_read = fread(buf, 1, kBufSize, f)) > 0) {
93       compressed.insert(compressed.end(), buf, buf + num_read);
94     }
95 
96     fclose(f);
97 
98     data_ = image_diff_png::DecodePNG(compressed, reverse_byte_order, &w_, &h_);
99     if (data_.empty()) {
100       Clear();
101       return false;
102     }
103     return true;
104   }
105 
pixel_in_bounds(int x,int y) const106   bool pixel_in_bounds(int x, int y) const {
107     return x >= 0 && x < w_ && y >= 0 && y < h_;
108   }
109 
pixel_address(int x,int y) const110   size_t pixel_address(int x, int y) const { return (y * w_ + x) * 4; }
111 
112   // Pixel dimensions of the image.
113   int w_ = 0;
114   int h_ = 0;
115 
116   std::vector<uint8_t> data_;
117 };
118 
CalculateDifferencePercentage(const Image & actual,int pixels_different)119 float CalculateDifferencePercentage(const Image& actual, int pixels_different) {
120   // Like the WebKit ImageDiff tool, we define percentage different in terms
121   // of the size of the 'actual' bitmap.
122   float total_pixels =
123       static_cast<float>(actual.w()) * static_cast<float>(actual.h());
124   if (total_pixels == 0) {
125     // When the bitmap is empty, they are 100% different.
126     return 100.0f;
127   }
128   return 100.0f * pixels_different / total_pixels;
129 }
130 
CountImageSizeMismatchAsPixelDifference(const Image & baseline,const Image & actual,int * pixels_different)131 void CountImageSizeMismatchAsPixelDifference(const Image& baseline,
132                                              const Image& actual,
133                                              int* pixels_different) {
134   int w = std::min(baseline.w(), actual.w());
135   int h = std::min(baseline.h(), actual.h());
136 
137   // Count pixels that are a difference in size as also being different.
138   int max_w = std::max(baseline.w(), actual.w());
139   int max_h = std::max(baseline.h(), actual.h());
140   // These pixels are off the right side, not including the lower right corner.
141   *pixels_different += (max_w - w) * h;
142   // These pixels are along the bottom, including the lower right corner.
143   *pixels_different += (max_h - h) * max_w;
144 }
145 
146 struct UnpackedPixel {
UnpackedPixelUnpackedPixel147   explicit UnpackedPixel(uint32_t packed)
148       : red(packed & 0xff),
149         green((packed >> 8) & 0xff),
150         blue((packed >> 16) & 0xff),
151         alpha((packed >> 24) & 0xff) {}
152 
153   uint8_t red;
154   uint8_t green;
155   uint8_t blue;
156   uint8_t alpha;
157 };
158 
ChannelDelta(uint8_t baseline_channel,uint8_t actual_channel)159 uint8_t ChannelDelta(uint8_t baseline_channel, uint8_t actual_channel) {
160   // No casts are necessary because arithmetic operators implicitly convert
161   // `uint8_t` to `int` first. The final delta is always in the range 0 to 255.
162   return std::abs(baseline_channel - actual_channel);
163 }
164 
MaxPixelPerChannelDelta(const UnpackedPixel & baseline_pixel,const UnpackedPixel & actual_pixel)165 uint8_t MaxPixelPerChannelDelta(const UnpackedPixel& baseline_pixel,
166                                 const UnpackedPixel& actual_pixel) {
167   return std::max({ChannelDelta(baseline_pixel.red, actual_pixel.red),
168                    ChannelDelta(baseline_pixel.green, actual_pixel.green),
169                    ChannelDelta(baseline_pixel.blue, actual_pixel.blue),
170                    ChannelDelta(baseline_pixel.alpha, actual_pixel.alpha)});
171 }
172 
PercentageDifferent(const Image & baseline,const Image & actual,uint8_t max_pixel_per_channel_delta)173 float PercentageDifferent(const Image& baseline,
174                           const Image& actual,
175                           uint8_t max_pixel_per_channel_delta) {
176   int w = std::min(baseline.w(), actual.w());
177   int h = std::min(baseline.h(), actual.h());
178 
179   // Compute pixels different in the overlap.
180   int pixels_different = 0;
181   for (int y = 0; y < h; ++y) {
182     for (int x = 0; x < w; ++x) {
183       const uint32_t baseline_pixel = baseline.pixel_at(x, y);
184       const uint32_t actual_pixel = actual.pixel_at(x, y);
185       if (baseline_pixel == actual_pixel) {
186         continue;
187       }
188 
189       if (MaxPixelPerChannelDelta(UnpackedPixel(baseline_pixel),
190                                   UnpackedPixel(actual_pixel)) >
191           max_pixel_per_channel_delta) {
192         ++pixels_different;
193       }
194     }
195   }
196 
197   CountImageSizeMismatchAsPixelDifference(baseline, actual, &pixels_different);
198   return CalculateDifferencePercentage(actual, pixels_different);
199 }
200 
HistogramPercentageDifferent(const Image & baseline,const Image & actual)201 float HistogramPercentageDifferent(const Image& baseline, const Image& actual) {
202   // TODO(johnme): Consider using a joint histogram instead, as described in
203   // "Comparing Images Using Joint Histograms" by Pass & Zabih
204   // http://www.cs.cornell.edu/~rdz/papers/pz-jms99.pdf
205 
206   int w = std::min(baseline.w(), actual.w());
207   int h = std::min(baseline.h(), actual.h());
208 
209   // Count occurrences of each RGBA pixel value of baseline in the overlap.
210   std::map<uint32_t, int32_t> baseline_histogram;
211   for (int y = 0; y < h; ++y) {
212     for (int x = 0; x < w; ++x) {
213       // hash_map operator[] inserts a 0 (default constructor) if key not found.
214       ++baseline_histogram[baseline.pixel_at(x, y)];
215     }
216   }
217 
218   // Compute pixels different in the histogram of the overlap.
219   int pixels_different = 0;
220   for (int y = 0; y < h; ++y) {
221     for (int x = 0; x < w; ++x) {
222       uint32_t actual_rgba = actual.pixel_at(x, y);
223       auto it = baseline_histogram.find(actual_rgba);
224       if (it != baseline_histogram.end() && it->second > 0)
225         --it->second;
226       else
227         ++pixels_different;
228     }
229   }
230 
231   CountImageSizeMismatchAsPixelDifference(baseline, actual, &pixels_different);
232   return CalculateDifferencePercentage(actual, pixels_different);
233 }
234 
PrintHelp(const std::string & binary_name)235 void PrintHelp(const std::string& binary_name) {
236   fprintf(
237       stderr,
238       "Usage:\n"
239       "  %s OPTIONS <compare_file> <reference_file>\n"
240       "    Compares two files on disk, returning 0 when they are the same.\n"
241       "    Passing \"--histogram\" additionally calculates a diff of the\n"
242       "    RGBA value histograms (which is resistant to shifts in layout).\n"
243       "    Passing \"--reverse-byte-order\" additionally assumes the\n"
244       "    compare file has BGRA byte ordering.\n"
245       "    Passing \"--fuzzy\" additionally allows individual pixels to\n"
246       "    differ by at most 1 on each channel.\n\n"
247       "  %s --diff <compare_file> <reference_file> <output_file>\n"
248       "    Compares two files on disk, and if they differ, outputs an image\n"
249       "    to <output_file> that visualizes the differing pixels as red\n"
250       "    dots.\n\n"
251       "  %s --subtract <compare_file> <reference_file> <output_file>\n"
252       "    Compares two files on disk, and if they differ, outputs an image\n"
253       "    to <output_file> that visualizes the difference as a scaled\n"
254       "    subtraction of pixel values.\n",
255       binary_name.c_str(), binary_name.c_str(), binary_name.c_str());
256 }
257 
CompareImages(const std::string & binary_name,const std::string & file1,const std::string & file2,bool compare_histograms,bool reverse_byte_order,uint8_t max_pixel_per_channel_delta)258 int CompareImages(const std::string& binary_name,
259                   const std::string& file1,
260                   const std::string& file2,
261                   bool compare_histograms,
262                   bool reverse_byte_order,
263                   uint8_t max_pixel_per_channel_delta) {
264   Image actual_image;
265   Image baseline_image;
266 
267   bool actual_load_result =
268       reverse_byte_order
269           ? actual_image.CreateFromFilenameWithReverseByteOrder(file1)
270           : actual_image.CreateFromFilename(file1);
271   if (!actual_load_result) {
272     fprintf(stderr, "%s: Unable to open file \"%s\"\n", binary_name.c_str(),
273             file1.c_str());
274     return kStatusError;
275   }
276   if (!baseline_image.CreateFromFilename(file2)) {
277     fprintf(stderr, "%s: Unable to open file \"%s\"\n", binary_name.c_str(),
278             file2.c_str());
279     return kStatusError;
280   }
281 
282   if (compare_histograms) {
283     float percent = HistogramPercentageDifferent(actual_image, baseline_image);
284     const char* passed = percent > 0.0 ? "failed" : "passed";
285     printf("histogram diff: %01.2f%% %s\n", percent, passed);
286   }
287 
288   const char* const diff_name = compare_histograms ? "exact diff" : "diff";
289   float percent = PercentageDifferent(actual_image, baseline_image,
290                                       max_pixel_per_channel_delta);
291   const char* const passed = percent > 0.0 ? "failed" : "passed";
292   printf("%s: %01.2f%% %s\n", diff_name, percent, passed);
293 
294   if (percent > 0.0) {
295     // failure: The WebKit version also writes the difference image to
296     // stdout, which seems excessive for our needs.
297     return kStatusDifferent;
298   }
299   // success
300   return kStatusSame;
301 }
302 
CreateImageDiff(const Image & image1,const Image & image2,Image * out)303 bool CreateImageDiff(const Image& image1, const Image& image2, Image* out) {
304   int w = std::min(image1.w(), image2.w());
305   int h = std::min(image1.h(), image2.h());
306   *out = Image(image1);
307   bool same = (image1.w() == image2.w()) && (image1.h() == image2.h());
308 
309   // TODO(estade): do something with the extra pixels if the image sizes
310   // are different.
311   for (int y = 0; y < h; ++y) {
312     for (int x = 0; x < w; ++x) {
313       uint32_t base_pixel = image1.pixel_at(x, y);
314       if (base_pixel != image2.pixel_at(x, y)) {
315         // Set differing pixels red.
316         out->set_pixel_at(x, y, RGBA_RED | RGBA_ALPHA);
317         same = false;
318       } else {
319         // Set same pixels as faded.
320         uint32_t alpha = base_pixel & RGBA_ALPHA;
321         uint32_t new_pixel = base_pixel - ((alpha / 2) & RGBA_ALPHA);
322         out->set_pixel_at(x, y, new_pixel);
323       }
324     }
325   }
326 
327   return same;
328 }
329 
SubtractImages(const Image & image1,const Image & image2,Image * out)330 bool SubtractImages(const Image& image1, const Image& image2, Image* out) {
331   int w = std::min(image1.w(), image2.w());
332   int h = std::min(image1.h(), image2.h());
333   *out = Image(image1);
334   bool same = (image1.w() == image2.w()) && (image1.h() == image2.h());
335 
336   for (int y = 0; y < h; ++y) {
337     for (int x = 0; x < w; ++x) {
338       uint32_t pixel1 = image1.pixel_at(x, y);
339       int32_t r1 = pixel1 & 0xff;
340       int32_t g1 = (pixel1 >> 8) & 0xff;
341       int32_t b1 = (pixel1 >> 16) & 0xff;
342 
343       uint32_t pixel2 = image2.pixel_at(x, y);
344       int32_t r2 = pixel2 & 0xff;
345       int32_t g2 = (pixel2 >> 8) & 0xff;
346       int32_t b2 = (pixel2 >> 16) & 0xff;
347 
348       int32_t delta_r = r1 - r2;
349       int32_t delta_g = g1 - g2;
350       int32_t delta_b = b1 - b2;
351       same &= (delta_r == 0 && delta_g == 0 && delta_b == 0);
352 
353       delta_r = std::clamp(128 + delta_r * 8, 0, 255);
354       delta_g = std::clamp(128 + delta_g * 8, 0, 255);
355       delta_b = std::clamp(128 + delta_b * 8, 0, 255);
356 
357       uint32_t new_pixel = RGBA_ALPHA;
358       new_pixel |= delta_r;
359       new_pixel |= (delta_g << 8);
360       new_pixel |= (delta_b << 16);
361       out->set_pixel_at(x, y, new_pixel);
362     }
363   }
364   return same;
365 }
366 
DiffImages(const std::string & binary_name,const std::string & file1,const std::string & file2,const std::string & out_file,bool do_subtraction,bool reverse_byte_order)367 int DiffImages(const std::string& binary_name,
368                const std::string& file1,
369                const std::string& file2,
370                const std::string& out_file,
371                bool do_subtraction,
372                bool reverse_byte_order) {
373   Image actual_image;
374   Image baseline_image;
375 
376   bool actual_load_result =
377       reverse_byte_order
378           ? actual_image.CreateFromFilenameWithReverseByteOrder(file1)
379           : actual_image.CreateFromFilename(file1);
380 
381   if (!actual_load_result) {
382     fprintf(stderr, "%s: Unable to open file \"%s\"\n", binary_name.c_str(),
383             file1.c_str());
384     return kStatusError;
385   }
386   if (!baseline_image.CreateFromFilename(file2)) {
387     fprintf(stderr, "%s: Unable to open file \"%s\"\n", binary_name.c_str(),
388             file2.c_str());
389     return kStatusError;
390   }
391 
392   Image diff_image;
393   bool same = do_subtraction
394                   ? SubtractImages(baseline_image, actual_image, &diff_image)
395                   : CreateImageDiff(baseline_image, actual_image, &diff_image);
396   if (same)
397     return kStatusSame;
398 
399   std::vector<uint8_t> png_encoding = image_diff_png::EncodeRGBAPNG(
400       diff_image.span(), diff_image.w(), diff_image.h(), diff_image.w() * 4);
401   if (png_encoding.empty())
402     return kStatusError;
403 
404   FILE* f = fopen(out_file.c_str(), "wb");
405   if (!f)
406     return kStatusError;
407 
408   size_t size = png_encoding.size();
409   char* ptr = reinterpret_cast<char*>(&png_encoding.front());
410   if (fwrite(ptr, 1, size, f) != size)
411     return kStatusError;
412 
413   return kStatusDifferent;
414 }
415 
main(int argc,const char * argv[])416 int main(int argc, const char* argv[]) {
417   FX_InitializeMemoryAllocators();
418 
419   bool histograms = false;
420   bool produce_diff_image = false;
421   bool produce_image_subtraction = false;
422   bool reverse_byte_order = false;
423   uint8_t max_pixel_per_channel_delta = 0;
424   std::string filename1;
425   std::string filename2;
426   std::string diff_filename;
427 
428   // Strip the path from the first arg
429   const char* last_separator = strrchr(argv[0], PATH_SEPARATOR);
430   std::string binary_name = last_separator ? last_separator + 1 : argv[0];
431 
432   int i;
433   for (i = 1; i < argc; ++i) {
434     const char* arg = argv[i];
435     if (strstr(arg, "--") != arg)
436       break;
437     if (strcmp(arg, "--histogram") == 0) {
438       histograms = true;
439     } else if (strcmp(arg, "--diff") == 0) {
440       produce_diff_image = true;
441     } else if (strcmp(arg, "--subtract") == 0) {
442       produce_image_subtraction = true;
443     } else if (strcmp(arg, "--reverse-byte-order") == 0) {
444       reverse_byte_order = true;
445     } else if (strcmp(arg, "--fuzzy") == 0) {
446       max_pixel_per_channel_delta = 1;
447     }
448   }
449   if (i < argc)
450     filename1 = argv[i++];
451   if (i < argc)
452     filename2 = argv[i++];
453   if (i < argc)
454     diff_filename = argv[i++];
455 
456   if (produce_diff_image || produce_image_subtraction) {
457     if (!diff_filename.empty()) {
458       return DiffImages(binary_name, filename1, filename2, diff_filename,
459                         produce_image_subtraction, reverse_byte_order);
460     }
461   } else if (!filename2.empty()) {
462     return CompareImages(binary_name, filename1, filename2, histograms,
463                          reverse_byte_order, max_pixel_per_channel_delta);
464   }
465 
466   PrintHelp(binary_name);
467   return kStatusError;
468 }
469