ImageDiff.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /*
  2. * Copyright (C) 2009 Zan Dobersek <zandobersek@gmail.com>
  3. * Copyright (C) 2010 Igalia S.L.
  4. * Copyright (C) 2011 ProFUSION Embedded Systems
  5. * Copyright (C) 2011 Samsung Electronics
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. * 2. Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
  17. * its contributors may be used to endorse or promote products derived
  18. * from this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
  21. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  22. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  23. * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
  24. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  25. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  26. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  27. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  29. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. */
  31. #include "config.h"
  32. #include <Ecore.h>
  33. #include <Ecore_Evas.h>
  34. #include <Evas.h>
  35. #include <algorithm>
  36. #include <cmath>
  37. #include <cstdio>
  38. #include <cstdlib>
  39. #include <getopt.h>
  40. #include <sys/stat.h>
  41. #include <sys/types.h>
  42. #include <unistd.h>
  43. #include <wtf/OwnArrayPtr.h>
  44. #include <wtf/OwnPtr.h>
  45. #include <wtf/PassOwnPtr.h>
  46. #include <wtf/PassRefPtr.h>
  47. #include <wtf/efl/RefPtrEfl.h>
  48. enum PixelComponent {
  49. Red,
  50. Green,
  51. Blue,
  52. Alpha
  53. };
  54. static OwnPtr<Ecore_Evas> gEcoreEvas;
  55. static double gTolerance = 0;
  56. static void abortWithErrorMessage(const char* errorMessage);
  57. static unsigned char* pixelFromImageData(unsigned char* imageData, int rowStride, int x, int y)
  58. {
  59. return imageData + (y * rowStride) + (x << 2);
  60. }
  61. static Evas_Object* differenceImageFromDifferenceBuffer(Evas* evas, unsigned char* buffer, int width, int height)
  62. {
  63. Evas_Object* image = evas_object_image_filled_add(evas);
  64. if (!image)
  65. abortWithErrorMessage("could not create difference image");
  66. evas_object_image_size_set(image, width, height);
  67. evas_object_image_colorspace_set(image, EVAS_COLORSPACE_ARGB8888);
  68. unsigned char* diffPixels = static_cast<unsigned char*>(evas_object_image_data_get(image, EINA_TRUE));
  69. const int rowStride = evas_object_image_stride_get(image);
  70. for (int x = 0; x < width; x++) {
  71. for (int y = 0; y < height; y++) {
  72. unsigned char* diffPixel = pixelFromImageData(diffPixels, rowStride, x, y);
  73. diffPixel[Red] = diffPixel[Green] = diffPixel[Blue] = *buffer++;
  74. diffPixel[Alpha] = 0xff;
  75. }
  76. }
  77. evas_object_image_data_set(image, diffPixels);
  78. return image;
  79. }
  80. static float computeDistanceBetweenPixelComponents(unsigned char actualComponent, unsigned char baseComponent)
  81. {
  82. return (actualComponent - baseComponent) / std::max<float>(255 - baseComponent, baseComponent);
  83. }
  84. static float computeDistanceBetweenPixelComponents(unsigned char* actualPixel, unsigned char* basePixel, PixelComponent component)
  85. {
  86. return computeDistanceBetweenPixelComponents(actualPixel[component], basePixel[component]);
  87. }
  88. static float calculatePixelDifference(unsigned char* basePixel, unsigned char* actualPixel)
  89. {
  90. const float red = computeDistanceBetweenPixelComponents(actualPixel, basePixel, Red);
  91. const float green = computeDistanceBetweenPixelComponents(actualPixel, basePixel, Green);
  92. const float blue = computeDistanceBetweenPixelComponents(actualPixel, basePixel, Blue);
  93. const float alpha = computeDistanceBetweenPixelComponents(actualPixel, basePixel, Alpha);
  94. return sqrtf(red * red + green * green + blue * blue + alpha * alpha) / 2.0f;
  95. }
  96. static float calculateDifference(Evas_Object* baselineImage, Evas_Object* actualImage, RefPtr<Evas_Object>& differenceImage)
  97. {
  98. int width, height, baselineWidth, baselineHeight;
  99. evas_object_image_size_get(actualImage, &width, &height);
  100. evas_object_image_size_get(baselineImage, &baselineWidth, &baselineHeight);
  101. if (width != baselineWidth || height != baselineHeight) {
  102. printf("Error, test and reference image have different sizes.\n");
  103. return 100; // Completely different.
  104. }
  105. OwnArrayPtr<unsigned char> diffBuffer = adoptArrayPtr(new unsigned char[width * height]);
  106. if (!diffBuffer)
  107. abortWithErrorMessage("could not create difference buffer");
  108. const int actualRowStride = evas_object_image_stride_get(actualImage);
  109. const int baseRowStride = evas_object_image_stride_get(baselineImage);
  110. unsigned numberOfDifferentPixels = 0;
  111. float totalDistance = 0;
  112. float maxDistance = 0;
  113. unsigned char* actualPixels = static_cast<unsigned char*>(evas_object_image_data_get(actualImage, EINA_FALSE));
  114. unsigned char* basePixels = static_cast<unsigned char*>(evas_object_image_data_get(baselineImage, EINA_FALSE));
  115. unsigned char* currentDiffPixel = diffBuffer.get();
  116. for (int x = 0; x < width; x++) {
  117. for (int y = 0; y < height; y++) {
  118. unsigned char* actualPixel = pixelFromImageData(actualPixels, actualRowStride, x, y);
  119. unsigned char* basePixel = pixelFromImageData(basePixels, baseRowStride, x, y);
  120. const float distance = calculatePixelDifference(basePixel, actualPixel);
  121. *currentDiffPixel++ = static_cast<unsigned char>(distance * 255.0f);
  122. if (distance >= 1.0f / 255.0f) {
  123. ++numberOfDifferentPixels;
  124. totalDistance += distance;
  125. maxDistance = std::max<float>(maxDistance, distance);
  126. }
  127. }
  128. }
  129. // When using evas_object_image_data_get(), a complementary evas_object_data_set() must be
  130. // issued to balance the reference count, even if the image hasn't been changed.
  131. evas_object_image_data_set(baselineImage, basePixels);
  132. evas_object_image_data_set(actualImage, actualPixels);
  133. // Compute the difference as a percentage combining both the number of
  134. // different pixels and their difference amount i.e. the average distance
  135. // over the entire image
  136. float difference = 0;
  137. if (numberOfDifferentPixels)
  138. difference = 100.0f * totalDistance / (height * width);
  139. if (difference <= gTolerance)
  140. difference = 0;
  141. else {
  142. difference = roundf(difference * 100.0f) / 100.0f;
  143. difference = std::max(difference, 0.01f); // round to 2 decimal places
  144. differenceImage = adoptRef(differenceImageFromDifferenceBuffer(evas_object_evas_get(baselineImage), diffBuffer.get(), width, height));
  145. }
  146. return difference;
  147. }
  148. static int getTemporaryFile(char *fileName, size_t fileNameLength)
  149. {
  150. char* tempDirectory = getenv("TMPDIR");
  151. if (!tempDirectory)
  152. tempDirectory = getenv("TEMP");
  153. if (tempDirectory)
  154. snprintf(fileName, fileNameLength, "%s/ImageDiffXXXXXX.png", tempDirectory);
  155. else {
  156. #if __linux__
  157. strcpy(fileName, "/dev/shm/ImageDiffXXXXXX.png");
  158. const int fileDescriptor = mkstemps(fileName, sizeof(".png") - 1);
  159. if (fileDescriptor >= 0)
  160. return fileDescriptor;
  161. #endif // __linux__
  162. strcpy(fileName, "ImageDiffXXXXXX.png");
  163. }
  164. return mkstemps(fileName, sizeof(".png") - 1);
  165. }
  166. static void printImage(Evas_Object* image)
  167. {
  168. char fileName[PATH_MAX];
  169. const int tempImageFd = getTemporaryFile(fileName, PATH_MAX);
  170. if (tempImageFd == -1)
  171. abortWithErrorMessage("could not create temporary file");
  172. evas_render(evas_object_evas_get(image));
  173. if (evas_object_image_save(image, fileName, 0, 0)) {
  174. struct stat fileInfo;
  175. if (!stat(fileName, &fileInfo)) {
  176. printf("Content-Length: %ld\n", fileInfo.st_size);
  177. fflush(stdout);
  178. unsigned char buffer[2048];
  179. ssize_t bytesRead;
  180. while ((bytesRead = read(tempImageFd, buffer, sizeof(buffer))) > 0) {
  181. ssize_t bytesWritten = 0;
  182. ssize_t count;
  183. do {
  184. if ((count = write(1, buffer + bytesWritten, bytesRead - bytesWritten)) <= 0)
  185. break;
  186. bytesWritten += count;
  187. } while (bytesWritten < bytesRead);
  188. }
  189. }
  190. }
  191. close(tempImageFd);
  192. unlink(fileName);
  193. }
  194. static void printImageDifferences(Evas_Object* baselineImage, Evas_Object* actualImage)
  195. {
  196. RefPtr<Evas_Object> differenceImage;
  197. const float difference = calculateDifference(baselineImage, actualImage, differenceImage);
  198. if (difference > 0.0f) {
  199. if (differenceImage)
  200. printImage(differenceImage.get());
  201. printf("diff: %01.2f%% failed\n", difference);
  202. } else
  203. printf("diff: %01.2f%% passed\n", difference);
  204. }
  205. static void resizeEcoreEvasIfNeeded(Evas_Object* image)
  206. {
  207. int newWidth, newHeight;
  208. evas_object_image_size_get(image, &newWidth, &newHeight);
  209. int currentWidth, currentHeight;
  210. ecore_evas_screen_geometry_get(gEcoreEvas.get(), 0, 0, &currentWidth, &currentHeight);
  211. if (newWidth > currentWidth)
  212. currentWidth = newWidth;
  213. if (newHeight > currentHeight)
  214. currentHeight = newHeight;
  215. ecore_evas_resize(gEcoreEvas.get(), currentWidth, currentHeight);
  216. }
  217. static PassRefPtr<Evas_Object> readImageFromStdin(Evas* evas, long imageSize)
  218. {
  219. OwnArrayPtr<unsigned char> imageBuffer = adoptArrayPtr(new unsigned char[imageSize]);
  220. if (!imageBuffer)
  221. abortWithErrorMessage("cannot allocate image");
  222. const size_t bytesRead = fread(imageBuffer.get(), 1, imageSize, stdin);
  223. if (!bytesRead)
  224. return PassRefPtr<Evas_Object>();
  225. Evas_Object* image = evas_object_image_filled_add(evas);
  226. evas_object_image_colorspace_set(image, EVAS_COLORSPACE_ARGB8888);
  227. evas_object_image_memfile_set(image, imageBuffer.get(), bytesRead, 0, 0);
  228. resizeEcoreEvasIfNeeded(image);
  229. return adoptRef(image);
  230. }
  231. static bool parseCommandLineOptions(int argc, char** argv)
  232. {
  233. static const option options[] = {
  234. { "tolerance", required_argument, 0, 't' },
  235. { 0, 0, 0, 0 }
  236. };
  237. int option;
  238. while ((option = getopt_long(argc, (char* const*)argv, "t:", options, 0)) != -1) {
  239. switch (option) {
  240. case 't':
  241. gTolerance = atof(optarg);
  242. break;
  243. case '?':
  244. case ':':
  245. return false;
  246. }
  247. }
  248. return true;
  249. }
  250. static void shutdownEfl()
  251. {
  252. ecore_evas_shutdown();
  253. ecore_shutdown();
  254. evas_shutdown();
  255. }
  256. static void abortWithErrorMessage(const char* errorMessage)
  257. {
  258. shutdownEfl();
  259. printf("Error, %s.\n", errorMessage);
  260. exit(EXIT_FAILURE);
  261. }
  262. static Evas* initEfl()
  263. {
  264. evas_init();
  265. ecore_init();
  266. ecore_evas_init();
  267. gEcoreEvas = adoptPtr(ecore_evas_buffer_new(1, 1));
  268. Evas* evas = ecore_evas_get(gEcoreEvas.get());
  269. if (!evas)
  270. abortWithErrorMessage("could not create Ecore_Evas buffer");
  271. return evas;
  272. }
  273. int main(int argc, char* argv[])
  274. {
  275. if (!parseCommandLineOptions(argc, argv))
  276. return EXIT_FAILURE;
  277. Evas* evas = initEfl();
  278. RefPtr<Evas_Object> actualImage;
  279. RefPtr<Evas_Object> baselineImage;
  280. char buffer[2048];
  281. while (fgets(buffer, sizeof(buffer), stdin)) {
  282. char* contentLengthStart = strstr(buffer, "Content-Length: ");
  283. if (!contentLengthStart)
  284. continue;
  285. long imageSize;
  286. if (sscanf(contentLengthStart, "Content-Length: %ld", &imageSize) == 1) {
  287. if (imageSize <= 0)
  288. abortWithErrorMessage("image size must be specified");
  289. if (!actualImage)
  290. actualImage = readImageFromStdin(evas, imageSize);
  291. else if (!baselineImage) {
  292. baselineImage = readImageFromStdin(evas, imageSize);
  293. printImageDifferences(baselineImage.get(), actualImage.get());
  294. actualImage.clear();
  295. baselineImage.clear();
  296. }
  297. }
  298. fflush(stdout);
  299. }
  300. gEcoreEvas.clear(); // Make sure ecore_evas_free is called before the EFL are shut down
  301. shutdownEfl();
  302. return EXIT_SUCCESS;
  303. }