• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2018 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "tools/skqp/src/skqp.h"
9 
10 #include "gm/gm.h"
11 #include "include/core/SkFontStyle.h"
12 #include "include/core/SkGraphics.h"
13 #include "include/core/SkStream.h"
14 #include "include/core/SkSurface.h"
15 #include "include/encode/SkPngEncoder.h"
16 #include "include/gpu/GrContext.h"
17 #include "include/gpu/GrContextOptions.h"
18 #include "include/private/SkImageInfoPriv.h"
19 #include "src/core/SkFontMgrPriv.h"
20 #include "src/core/SkOSFile.h"
21 #include "src/core/SkStreamPriv.h"
22 #include "src/utils/SkOSPath.h"
23 #include "tests/Test.h"
24 #include "tools/fonts/TestFontMgr.h"
25 #include "tools/gpu/gl/GLTestContext.h"
26 #include "tools/gpu/vk/VkTestContext.h"
27 
28 #include <limits.h>
29 #include <algorithm>
30 #include <cinttypes>
31 #include <sstream>
32 
33 #include "tools/skqp/src/skqp_model.h"
34 
35 #define IMAGES_DIRECTORY_PATH "images"
36 #define PATH_MAX_PNG "max.png"
37 #define PATH_MIN_PNG "min.png"
38 #define PATH_IMG_PNG "image.png"
39 #define PATH_ERR_PNG "errors.png"
40 #define PATH_MODEL "model"
41 
42 static constexpr char kRenderTestCSVReport[] = "out.csv";
43 static constexpr char kRenderTestReportPath[] = "report.html";
44 static constexpr char kRenderTestsPath[] = "skqp/rendertests.txt";
45 static constexpr char kUnitTestReportPath[] = "unit_tests.txt";
46 static constexpr char kUnitTestsPath[]   = "skqp/unittests.txt";
47 
48 // Kind of like Python's readlines(), but without any allocation.
49 // Calls f() on each line.
50 // F is [](const char*, size_t) -> void
51 template <typename F>
readlines(const void * data,size_t size,F f)52 static void readlines(const void* data, size_t size, F f) {
53     const char* start = (const char*)data;
54     const char* end = start + size;
55     const char* ptr = start;
56     while (ptr < end) {
57         while (*ptr++ != '\n' && ptr < end) {}
58         size_t len = ptr - start;
59         f(start, len);
60         start = ptr;
61     }
62 }
63 
get_unit_tests(SkQPAssetManager * mgr,std::vector<SkQP::UnitTest> * unitTests)64 static void get_unit_tests(SkQPAssetManager* mgr, std::vector<SkQP::UnitTest>* unitTests) {
65     std::unordered_set<std::string> testset;
66     auto insert = [&testset](const char* s, size_t l) {
67         SkASSERT(l > 1) ;
68         if (l > 0 && s[l - 1] == '\n') {  // strip line endings.
69             --l;
70         }
71         if (l > 0) {  // only add non-empty strings.
72             testset.insert(std::string(s, l));
73         }
74     };
75     if (sk_sp<SkData> dat = mgr->open(kUnitTestsPath)) {
76         readlines(dat->data(), dat->size(), insert);
77     }
78     for (const skiatest::Test& test : skiatest::TestRegistry::Range()) {
79         if ((testset.empty() || testset.count(std::string(test.name)) > 0) && test.needsGpu) {
80             unitTests->push_back(&test);
81         }
82     }
83     auto lt = [](SkQP::UnitTest u, SkQP::UnitTest v) { return strcmp(u->name, v->name) < 0; };
84     std::sort(unitTests->begin(), unitTests->end(), lt);
85 }
86 
get_render_tests(SkQPAssetManager * mgr,std::vector<SkQP::GMFactory> * gmlist,std::unordered_map<std::string,int64_t> * gmThresholds)87 static void get_render_tests(SkQPAssetManager* mgr,
88                              std::vector<SkQP::GMFactory>* gmlist,
89                              std::unordered_map<std::string, int64_t>* gmThresholds) {
90     auto insert = [gmThresholds](const char* s, size_t l) {
91         SkASSERT(l > 1) ;
92         if (l > 0 && s[l - 1] == '\n') {  // strip line endings.
93             --l;
94         }
95         if (l == 0) {
96             return;
97         }
98         const char* end = s + l;
99         const char* ptr = s;
100         constexpr char kDelimeter = ',';
101         while (ptr < end && *ptr != kDelimeter) { ++ptr; }
102         if (ptr + 1 >= end) {
103             SkASSERT(false);  // missing delimeter
104             return;
105         }
106         std::string key(s, ptr - s);
107         ++ptr;  // skip delimeter
108         std::string number(ptr, end - ptr);  // null-terminated copy.
109         int64_t value = 0;
110         if (1 != sscanf(number.c_str(), "%" SCNd64 , &value)) {
111             SkASSERT(false);  // Not a number
112             return;
113         }
114         gmThresholds->insert({std::move(key), value});  // (*gmThresholds)[s] = value;
115     };
116     if (sk_sp<SkData> dat = mgr->open(kRenderTestsPath)) {
117         readlines(dat->data(), dat->size(), insert);
118     }
119     using GmAndName = std::pair<SkQP::GMFactory, std::string>;
120     std::vector<GmAndName> gmsWithNames;
121     for (skiagm::GMFactory f : skiagm::GMRegistry::Range()) {
122         std::string name = SkQP::GetGMName(f);
123         if ((gmThresholds->empty() || gmThresholds->count(name) > 0)) {
124             gmsWithNames.push_back(std::make_pair(f, std::move(name)));
125         }
126     }
127     std::sort(gmsWithNames.begin(), gmsWithNames.end(),
128               [](GmAndName u, GmAndName v) { return u.second < v.second; });
129     gmlist->reserve(gmsWithNames.size());
130     for (const GmAndName& gmn : gmsWithNames) {
131         gmlist->push_back(gmn.first);
132     }
133 }
134 
make_test_context(SkQP::SkiaBackend backend)135 static std::unique_ptr<sk_gpu_test::TestContext> make_test_context(SkQP::SkiaBackend backend) {
136     using U = std::unique_ptr<sk_gpu_test::TestContext>;
137     switch (backend) {
138         case SkQP::SkiaBackend::kGL:
139             return U(sk_gpu_test::CreatePlatformGLTestContext(kGL_GrGLStandard, nullptr));
140         case SkQP::SkiaBackend::kGLES:
141             return U(sk_gpu_test::CreatePlatformGLTestContext(kGLES_GrGLStandard, nullptr));
142 #ifdef SK_VULKAN
143         case SkQP::SkiaBackend::kVulkan:
144             return U(sk_gpu_test::CreatePlatformVkTestContext(nullptr));
145 #endif
146         default:
147             return nullptr;
148     }
149 }
150 
context_options(skiagm::GM * gm=nullptr)151 static GrContextOptions context_options(skiagm::GM* gm = nullptr) {
152     GrContextOptions grContextOptions;
153     grContextOptions.fAllowPathMaskCaching = true;
154     grContextOptions.fDisableDriverCorrectnessWorkarounds = true;
155     if (gm) {
156         gm->modifyGrContextOptions(&grContextOptions);
157     }
158     return grContextOptions;
159 }
160 
get_backends()161 static std::vector<SkQP::SkiaBackend> get_backends() {
162     std::vector<SkQP::SkiaBackend> result;
163     SkQP::SkiaBackend backends[] = {
164         #ifndef SK_BUILD_FOR_ANDROID
165         SkQP::SkiaBackend::kGL,  // Used for testing on desktop machines.
166         #endif
167         SkQP::SkiaBackend::kGLES,
168         #ifdef SK_VULKAN
169         SkQP::SkiaBackend::kVulkan,
170         #endif
171     };
172     for (SkQP::SkiaBackend backend : backends) {
173         std::unique_ptr<sk_gpu_test::TestContext> testCtx = make_test_context(backend);
174         if (testCtx) {
175             testCtx->makeCurrent();
176             if (nullptr != testCtx->makeGrContext(context_options())) {
177                 result.push_back(backend);
178             }
179         }
180     }
181     SkASSERT_RELEASE(result.size() > 0);
182     return result;
183 }
184 
print_backend_info(const char * dstPath,const std::vector<SkQP::SkiaBackend> & backends)185 static void print_backend_info(const char* dstPath,
186                                const std::vector<SkQP::SkiaBackend>& backends) {
187 #ifdef SK_ENABLE_DUMP_GPU
188     SkFILEWStream out(dstPath);
189     out.writeText("[\n");
190     for (SkQP::SkiaBackend backend : backends) {
191         if (std::unique_ptr<sk_gpu_test::TestContext> testCtx = make_test_context(backend)) {
192             testCtx->makeCurrent();
193             if (sk_sp<GrContext> ctx = testCtx->makeGrContext(context_options())) {
194                 SkString info = ctx->dump();
195                 // remove null
196                 out.write(info.c_str(), info.size());
197                 out.writeText(",\n");
198             }
199         }
200     }
201     out.writeText("]\n");
202 #endif
203 }
204 
encode_png(const SkBitmap & src,const std::string & dst)205 static void encode_png(const SkBitmap& src, const std::string& dst) {
206     SkFILEWStream wStream(dst.c_str());
207     SkPngEncoder::Options options;
208     bool success = wStream.isValid() && SkPngEncoder::Encode(&wStream, src.pixmap(), options);
209     SkASSERT_RELEASE(success);
210 }
211 
write_to_file(const sk_sp<SkData> & src,const std::string & dst)212 static void write_to_file(const sk_sp<SkData>& src, const std::string& dst) {
213     SkFILEWStream wStream(dst.c_str());
214     bool success = wStream.isValid() && wStream.write(src->data(), src->size());
215     SkASSERT_RELEASE(success);
216 }
217 
218 ////////////////////////////////////////////////////////////////////////////////
219 
GetBackendName(SkQP::SkiaBackend b)220 const char* SkQP::GetBackendName(SkQP::SkiaBackend b) {
221     switch (b) {
222         case SkQP::SkiaBackend::kGL:     return "gl";
223         case SkQP::SkiaBackend::kGLES:   return "gles";
224         case SkQP::SkiaBackend::kVulkan: return "vk";
225     }
226     return "";
227 }
228 
GetGMName(SkQP::GMFactory f)229 std::string SkQP::GetGMName(SkQP::GMFactory f) {
230     std::unique_ptr<skiagm::GM> gm(f ? f() : nullptr);
231     return std::string(gm ? gm->getName() : "");
232 }
233 
GetUnitTestName(SkQP::UnitTest t)234 const char* SkQP::GetUnitTestName(SkQP::UnitTest t) { return t->name; }
235 
SkQP()236 SkQP::SkQP() {}
237 
~SkQP()238 SkQP::~SkQP() {}
239 
init(SkQPAssetManager * am,const char * reportDirectory)240 void SkQP::init(SkQPAssetManager* am, const char* reportDirectory) {
241     SkASSERT_RELEASE(!fAssetManager);
242     SkASSERT_RELEASE(am);
243     fAssetManager = am;
244     fReportDirectory = reportDirectory;
245 
246     SkGraphics::Init();
247     gSkFontMgr_DefaultFactory = &ToolUtils::MakePortableFontMgr;
248 
249     /* If the file "skqp/rendertests.txt" does not exist or is empty, run all
250        render tests.  Otherwise only run tests mentioned in that file.  */
251     get_render_tests(fAssetManager, &fGMs, &fGMThresholds);
252     /* If the file "skqp/unittests.txt" does not exist or is empty, run all gpu
253        unit tests.  Otherwise only run tests mentioned in that file.  */
254     get_unit_tests(fAssetManager, &fUnitTests);
255     fSupportedBackends = get_backends();
256 
257     print_backend_info((fReportDirectory + "/grdump.txt").c_str(), fSupportedBackends);
258 }
259 
evaluateGM(SkQP::SkiaBackend backend,SkQP::GMFactory gmFact)260 std::tuple<SkQP::RenderOutcome, std::string> SkQP::evaluateGM(SkQP::SkiaBackend backend,
261                                                               SkQP::GMFactory gmFact) {
262     SkASSERT_RELEASE(fAssetManager);
263     static constexpr SkQP::RenderOutcome kError = {INT_MAX, INT_MAX, INT64_MAX};
264     static constexpr SkQP::RenderOutcome kPass = {0, 0, 0};
265 
266     std::unique_ptr<sk_gpu_test::TestContext> testCtx = make_test_context(backend);
267     if (!testCtx) {
268         return std::make_tuple(kError, "Skia Failure: test context");
269     }
270     testCtx->makeCurrent();
271 
272     SkASSERT(gmFact);
273     std::unique_ptr<skiagm::GM> gm(gmFact());
274     SkASSERT(gm);
275     const char* const name = gm->getName();
276     const SkISize size = gm->getISize();
277     const int w = size.width();
278     const int h = size.height();
279     const SkImageInfo info =
280         SkImageInfo::Make(w, h, skqp::kColorType, kPremul_SkAlphaType, nullptr);
281     const SkSurfaceProps props(0, SkSurfaceProps::kLegacyFontHost_InitType);
282 
283     sk_sp<SkSurface> surf = SkSurface::MakeRenderTarget(
284             testCtx->makeGrContext(context_options(gm.get())).get(),
285             SkBudgeted::kNo, info, 0, &props);
286     if (!surf) {
287         return std::make_tuple(kError, "Skia Failure: gr-context");
288     }
289     gm->draw(surf->getCanvas());
290 
291     SkBitmap image;
292     image.allocPixels(SkImageInfo::Make(w, h, skqp::kColorType, skqp::kAlphaType));
293 
294     // SkColorTypeBytesPerPixel should be constexpr, but is not.
295     SkASSERT(SkColorTypeBytesPerPixel(skqp::kColorType) == sizeof(uint32_t));
296     // Call readPixels because we need to compare pixels.
297     if (!surf->readPixels(image.pixmap(), 0, 0)) {
298         return std::make_tuple(kError, "Skia Failure: read pixels");
299     }
300     int64_t passingThreshold = fGMThresholds.empty() ? -1 : fGMThresholds[std::string(name)];
301 
302     if (-1 == passingThreshold) {
303         return std::make_tuple(kPass, "");
304     }
305     skqp::ModelResult modelResult =
306         skqp::CheckAgainstModel(name, image.pixmap(), fAssetManager);
307 
308     if (!modelResult.fErrorString.empty()) {
309         return std::make_tuple(kError, std::move(modelResult.fErrorString));
310     }
311     fRenderResults.push_back(SkQP::RenderResult{backend, gmFact, modelResult.fOutcome});
312     if (modelResult.fOutcome.fMaxError <= passingThreshold) {
313         return std::make_tuple(kPass, "");
314     }
315     std::string imagesDirectory = fReportDirectory + "/" IMAGES_DIRECTORY_PATH;
316     if (!sk_mkdir(imagesDirectory.c_str())) {
317         SkDebugf("ERROR: sk_mkdir('%s');\n", imagesDirectory.c_str());
318         return std::make_tuple(modelResult.fOutcome, "");
319     }
320     std::ostringstream tmp;
321     tmp << imagesDirectory << '/' << SkQP::GetBackendName(backend) << '_' << name << '_';
322     std::string imagesPathPrefix1 = tmp.str();
323     tmp = std::ostringstream();
324     tmp << imagesDirectory << '/' << PATH_MODEL << '_' << name << '_';
325     std::string imagesPathPrefix2 = tmp.str();
326     encode_png(image,                  imagesPathPrefix1 + PATH_IMG_PNG);
327     encode_png(modelResult.fErrors,    imagesPathPrefix1 + PATH_ERR_PNG);
328     write_to_file(modelResult.fMaxPng, imagesPathPrefix2 + PATH_MAX_PNG);
329     write_to_file(modelResult.fMinPng, imagesPathPrefix2 + PATH_MIN_PNG);
330     return std::make_tuple(modelResult.fOutcome, "");
331 }
332 
executeTest(SkQP::UnitTest test)333 std::vector<std::string> SkQP::executeTest(SkQP::UnitTest test) {
334     SkASSERT_RELEASE(fAssetManager);
335     struct : public skiatest::Reporter {
336         std::vector<std::string> fErrors;
337         void reportFailed(const skiatest::Failure& failure) override {
338             SkString desc = failure.toString();
339             fErrors.push_back(std::string(desc.c_str(), desc.size()));
340         }
341     } r;
342     GrContextOptions options;
343     options.fDisableDriverCorrectnessWorkarounds = true;
344     if (test->fContextOptionsProc) {
345         test->fContextOptionsProc(&options);
346     }
347     test->proc(&r, options);
348     fUnitTestResults.push_back(UnitTestResult{test, r.fErrors});
349     return r.fErrors;
350 }
351 
352 ////////////////////////////////////////////////////////////////////////////////
353 
354 static constexpr char kDocHead[] =
355     "<!doctype html>\n"
356     "<html lang=\"en\">\n"
357     "<head>\n"
358     "<meta charset=\"UTF-8\">\n"
359     "<title>SkQP Report</title>\n"
360     "<style>\n"
361     "img { max-width:48%; border:1px green solid;\n"
362     "      image-rendering: pixelated;\n"
363     "      background-image:url('data:image/png;base64,iVBORw0KGgoA"
364     "AAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAAXNSR0IArs4c6QAAAAJiS0dEAP+H"
365     "j8y/AAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAB3RJTUUH3gUBEi4DGRAQYgAAAB1J"
366     "REFUGNNjfMoAAVJQmokBDdBHgPE/lPFsYN0BABdaAwN6tehMAAAAAElFTkSuQmCC"
367     "'); }\n"
368     "</style>\n"
369     "<script>\n"
370     "function ce(t) { return document.createElement(t); }\n"
371     "function ct(n) { return document.createTextNode(n); }\n"
372     "function ac(u,v) { return u.appendChild(v); }\n"
373     "function br(u) { ac(u, ce(\"br\")); }\n"
374     "function ma(s, c) { var a = ce(\"a\"); a.href = s; ac(a, c); return a; }\n"
375     "function f(backend, gm, e1, e2, e3) {\n"
376     "  var b = ce(\"div\");\n"
377     "  var x = ce(\"h2\");\n"
378     "  var t = backend + \"_\" + gm;\n"
379     "  ac(x, ct(t));\n"
380     "  ac(b, x);\n"
381     "  ac(b, ct(\"backend: \" + backend));\n"
382     "  br(b);\n"
383     "  ac(b, ct(\"gm name: \" + gm));\n"
384     "  br(b);\n"
385     "  ac(b, ct(\"maximum error: \" + e1));\n"
386     "  br(b);\n"
387     "  ac(b, ct(\"bad pixel counts: \" + e2));\n"
388     "  br(b);\n"
389     "  ac(b, ct(\"total error: \" + e3));\n"
390     "  br(b);\n"
391     "  var q = \"" IMAGES_DIRECTORY_PATH "/\" + backend + \"_\" + gm + \"_\";\n"
392     "  var p = \"" IMAGES_DIRECTORY_PATH "/"   PATH_MODEL  "_\" + gm + \"_\";\n"
393     "  var i = ce(\"img\");\n"
394     "  i.src = q + \"" PATH_IMG_PNG "\";\n"
395     "  i.alt = \"img\";\n"
396     "  ac(b, ma(i.src, i));\n"
397     "  i = ce(\"img\");\n"
398     "  i.src = q + \"" PATH_ERR_PNG "\";\n"
399     "  i.alt = \"err\";\n"
400     "  ac(b, ma(i.src, i));\n"
401     "  br(b);\n"
402     "  ac(b, ct(\"Expectation: \"));\n"
403     "  ac(b, ma(p + \"" PATH_MAX_PNG "\", ct(\"max\")));\n"
404     "  ac(b, ct(\" | \"));\n"
405     "  ac(b, ma(p + \"" PATH_MIN_PNG "\", ct(\"min\")));\n"
406     "  ac(b, ce(\"hr\"));\n"
407     "  b.id = backend + \":\" + gm;\n"
408     "  ac(document.body, b);\n"
409     "  l = ce(\"li\");\n"
410     "  ac(l, ct(\"[\" + e3 + \"] \"));\n"
411     "  ac(l, ma(\"#\" + backend +\":\"+ gm , ct(t)));\n"
412     "  ac(document.getElementById(\"toc\"), l);\n"
413     "}\n"
414     "function main() {\n";
415 
416 static constexpr char kDocMiddle[] =
417     "}\n"
418     "</script>\n"
419     "</head>\n"
420     "<body onload=\"main()\">\n"
421     "<h1>SkQP Report</h1>\n";
422 
423 static constexpr char kDocTail[] =
424     "<ul id=\"toc\"></ul>\n"
425     "<hr>\n"
426     "<p>Left image: test result<br>\n"
427     "Right image: errors (white = no error, black = smallest error, red = biggest error; "
428     "other errors are a color between black and red.)</p>\n"
429     "<hr>\n"
430     "</body>\n"
431     "</html>\n";
432 
433 template <typename T>
write(SkWStream * wStream,const T & text)434 inline void write(SkWStream* wStream, const T& text) {
435     wStream->write(text.c_str(), text.size());
436 }
437 
makeReport()438 void SkQP::makeReport() {
439     SkASSERT_RELEASE(fAssetManager);
440     int glesErrorCount = 0, vkErrorCount = 0, gles = 0, vk = 0;
441 
442     if (!sk_isdir(fReportDirectory.c_str())) {
443         SkDebugf("Report destination does not exist: '%s'\n", fReportDirectory.c_str());
444         return;
445     }
446     SkFILEWStream csvOut(SkOSPath::Join(fReportDirectory.c_str(), kRenderTestCSVReport).c_str());
447     SkFILEWStream htmOut(SkOSPath::Join(fReportDirectory.c_str(), kRenderTestReportPath).c_str());
448     SkASSERT_RELEASE(csvOut.isValid() && htmOut.isValid());
449     htmOut.writeText(kDocHead);
450     for (const SkQP::RenderResult& run : fRenderResults) {
451         switch (run.fBackend) {
452             case SkQP::SkiaBackend::kGLES: ++gles; break;
453             case SkQP::SkiaBackend::kVulkan: ++vk; break;
454             default: break;
455         }
456         const char* backendName = SkQP::GetBackendName(run.fBackend);
457         std::string gmName = SkQP::GetGMName(run.fGM);
458         const SkQP::RenderOutcome& outcome = run.fOutcome;
459         auto str = SkStringPrintf("\"%s\",\"%s\",%d,%d,%" PRId64, backendName, gmName.c_str(),
460                                   outcome.fMaxError, outcome.fBadPixelCount, outcome.fTotalError);
461         write(&csvOut, SkStringPrintf("%s\n", str.c_str()));
462 
463         int64_t passingThreshold = fGMThresholds.empty() ? 0 : fGMThresholds[gmName];
464         if (passingThreshold == -1 || outcome.fMaxError <= passingThreshold) {
465             continue;
466         }
467         write(&htmOut, SkStringPrintf("  f(%s);\n", str.c_str()));
468         switch (run.fBackend) {
469             case SkQP::SkiaBackend::kGLES: ++glesErrorCount; break;
470             case SkQP::SkiaBackend::kVulkan: ++vkErrorCount; break;
471             default: break;
472         }
473     }
474     htmOut.writeText(kDocMiddle);
475     write(&htmOut, SkStringPrintf("<p>gles errors: %d (of %d)</br>\n"
476                                   "vk errors: %d (of %d)</p>\n",
477                                   glesErrorCount, gles, vkErrorCount, vk));
478     htmOut.writeText(kDocTail);
479     SkFILEWStream unitOut(SkOSPath::Join(fReportDirectory.c_str(), kUnitTestReportPath).c_str());
480     SkASSERT_RELEASE(unitOut.isValid());
481     for (const SkQP::UnitTestResult& result : fUnitTestResults) {
482         unitOut.writeText(GetUnitTestName(result.fUnitTest));
483         if (result.fErrors.empty()) {
484             unitOut.writeText(" PASSED\n* * *\n");
485         } else {
486             write(&unitOut, SkStringPrintf(" FAILED (%u errors)\n", result.fErrors.size()));
487             for (const std::string& err : result.fErrors) {
488                 write(&unitOut, err);
489                 unitOut.newline();
490             }
491             unitOut.writeText("* * *\n");
492         }
493     }
494 }
495