1/*
2 * Copyright (C) 2005, 2007 Apple Inc. All rights reserved.
3 * Copyright (C) 2005 Ben La Monica <ben.lamonica@gmail.com>.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#define min min
28
29// FIXME: We need to be able to include these defines from a config.h somewhere.
30#define JS_EXPORT_PRIVATE
31#define WTF_EXPORT_PRIVATE
32
33#include <stdio.h>
34#include <wtf/Platform.h>
35#include <wtf/RetainPtr.h>
36
37#if PLATFORM(WIN)
38#include <winsock2.h>
39#include <windows.h>
40#include <fcntl.h>
41#include <io.h>
42#include <wtf/MathExtras.h>
43#endif
44
45#include <CoreGraphics/CGBitmapContext.h>
46#include <CoreGraphics/CGImage.h>
47#include <ImageIO/CGImageDestination.h>
48
49#if PLATFORM(MAC)
50#include <LaunchServices/UTCoreTypes.h>
51#endif
52
53#ifndef CGFLOAT_DEFINED
54#ifdef __LP64__
55typedef double CGFloat;
56#else
57typedef float CGFloat;
58#endif
59#define CGFLOAT_DEFINED 1
60#endif
61
62using namespace std;
63
64#if PLATFORM(WIN)
65static inline float strtof(const char *nptr, char **endptr)
66{
67    return strtod(nptr, endptr);
68}
69static const CFStringRef kUTTypePNG = CFSTR("public.png");
70#endif
71
72static RetainPtr<CGImageRef> createImageFromStdin(int bytesRemaining)
73{
74    unsigned char buffer[2048];
75    RetainPtr<CFMutableDataRef> data(AdoptCF, CFDataCreateMutable(0, bytesRemaining));
76
77    while (bytesRemaining > 0) {
78        size_t bytesToRead = min(bytesRemaining, 2048);
79        size_t bytesRead = fread(buffer, 1, bytesToRead, stdin);
80        CFDataAppendBytes(data.get(), buffer, static_cast<CFIndex>(bytesRead));
81        bytesRemaining -= static_cast<int>(bytesRead);
82    }
83    RetainPtr<CGDataProviderRef> dataProvider(AdoptCF, CGDataProviderCreateWithCFData(data.get()));
84    return RetainPtr<CGImageRef>(AdoptCF, CGImageCreateWithPNGDataProvider(dataProvider.get(), 0, false, kCGRenderingIntentDefault));
85}
86
87static void releaseMallocBuffer(void* info, const void* data, size_t size)
88{
89    free((void*)data);
90}
91
92static RetainPtr<CGImageRef> createDifferenceImage(CGImageRef baseImage, CGImageRef testImage, float& difference)
93{
94    size_t width = CGImageGetWidth(baseImage);
95    size_t height = CGImageGetHeight(baseImage);
96    size_t rowBytes = width * 4;
97
98    // Draw base image in bitmap context
99    void* baseBuffer = calloc(height, rowBytes);
100    RetainPtr<CGContextRef> baseContext(AdoptCF, CGBitmapContextCreate(baseBuffer, width, height, 8, rowBytes, CGImageGetColorSpace(baseImage), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host));
101    CGContextDrawImage(baseContext.get(), CGRectMake(0, 0, width, height), baseImage);
102
103    // Draw test image in bitmap context
104    void* buffer = calloc(height, rowBytes);
105    RetainPtr<CGContextRef> context(AdoptCF, CGBitmapContextCreate(buffer, width, height, 8, rowBytes, CGImageGetColorSpace(testImage), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host));
106    CGContextDrawImage(context.get(), CGRectMake(0, 0, width, height), testImage);
107
108    // Compare the content of the 2 bitmaps
109    void* diffBuffer = malloc(width * height);
110    float count = 0.0f;
111    float sum = 0.0f;
112    float maxDistance = 0.0f;
113    unsigned char* basePixel = (unsigned char*)baseBuffer;
114    unsigned char* pixel = (unsigned char*)buffer;
115    unsigned char* diff = (unsigned char*)diffBuffer;
116    for (size_t y = 0; y < height; ++y) {
117        for (size_t x = 0; x < width; ++x) {
118            float red = (pixel[0] - basePixel[0]) / max<float>(255 - basePixel[0], basePixel[0]);
119            float green = (pixel[1] - basePixel[1]) / max<float>(255 - basePixel[1], basePixel[1]);
120            float blue = (pixel[2] - basePixel[2]) / max<float>(255 - basePixel[2], basePixel[2]);
121            float alpha = (pixel[3] - basePixel[3]) / max<float>(255 - basePixel[3], basePixel[3]);
122            float distance = sqrtf(red * red + green * green + blue * blue + alpha * alpha) / 2.0f;
123
124            *diff++ = (unsigned char)(distance * 255.0f);
125
126            if (distance >= 1.0f / 255.0f) {
127                count += 1.0f;
128                sum += distance;
129                if (distance > maxDistance)
130                    maxDistance = distance;
131            }
132
133            basePixel += 4;
134            pixel += 4;
135        }
136    }
137
138    // Compute the difference as a percentage combining both the number of different pixels and their difference amount i.e. the average distance over the entire image
139    if (count > 0.0f)
140        difference = 100.0f * sum / (height * width);
141    else
142        difference = 0.0f;
143
144    RetainPtr<CGImageRef> diffImage;
145    // Generate a normalized diff image if there is any difference
146    if (difference > 0.0f) {
147        if (maxDistance < 1.0f) {
148            diff = (unsigned char*)diffBuffer;
149            for(size_t p = 0; p < height * width; ++p)
150                diff[p] = diff[p] / maxDistance;
151        }
152
153        static CGColorSpaceRef diffColorspace = CGColorSpaceCreateDeviceGray();
154        RetainPtr<CGDataProviderRef> provider(AdoptCF, CGDataProviderCreateWithData(0, diffBuffer, width * height, releaseMallocBuffer));
155        diffImage.adoptCF(CGImageCreate(width, height, 8, 8, width, diffColorspace, 0, provider.get(), 0, false, kCGRenderingIntentDefault));
156    }
157    else
158        free(diffBuffer);
159
160    // Destroy drawing buffers
161    if (buffer)
162        free(buffer);
163    if (baseBuffer)
164        free(baseBuffer);
165
166    return diffImage;
167}
168
169static inline bool imageHasAlpha(CGImageRef image)
170{
171    CGImageAlphaInfo info = CGImageGetAlphaInfo(image);
172
173    return (info >= kCGImageAlphaPremultipliedLast) && (info <= kCGImageAlphaFirst);
174}
175
176int main(int argc, const char* argv[])
177{
178#if PLATFORM(WIN)
179    _setmode(0, _O_BINARY);
180    _setmode(1, _O_BINARY);
181#endif
182
183    float tolerance = 0.0f;
184
185    for (int i = 1; i < argc; ++i) {
186        if (!strcmp(argv[i], "-t") || !strcmp(argv[i], "--tolerance")) {
187            if (i >= argc - 1)
188                exit(1);
189            tolerance = strtof(argv[i + 1], 0);
190            ++i;
191            continue;
192        }
193    }
194
195    char buffer[2048];
196    RetainPtr<CGImageRef> actualImage;
197    RetainPtr<CGImageRef> baselineImage;
198
199    while (fgets(buffer, sizeof(buffer), stdin)) {
200        // remove the CR
201        char* newLineCharacter = strchr(buffer, '\n');
202        if (newLineCharacter)
203            *newLineCharacter = '\0';
204
205        if (!strncmp("Content-Length: ", buffer, 16)) {
206            strtok(buffer, " ");
207            int imageSize = strtol(strtok(0, " "), 0, 10);
208
209            if (imageSize > 0 && !actualImage)
210                actualImage = createImageFromStdin(imageSize);
211            else if (imageSize > 0 && !baselineImage)
212                baselineImage = createImageFromStdin(imageSize);
213            else
214                fputs("error, image size must be specified.\n", stdout);
215        }
216
217        if (actualImage && baselineImage) {
218            RetainPtr<CGImageRef> diffImage;
219            float difference = 100.0f;
220
221            if ((CGImageGetWidth(actualImage.get()) == CGImageGetWidth(baselineImage.get())) && (CGImageGetHeight(actualImage.get()) == CGImageGetHeight(baselineImage.get())) && (imageHasAlpha(actualImage.get()) == imageHasAlpha(baselineImage.get()))) {
222                diffImage = createDifferenceImage(actualImage.get(), baselineImage.get(), difference); // difference is passed by reference
223                if (difference <= tolerance)
224                    difference = 0.0f;
225                else {
226                    difference = roundf(difference * 100.0f) / 100.0f;
227                    difference = max(difference, 0.01f); // round to 2 decimal places
228                }
229            } else
230                fputs("error, test and reference image have different properties.\n", stderr);
231
232            if (difference > 0.0f) {
233                if (diffImage) {
234                    RetainPtr<CFMutableDataRef> imageData(AdoptCF, CFDataCreateMutable(0, 0));
235                    RetainPtr<CGImageDestinationRef> imageDest(AdoptCF, CGImageDestinationCreateWithData(imageData.get(), kUTTypePNG, 1, 0));
236                    CGImageDestinationAddImage(imageDest.get(), diffImage.get(), 0);
237                    CGImageDestinationFinalize(imageDest.get());
238                    printf("Content-Length: %lu\n", CFDataGetLength(imageData.get()));
239                    fwrite(CFDataGetBytePtr(imageData.get()), 1, CFDataGetLength(imageData.get()), stdout);
240                }
241
242                fprintf(stdout, "diff: %01.2f%% failed\n", difference);
243            } else
244                fprintf(stdout, "diff: %01.2f%% passed\n", difference);
245
246            actualImage = 0;
247            baselineImage = 0;
248        }
249
250        fflush(stdout);
251    }
252
253    return 0;
254}
255