Debian Codegraph @

dm/DM.cpp

raw
1 /*
2 * Copyright 2013 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 "dm/DMJsonWriter.h"
9 #include "dm/DMSrcSink.h"
10 #include "include/codec/SkCodec.h"
11 #include "include/codec/SkEncodedImageFormat.h"
12 #include "include/core/SkBBHFactory.h"
13 #include "include/core/SkColorSpace.h"
14 #include "include/core/SkData.h"
15 #include "include/core/SkDocument.h"
16 #include "include/core/SkGraphics.h"
17 #include "src/base/SkHalf.h"
18 #include "src/base/SkLeanWindows.h"
19 #include "src/base/SkNoDestructor.h"
20 #include "src/base/SkSpinlock.h"
21 #include "src/base/SkTime.h"
22 #include "src/base/SkVx.h"
23 #include "src/core/SkChecksum.h"
24 #include "src/core/SkColorPriv.h"
25 #include "src/core/SkColorSpacePriv.h"
26 #include "src/core/SkMD5.h"
27 #include "src/core/SkOSFile.h"
28 #include "src/core/SkStringUtils.h"
29 #include "src/core/SkTHash.h"
30 #include "src/core/SkTaskGroup.h"
31 #include "src/utils/SkOSPath.h"
32 #include "tools/AutoreleasePool.h"
33 #include "tools/CodecUtils.h"
34 #include "tools/HashAndEncode.h"
35 #include "tools/ProcStats.h"
36 #include "tools/Resources.h"
37 #include "tools/TestFontDataProvider.h"
38 #include "tools/ToolUtils.h"
39 #include "tools/flags/CommonFlags.h"
40 #include "tools/flags/CommonFlagsConfig.h"
41 #include "tools/flags/CommonFlagsGanesh.h"
42 #include "tools/fonts/FontToolUtils.h"
43 #include "tools/trace/ChromeTracingTracer.h"
44 #include "tools/trace/EventTracingPriv.h"
45 #include "tools/trace/SkDebugfTracer.h"
46
47 #include <memory>
48 #include <vector>
49
50 #include <stdlib.h>
51
52 #if defined(SK_GRAPHITE)
53 #include "tools/flags/CommonFlagsGraphite.h"
54 #endif
55
56 #if !defined(SK_DISABLE_LEGACY_TESTS)
57 #include "tests/Test.h"
58 #include "tests/TestHarness.h"
59 #endif
60
61 #if defined(SK_BUILD_FOR_IOS)
62 #include "tools/ios_utils.h"
63 #endif
64
65 #ifndef SK_BUILD_FOR_WIN
66 #include <unistd.h>
67 #endif
68
69 #if defined(SK_BUILD_FOR_MAC)
70 #include "include/utils/mac/SkCGUtils.h"
71 #include "src/utils/mac/SkUniqueCFRef.h"
72 #endif
73
74 #if defined(SK_ENABLE_SVG)
75 #include "modules/svg/include/SkSVGOpenTypeSVGDecoder.h"
76 #endif
77
78 using namespace skia_private;
79
80 extern bool gSkForceRasterPipelineBlitter;
81 extern bool gForceHighPrecisionRasterPipeline;
82 #if defined(SK_GANESH)
83 extern bool gCreateProtectedContext;
84 #endif
85 static DEFINE_string(src, "tests gm skp mskp lottie rive svg image colorImage",
86 "Source types to test.");
87 static DEFINE_bool(nameByHash, false,
88 "If true, write to FLAGS_writePath[0]/<hash>.png instead of "
89 "to FLAGS_writePath[0]/<config>/<sourceType>/<sourceOptions>/<name>.png");
90 static DEFINE_bool2(pathOpsExtended, x, false, "Run extended pathOps tests.");
91 static DEFINE_string(matrix, "1 0 0 1",
92 "2x2 scale+skew matrix to apply or upright when using "
93 "'matrix' or 'upright' in config.");
94
95 static DEFINE_string(skip, "",
96 "Space-separated config/src/srcOptions/name quadruples to skip. "
97 "'_' matches anything. '~' negates the match. E.g. \n"
98 "'--skip gpu skp _ _' will skip all SKPs drawn into the gpu config.\n"
99 "'--skip gpu skp _ _ 8888 gm _ aarects' will also skip the aarects GM on 8888.\n"
100 "'--skip ~8888 svg _ svgparse_' blocks non-8888 SVGs that contain \"svgparse_\" in "
101 "the name.");
102
103 static DEFINE_string2(readPath, r, "",
104 "If set check for equality with golden results in this directory.");
105 DEFINE_string2(writePath, w, "", "If set, write bitmaps here as .pngs.");
106
107
108 static DEFINE_string(uninterestingHashesFile, "",
109 "File containing a list of uninteresting hashes. If a result hashes to something in "
110 "this list, no image is written for that result.");
111
112 static DEFINE_int(shards, 1, "We're splitting source data into this many shards.");
113 static DEFINE_int(shard, 0, "Which shard do I run?");
114
115 static DEFINE_string(mskps, "", "Directory to read mskps from, or a single mskp file.");
116 static DEFINE_bool(forceRasterPipeline, false, "sets gSkForceRasterPipelineBlitter");
117 static DEFINE_bool(forceRasterPipelineHP, false, "sets gSkForceRasterPipelineBlitter and gForceHighPrecisionRasterPipeline");
118 static DEFINE_bool(createProtected, false, "attempts to create a protected backend context");
119
120 static DEFINE_string(bisect, "",
121 "Pair of: SKP file to bisect, followed by an l/r bisect trail string (e.g., 'lrll'). The "
122 "l/r trail specifies which half to keep at each step of a binary search through the SKP's "
123 "paths. An empty string performs no bisect. Only the SkPaths are bisected; all other draws "
124 "are thrown out. This is useful for finding a reduced repo case for path drawing bugs.");
125
126 static DEFINE_bool(ignoreSigInt, false, "ignore SIGINT signals during test execution");
127
128 static DEFINE_bool(checkF16, false, "Ensure that F16Norm pixels are clamped.");
129
130 static DEFINE_string(colorImages, "",
131 "List of images and/or directories to decode with color correction. "
132 "A directory with no images is treated as a fatal error.");
133
134 static DEFINE_bool2(veryVerbose, V, false, "tell individual tests to be verbose.");
135
136 static DEFINE_bool(cpu, true, "Run CPU-bound work?");
137 static DEFINE_bool(gpu, true, "Run GPU-bound work?");
138 static DEFINE_bool(graphite, true, "Run Graphite work?");
139
140 static DEFINE_bool(dryRun, false,
141 "just print the tests that would be run, without actually running them.");
142
143 static DEFINE_string(images, "",
144 "List of images and/or directories to decode. A directory with no images"
145 " is treated as a fatal error.");
146
147 static DEFINE_bool(simpleCodec, false,
148 "Runs of a subset of the codec tests, "
149 "with no scaling or subsetting, always using the canvas color type.");
150
151 static DEFINE_string2(match, m, nullptr,
152 "[~][^]substring[$] [...] of name to run.\n"
153 "Multiple matches may be separated by spaces.\n"
154 "~ causes a matching name to always be skipped\n"
155 "^ requires the start of the name to match\n"
156 "$ requires the end of the name to match\n"
157 "^ and $ requires an exact match\n"
158 "If a name does not match any list entry,\n"
159 "it is skipped unless some list entry starts with ~");
160
161 static DEFINE_bool2(quiet, q, false, "if true, don't print status updates.");
162 static DEFINE_bool2(verbose, v, false, "enable verbose output from the test driver.");
163
164 static DEFINE_string(skps, "skps", "Directory to read skps from.");
165 static DEFINE_string(lotties, "lotties", "Directory to read (Bodymovin) jsons from.");
166 static DEFINE_string(svgs, "", "Directory to read SVGs from, or a single SVG file.");
167
168 static DEFINE_int_2(threads, j, -1,
169 "Run threadsafe tests on a threadpool with this many extra threads, "
170 "defaulting to one extra thread per core.");
171
172 static DEFINE_string(key, "",
173 "Space-separated key/value pairs to add to JSON identifying this builder.");
174 static DEFINE_string(properties, "",
175 "Space-separated key/value pairs to add to JSON identifying this run.");
176
177 static DEFINE_bool(rasterize_pdf, false, "Rasterize PDFs when possible.");
178
179 using namespace DM;
180
181 #if !defined(SK_DISABLE_LEGACY_TESTS)
182 using skiatest::TestType;
183 #endif
184 #if defined(SK_GANESH)
185 using sk_gpu_test::GrContextFactory;
186 using sk_gpu_test::ContextInfo;
187 #ifdef SK_GL
188 using sk_gpu_test::GLTestContext;
189 #endif
190 #endif
191
192 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
193
194 static FILE* gVLog;
195
196 static void vlog(const char* fmt, ...) SK_PRINTF_LIKE(1, 2);
197
198 static void vlog(const char* fmt, ...) {
199 if (gVLog) {
200 va_list args;
201 va_start(args, fmt);
202 vfprintf(gVLog, fmt, args);
203 fflush(gVLog);
204 va_end(args);
205 }
206 }
207
208 static void info(const char* fmt, ...) SK_PRINTF_LIKE(1, 2);
209
210 static void info(const char* fmt, ...) {
211 va_list args;
212 va_start(args, fmt);
213
214 if (gVLog) {
215 va_list vlogArgs;
216 va_copy(vlogArgs, args);
217 vfprintf(gVLog, fmt, vlogArgs);
218 fflush(gVLog);
219 va_end(vlogArgs);
220 }
221
222 if (!FLAGS_quiet) {
223 vprintf(fmt, args);
224 }
225
226 va_end(args);
227 }
228
229 static TArray<SkString>* gFailures = new TArray<SkString>;
230
231 static void fail(const SkString& err) {
232 static SkSpinlock mutex;
233 SkAutoSpinlock lock(mutex);
234 SkDebugf("\n\nFAILURE: %s\n\n", err.c_str());
235 gFailures->push_back(err);
236 }
237
238 struct Running {
239 SkString id;
240 SkThreadID thread;
241
242 void dump() const {
243 info("\t%s\n", id.c_str());
244 }
245 };
246
247 static void dump_json() {
248 if (!FLAGS_writePath.isEmpty()) {
249 JsonWriter::DumpJson(FLAGS_writePath[0], FLAGS_key, FLAGS_properties);
250 }
251 }
252
253 // We use a spinlock to make locking this in a signal handler _somewhat_ safe.
254 static SkSpinlock gMutex;
255 static int gPending;
256 static int gTotalCounts;
257 static double gLastUpdate;
258 static SkNoDestructor<TArray<Running>> gRunning;
259
260 static void done(const char* config, const char* src, const char* srcOptions, const char* name) {
261 SkString id = SkStringPrintf("%s %s %s %s", config, src, srcOptions, name);
262 bool updateDueToProgress;
263 double lastUpdate;
264 int totalCounts;
265 int pending;
266 {
267 SkAutoSpinlock lock(gMutex);
268 for (int i = 0; i < gRunning->size(); i++) {
269 if (gRunning->at(i).id == id) {
270 gRunning->removeShuffle(i);
271 break;
272 }
273 }
274 --gPending;
275 updateDueToProgress = gPending % 500 == 0;
276 lastUpdate = gLastUpdate;
277 totalCounts = gTotalCounts;
278 pending = gPending;
279 }
280 vlog("[%d/%d] %s done\n", totalCounts - pending, totalCounts, id.c_str());
281
282 // We write out dm.json file and print out a progress update every once in a while.
283 // Notice this also handles the final dm.json and progress update when pending == 0.
284 double now = SkTime::GetNSecs();
285 bool updateDueToTime = now - lastUpdate > 4e9;
286 if (updateDueToProgress || updateDueToTime) {
287 dump_json();
288
289 int curr = sk_tools::getCurrResidentSetSizeMB(),
290 peak = sk_tools::getMaxResidentSetSizeMB();
291
292 SkAutoSpinlock lock(gMutex);
293
294 // Since multiple threads can call `done`, it's possible that another thread has raced with
295 // this one and printed an update since we did our progress check above. We detect this case
296 // by checking to see if `gLastUpdate` has changed; if so, we don't need to print anything.
297 if (lastUpdate == gLastUpdate) {
298 info("\n[%d/%d] %dMB RAM, %dMB peak, %d queued, %d threads:\n\t%s done\n",
299 gTotalCounts - gPending, gTotalCounts,
300 curr, peak, gPending - gRunning->size(), gRunning->size() + 1, id.c_str());
301 for (auto& task : *gRunning) {
302 task.dump();
303 }
304 gLastUpdate = now;
305 }
306 }
307 }
308
309 static void start(const char* config, const char* src, const char* srcOptions, const char* name) {
310 SkString id = SkStringPrintf("%s %s %s %s", config, src, srcOptions, name);
311 vlog("\tstart %s\n", id.c_str());
312 SkAutoSpinlock lock(gMutex);
313 gRunning->push_back({id,SkGetThreadID()});
314 }
315
316 static void find_culprit() {
317 // Assumes gMutex is locked.
318 SkThreadID thisThread = SkGetThreadID();
319 for (auto& task : *gRunning) {
320 if (task.thread == thisThread) {
321 info("Likely culprit:\n");
322 task.dump();
323 }
324 }
325 }
326
327 #if defined(SK_BUILD_FOR_WIN)
328 static LONG WINAPI crash_handler(EXCEPTION_POINTERS* e) {
329 static const struct {
330 const char* name;
331 DWORD code;
332 } kExceptions[] = {
333 #define _(E) {#E, E}
334 _(EXCEPTION_ACCESS_VIOLATION),
335 _(EXCEPTION_BREAKPOINT),
336 _(EXCEPTION_INT_DIVIDE_BY_ZERO),
337 _(EXCEPTION_STACK_OVERFLOW),
338 // TODO: more?
339 #undef _
340 };
341
342 SkAutoSpinlock lock(gMutex);
343
344 const DWORD code = e->ExceptionRecord->ExceptionCode;
345 info("\nCaught exception %lu", code);
346 for (const auto& exception : kExceptions) {
347 if (exception.code == code) {
348 info(" %s", exception.name);
349 }
350 }
351 info(", was running:\n");
352 for (auto& task : *gRunning) {
353 task.dump();
354 }
355 find_culprit();
356 fflush(stdout);
357
358 // Execute default exception handler... hopefully, exit.
359 return EXCEPTION_EXECUTE_HANDLER;
360 }
361
362 static void setup_crash_handler() {
363 SetUnhandledExceptionFilter(crash_handler);
364 }
365 #else
366 #include <signal.h>
367 #if !defined(SK_BUILD_FOR_ANDROID)
368 #include <execinfo.h>
369 #endif
370
371 static constexpr int max_of() { return 0; }
372 template <typename... Rest>
373 static constexpr int max_of(int x, Rest... rest) {
374 return x > max_of(rest...) ? x : max_of(rest...);
375 }
376
377 static void (*previous_handler[max_of(SIGABRT,SIGBUS,SIGFPE,SIGILL,SIGSEGV,SIGTERM)+1])(int);
378
379 static void crash_handler(int sig) {
380 SkAutoSpinlock lock(gMutex);
381
382 info("\nCaught signal %d [%s] (%dMB RAM, peak %dMB), was running:\n",
383 sig, strsignal(sig),
384 sk_tools::getCurrResidentSetSizeMB(), sk_tools::getMaxResidentSetSizeMB());
385
386 for (auto& task : *gRunning) {
387 task.dump();
388 }
389 find_culprit();
390
391 #if !defined(SK_BUILD_FOR_ANDROID)
392 void* stack[128];
393 int count = backtrace(stack, std::size(stack));
394 char** symbols = backtrace_symbols(stack, count);
395 info("\nStack trace:\n");
396 for (int i = 0; i < count; i++) {
397 info(" %s\n", symbols[i]);
398 }
399 #endif
400 fflush(stdout);
401
402 if (sig == SIGINT && FLAGS_ignoreSigInt) {
403 info("Ignoring signal %d because of --ignoreSigInt.\n"
404 "This is probably a sign the bot is overloaded with work.\n", sig);
405 } else {
406 signal(sig, previous_handler[sig]);
407 raise(sig);
408 }
409 }
410
411 static void setup_crash_handler() {
412 const int kSignals[] = { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM };
413 for (int sig : kSignals) {
414 previous_handler[sig] = signal(sig, crash_handler);
415 }
416 }
417 #endif
418
419 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
420
421 struct Gold : public SkString {
422 Gold() : SkString("") {}
423 Gold(const SkString& sink, const SkString& src,
424 const SkString& srcOptions, const SkString& name,
425 const SkString& md5)
426 : SkString("") {
427 this->append(sink);
428 this->append(src);
429 this->append(srcOptions);
430 this->append(name);
431 this->append(md5);
432 }
433 struct Hash {
434 uint32_t operator()(const Gold& g) const {
435 return SkGoodHash()((const SkString&)g);
436 }
437 };
438 };
439 static THashSet<Gold, Gold::Hash>* gGold = new THashSet<Gold, Gold::Hash>;
440
441 static void add_gold(JsonWriter::BitmapResult r) {
442 gGold->add(Gold(r.config, r.sourceType, r.sourceOptions, r.name, r.md5));
443 }
444
445 static void gather_gold() {
446 if (!FLAGS_readPath.isEmpty()) {
447 SkString path(FLAGS_readPath[0]);
448 path.append("/dm.json");
449 if (!JsonWriter::ReadJson(path.c_str(), add_gold)) {
450 fail(SkStringPrintf("Couldn't read %s for golden results.", path.c_str()));
451 }
452 }
453 }
454
455 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
456
457 #if defined(SK_BUILD_FOR_WIN)
458 static constexpr char kNewline[] = "\r\n";
459 #else
460 static constexpr char kNewline[] = "\n";
461 #endif
462
463 static THashSet<SkString>* gUninterestingHashes = new THashSet<SkString>;
464
465 static void gather_uninteresting_hashes() {
466 if (!FLAGS_uninterestingHashesFile.isEmpty()) {
467 sk_sp<SkData> data(SkData::MakeFromFileName(FLAGS_uninterestingHashesFile[0]));
468 if (!data) {
469 info("WARNING: unable to read uninteresting hashes from %s\n",
470 FLAGS_uninterestingHashesFile[0]);
471 return;
472 }
473
474 // Copy to a string to make sure SkStrSplit has a terminating \0 to find.
475 SkString contents((const char*)data->data(), data->size());
476
477 TArray<SkString> hashes;
478 SkStrSplit(contents.c_str(), kNewline, &hashes);
479 for (const SkString& hash : hashes) {
480 gUninterestingHashes->add(hash);
481 }
482 info("FYI: loaded %d distinct uninteresting hashes from %d lines\n",
483 gUninterestingHashes->count(), hashes.size());
484 }
485 }
486
487 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
488
489 struct TaggedSrc : public std::unique_ptr<Src> {
490 SkString tag;
491 SkString options;
492 };
493
494 struct TaggedSink : public std::unique_ptr<Sink> {
495 SkString tag;
496 };
497
498 static constexpr bool kMemcpyOK = true;
499
500 static TArray<TaggedSrc, kMemcpyOK>* gSrcs = new TArray<TaggedSrc, kMemcpyOK>;
501 static TArray<TaggedSink, kMemcpyOK>* gSinks = new TArray<TaggedSink, kMemcpyOK>;
502
503 static bool in_shard() {
504 static int N = 0;
505 return N++ % FLAGS_shards == FLAGS_shard;
506 }
507
508 static void push_src(const char* tag, ImplicitString options, Src* inSrc) {
509 std::unique_ptr<Src> src(inSrc);
510 if (in_shard() && FLAGS_src.contains(tag) &&
511 !CommandLineFlags::ShouldSkip(FLAGS_match, src->name().c_str())) {
512 TaggedSrc& s = gSrcs->push_back();
513 s.reset(src.release()); // NOLINT(misc-uniqueptr-reset-release)
514 s.tag = tag;
515 s.options = options;
516 }
517 }
518
519 static void push_codec_src(Path path, CodecSrc::Mode mode, CodecSrc::DstColorType dstColorType,
520 SkAlphaType dstAlphaType, float scale) {
521 if (FLAGS_simpleCodec) {
522 const bool simple = CodecSrc::kCodec_Mode == mode || CodecSrc::kAnimated_Mode == mode;
523 if (!simple || dstColorType != CodecSrc::kGetFromCanvas_DstColorType || scale != 1.0f) {
524 // Only decode in the simple case.
525 return;
526 }
527 }
528 SkString folder;
529 switch (mode) {
530 case CodecSrc::kCodec_Mode:
531 folder.append("codec");
532 break;
533 case CodecSrc::kCodecZeroInit_Mode:
534 folder.append("codec_zero_init");
535 break;
536 case CodecSrc::kScanline_Mode:
537 folder.append("scanline");
538 break;
539 case CodecSrc::kStripe_Mode:
540 folder.append("stripe");
541 break;
542 case CodecSrc::kCroppedScanline_Mode:
543 folder.append("crop");
544 break;
545 case CodecSrc::kSubset_Mode:
546 folder.append("codec_subset");
547 break;
548 case CodecSrc::kAnimated_Mode:
549 folder.append("codec_animated");
550 break;
551 }
552
553 switch (dstColorType) {
554 case CodecSrc::kGrayscale_Always_DstColorType:
555 folder.append("_kGray8");
556 break;
557 case CodecSrc::kNonNative8888_Always_DstColorType:
558 folder.append("_kNonNative");
559 break;
560 default:
561 break;
562 }
563
564 switch (dstAlphaType) {
565 case kPremul_SkAlphaType:
566 folder.append("_premul");
567 break;
568 case kUnpremul_SkAlphaType:
569 folder.append("_unpremul");
570 break;
571 default:
572 break;
573 }
574
575 if (1.0f != scale) {
576 folder.appendf("_%.3f", scale);
577 }
578
579 CodecSrc* src = new CodecSrc(path, mode, dstColorType, dstAlphaType, scale);
580 push_src("image", folder, src);
581 }
582
583 static void push_android_codec_src(Path path, CodecSrc::DstColorType dstColorType,
584 SkAlphaType dstAlphaType, int sampleSize) {
585 SkString folder;
586 folder.append("scaled_codec");
587
588 switch (dstColorType) {
589 case CodecSrc::kGrayscale_Always_DstColorType:
590 folder.append("_kGray8");
591 break;
592 case CodecSrc::kNonNative8888_Always_DstColorType:
593 folder.append("_kNonNative");
594 break;
595 default:
596 break;
597 }
598
599 switch (dstAlphaType) {
600 case kPremul_SkAlphaType:
601 folder.append("_premul");
602 break;
603 case kUnpremul_SkAlphaType:
604 folder.append("_unpremul");
605 break;
606 default:
607 break;
608 }
609
610 if (1 != sampleSize) {
611 folder.appendf("_%.3f", 1.0f / (float) sampleSize);
612 }
613
614 AndroidCodecSrc* src = new AndroidCodecSrc(path, dstColorType, dstAlphaType, sampleSize);
615 push_src("image", folder, src);
616 }
617
618 static void push_image_gen_src(Path path, ImageGenSrc::Mode mode, SkAlphaType alphaType, bool isGpu)
619 {
620 SkString folder;
621 switch (mode) {
622 case ImageGenSrc::kCodec_Mode:
623 folder.append("gen_codec");
624 break;
625 case ImageGenSrc::kPlatform_Mode:
626 folder.append("gen_platform");
627 break;
628 }
629
630 if (isGpu) {
631 folder.append("_gpu");
632 } else {
633 switch (alphaType) {
634 case kOpaque_SkAlphaType:
635 folder.append("_opaque");
636 break;
637 case kPremul_SkAlphaType:
638 folder.append("_premul");
639 break;
640 case kUnpremul_SkAlphaType:
641 folder.append("_unpremul");
642 break;
643 default:
644 break;
645 }
646 }
647
648 ImageGenSrc* src = new ImageGenSrc(path, mode, alphaType, isGpu);
649 push_src("image", folder, src);
650 }
651
652 #ifdef SK_ENABLE_ANDROID_UTILS
653 static void push_brd_src(Path path, CodecSrc::DstColorType dstColorType, BRDSrc::Mode mode,
654 uint32_t sampleSize) {
655 SkString folder("brd_android_codec");
656 switch (mode) {
657 case BRDSrc::kFullImage_Mode:
658 break;
659 case BRDSrc::kDivisor_Mode:
660 folder.append("_divisor");
661 break;
662 default:
663 SkASSERT(false);
664 return;
665 }
666
667 switch (dstColorType) {
668 case CodecSrc::kGetFromCanvas_DstColorType:
669 break;
670 case CodecSrc::kGrayscale_Always_DstColorType:
671 folder.append("_kGray");
672 break;
673 default:
674 SkASSERT(false);
675 return;
676 }
677
678 if (1 != sampleSize) {
679 folder.appendf("_%.3f", 1.0f / (float) sampleSize);
680 }
681
682 BRDSrc* src = new BRDSrc(path, mode, dstColorType, sampleSize);
683 push_src("image", folder, src);
684 }
685
686 static void push_brd_srcs(Path path, bool gray) {
687 if (gray) {
688 // Only run grayscale to one sampleSize and Mode. Though interesting
689 // to test grayscale, it should not reveal anything across various
690 // sampleSizes and Modes
691 // Arbitrarily choose Mode and sampleSize.
692 push_brd_src(path, CodecSrc::kGrayscale_Always_DstColorType,
693 BRDSrc::kFullImage_Mode, 2);
694 }
695
696 // Test on a variety of sampleSizes, making sure to include:
697 // - 2, 4, and 8, which are natively supported by jpeg
698 // - multiples of 2 which are not divisible by 4 (analogous for 4)
699 // - larger powers of two, since BRD clients generally use powers of 2
700 // We will only produce output for the larger sizes on large images.
701 const uint32_t sampleSizes[] = { 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 24, 32, 64 };
702
703 const BRDSrc::Mode modes[] = { BRDSrc::kFullImage_Mode, BRDSrc::kDivisor_Mode, };
704
705 for (uint32_t sampleSize : sampleSizes) {
706 for (BRDSrc::Mode mode : modes) {
707 push_brd_src(path, CodecSrc::kGetFromCanvas_DstColorType, mode, sampleSize);
708 }
709 }
710 }
711 #endif // SK_ENABLE_ANDROID_UTILS
712
713 static void push_codec_srcs(Path path) {
714 sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
715 if (!encoded) {
716 info("Couldn't read %s.", path.c_str());
717 return;
718 }
719 std::unique_ptr<SkCodec> codec = SkCodec::MakeFromData(encoded);
720 if (nullptr == codec) {
721 info("Couldn't create codec for %s.", path.c_str());
722 return;
723 }
724
725 // native scaling is only supported by WEBP and JPEG
726 bool supportsNativeScaling = false;
727
728 TArray<CodecSrc::Mode> nativeModes;
729 nativeModes.push_back(CodecSrc::kCodec_Mode);
730 nativeModes.push_back(CodecSrc::kCodecZeroInit_Mode);
731 switch (codec->getEncodedFormat()) {
732 case SkEncodedImageFormat::kJPEG:
733 nativeModes.push_back(CodecSrc::kScanline_Mode);
734 nativeModes.push_back(CodecSrc::kStripe_Mode);
735 nativeModes.push_back(CodecSrc::kCroppedScanline_Mode);
736 supportsNativeScaling = true;
737 break;
738 case SkEncodedImageFormat::kWEBP:
739 nativeModes.push_back(CodecSrc::kSubset_Mode);
740 supportsNativeScaling = true;
741 break;
742 case SkEncodedImageFormat::kDNG:
743 break;
744 default:
745 nativeModes.push_back(CodecSrc::kScanline_Mode);
746 break;
747 }
748
749 TArray<CodecSrc::DstColorType> colorTypes;
750 colorTypes.push_back(CodecSrc::kGetFromCanvas_DstColorType);
751 colorTypes.push_back(CodecSrc::kNonNative8888_Always_DstColorType);
752 switch (codec->getInfo().colorType()) {
753 case kGray_8_SkColorType:
754 colorTypes.push_back(CodecSrc::kGrayscale_Always_DstColorType);
755 break;
756 default:
757 break;
758 }
759
760 TArray<SkAlphaType> alphaModes;
761 alphaModes.push_back(kPremul_SkAlphaType);
762 if (codec->getInfo().alphaType() != kOpaque_SkAlphaType) {
763 alphaModes.push_back(kUnpremul_SkAlphaType);
764 }
765
766 for (CodecSrc::Mode mode : nativeModes) {
767 for (CodecSrc::DstColorType colorType : colorTypes) {
768 for (SkAlphaType alphaType : alphaModes) {
769 // Only test kCroppedScanline_Mode when the alpha type is premul. The test is
770 // slow and won't be interestingly different with different alpha types.
771 if (CodecSrc::kCroppedScanline_Mode == mode &&
772 kPremul_SkAlphaType != alphaType) {
773 continue;
774 }
775
776 push_codec_src(path, mode, colorType, alphaType, 1.0f);
777
778 // Skip kNonNative on different native scales. It won't be interestingly
779 // different.
780 if (supportsNativeScaling &&
781 CodecSrc::kNonNative8888_Always_DstColorType == colorType) {
782 // Native Scales
783 // SkJpegCodec natively supports scaling to the following:
784 for (auto scale : { 0.125f, 0.25f, 0.375f, 0.5f, 0.625f, 0.750f, 0.875f }) {
785 push_codec_src(path, mode, colorType, alphaType, scale);
786 }
787 }
788 }
789 }
790 }
791
792 {
793 std::vector<SkCodec::FrameInfo> frameInfos = codec->getFrameInfo();
794 if (frameInfos.size() > 1) {
795 for (auto dstCT : { CodecSrc::kNonNative8888_Always_DstColorType,
796 CodecSrc::kGetFromCanvas_DstColorType }) {
797 for (auto at : { kUnpremul_SkAlphaType, kPremul_SkAlphaType }) {
798 push_codec_src(path, CodecSrc::kAnimated_Mode, dstCT, at, 1.0f);
799 }
800 }
801 for (float scale : { .5f, .33f }) {
802 push_codec_src(path, CodecSrc::kAnimated_Mode, CodecSrc::kGetFromCanvas_DstColorType,
803 kPremul_SkAlphaType, scale);
804 }
805 }
806
807 }
808
809 if (FLAGS_simpleCodec) {
810 return;
811 }
812
813 const int sampleSizes[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
814
815 for (int sampleSize : sampleSizes) {
816 for (CodecSrc::DstColorType colorType : colorTypes) {
817 for (SkAlphaType alphaType : alphaModes) {
818 // We can exercise all of the kNonNative support code in the swizzler with just a
819 // few sample sizes. Skip the rest.
820 if (CodecSrc::kNonNative8888_Always_DstColorType == colorType && sampleSize > 3) {
821 continue;
822 }
823
824 push_android_codec_src(path, colorType, alphaType, sampleSize);
825 }
826 }
827 }
828
829 const char* ext = strrchr(path.c_str(), '.');
830 if (ext) {
831 ext++;
832
833 static const char* const rawExts[] = {
834 "arw", "cr2", "dng", "nef", "nrw", "orf", "raf", "rw2", "pef", "srw",
835 "ARW", "CR2", "DNG", "NEF", "NRW", "ORF", "RAF", "RW2", "PEF", "SRW",
836 };
837 for (const char* rawExt : rawExts) {
838 if (0 == strcmp(rawExt, ext)) {
839 // RAW is not supported by image generator (skbug.com/40036243) or BRD.
840 return;
841 }
842 }
843
844 #ifdef SK_ENABLE_ANDROID_UTILS
845 static const char* const brdExts[] = {
846 "jpg", "jpeg", "png", "webp",
847 "JPG", "JPEG", "PNG", "WEBP",
848 };
849 for (const char* brdExt : brdExts) {
850 if (0 == strcmp(brdExt, ext)) {
851 bool gray = codec->getInfo().colorType() == kGray_8_SkColorType;
852 push_brd_srcs(path, gray);
853 break;
854 }
855 }
856 #endif
857 }
858
859 // Push image generator GPU test.
860 push_image_gen_src(path, ImageGenSrc::kCodec_Mode, codec->getInfo().alphaType(), true);
861
862 // Push image generator CPU tests.
863 for (SkAlphaType alphaType : alphaModes) {
864 push_image_gen_src(path, ImageGenSrc::kCodec_Mode, alphaType, false);
865
866 #if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
867 if (SkEncodedImageFormat::kWEBP != codec->getEncodedFormat() &&
868 SkEncodedImageFormat::kWBMP != codec->getEncodedFormat() &&
869 kUnpremul_SkAlphaType != alphaType)
870 {
871 push_image_gen_src(path, ImageGenSrc::kPlatform_Mode, alphaType, false);
872 }
873 #elif defined(SK_BUILD_FOR_WIN)
874 if (SkEncodedImageFormat::kWEBP != codec->getEncodedFormat() &&
875 SkEncodedImageFormat::kWBMP != codec->getEncodedFormat())
876 {
877 push_image_gen_src(path, ImageGenSrc::kPlatform_Mode, alphaType, false);
878 }
879 #elif defined(SK_ENABLE_NDK_IMAGES)
880 push_image_gen_src(path, ImageGenSrc::kPlatform_Mode, alphaType, false);
881 #endif
882 }
883 }
884
885 template <typename T>
886 void gather_file_srcs(const CommandLineFlags::StringArray& flags,
887 const char* ext,
888 const char* src_name = nullptr) {
889 if (!src_name) {
890 // With the exception of Lottie files, the source name is the extension.
891 src_name = ext;
892 }
893
894 for (int i = 0; i < flags.size(); i++) {
895 const char* path = flags[i];
896 if (sk_isdir(path)) {
897 SkOSFile::Iter it(path, ext);
898 for (SkString file; it.next(&file); ) {
899 push_src(src_name, "", new T(SkOSPath::Join(path, file.c_str())));
900 }
901 } else {
902 push_src(src_name, "", new T(path));
903 }
904 }
905 }
906
907 static bool gather_srcs() {
908 for (const skiagm::GMFactory& f : skiagm::GMRegistry::Range()) {
909 push_src("gm", "", new GMSrc(f));
910 }
911
912 gather_file_srcs<SKPSrc>(FLAGS_skps, "skp");
913 gather_file_srcs<MSKPSrc>(FLAGS_mskps, "mskp");
914 #if defined(SK_ENABLE_SKOTTIE)
915 gather_file_srcs<SkottieSrc>(FLAGS_lotties, "json", "lottie");
916 #endif
917 #if defined(SK_ENABLE_SVG)
918 gather_file_srcs<SVGSrc>(FLAGS_svgs, "svg");
919 #endif
920 if (!FLAGS_bisect.isEmpty()) {
921 // An empty l/r trail string will draw all the paths.
922 push_src("bisect", "",
923 new BisectSrc(FLAGS_bisect[0], FLAGS_bisect.size() > 1 ? FLAGS_bisect[1] : ""));
924 }
925
926 TArray<SkString> images;
927 if (!CommonFlags::CollectImages(FLAGS_images, &images)) {
928 return false;
929 }
930
931 for (const SkString& image : images) {
932 push_codec_srcs(image);
933 }
934
935 TArray<SkString> colorImages;
936 if (!CommonFlags::CollectImages(FLAGS_colorImages, &colorImages)) {
937 return false;
938 }
939
940 for (const SkString& colorImage : colorImages) {
941 push_src("colorImage", "decode_native", new ColorCodecSrc(colorImage, false));
942 push_src("colorImage", "decode_to_dst", new ColorCodecSrc(colorImage, true));
943 }
944
945 return true;
946 }
947
948 static void push_sink(const SkCommandLineConfig& config, Sink* s) {
949 std::unique_ptr<Sink> sink(s);
950
951 // Try a simple Src as a canary. If it fails, skip this sink.
952 struct : public Src {
953 Result draw(SkCanvas* c, skiatest::graphite::GraphiteTestContext*) const override {
954 c->drawRect(SkRect::MakeWH(1,1), SkPaint());
955 return Result::Ok();
956 }
957 SkISize size() const override { return SkISize::Make(16, 16); }
958 Name name() const override { return "justOneRect"; }
959 } justOneRect;
960
961 SkBitmap bitmap;
962 SkDynamicMemoryWStream stream;
963 SkString log;
964 Result result = sink->draw(justOneRect, &bitmap, &stream, &log);
965 if (result.isFatal()) {
966 info("Could not run %s: %s\n", config.getTag().c_str(), result.c_str());
967 exit(1);
968 }
969
970 TaggedSink& ts = gSinks->push_back();
971 ts.reset(sink.release()); // NOLINT(misc-uniqueptr-reset-release)
972 ts.tag = config.getTag();
973 }
974
975 static Sink* create_sink(
976 #if defined(SK_GANESH)
977 const GrContextOptions& grCtxOptions,
978 #endif
979 #if defined(SK_GRAPHITE)
980 const skiatest::graphite::TestOptions& graphiteOptions,
981 #endif
982 const SkCommandLineConfig* config) {
983 #if defined(SK_GANESH)
984 if (FLAGS_gpu) {
985 if (const SkCommandLineConfigGpu* gpuConfig = config->asConfigGpu()) {
986 GrContextFactory testFactory(grCtxOptions);
987 if (!testFactory.get(gpuConfig->getContextType(), gpuConfig->getContextOverrides())) {
988 info("WARNING: can not create GPU context for config '%s'. "
989 "GM tests will be skipped.\n", gpuConfig->getTag().c_str());
990 return nullptr;
991 }
992 if (gpuConfig->getTestPersistentCache()) {
993 return new GPUPersistentCacheTestingSink(gpuConfig, grCtxOptions);
994 } else if (gpuConfig->getTestPrecompileGanesh()) {
995 return new GaneshPrecompileTestingSink(gpuConfig, grCtxOptions);
996 } else if (gpuConfig->getUseDDLSink()) {
997 return new GPUDDLSink(gpuConfig, grCtxOptions);
998 } else if (gpuConfig->getSlug()) {
999 return new GPUSlugSink(gpuConfig, grCtxOptions);
1000 } else if (gpuConfig->getSerializedSlug()) {
1001 return new GPUSerializeSlugSink(gpuConfig, grCtxOptions);
1002 } else if (gpuConfig->getRemoteSlug()) {
1003 return new GPURemoteSlugSink(gpuConfig, grCtxOptions);
1004 } else {
1005 return new GPUSink(gpuConfig, grCtxOptions);
1006 }
1007 }
1008 }
1009 #endif
1010 #if defined(SK_GRAPHITE)
1011 if (FLAGS_graphite) {
1012 if (const SkCommandLineConfigGraphite *graphiteConfig = config->asConfigGraphite()) {
1013 if (graphiteConfig->getTestPersistentStorage()) {
1014 return new GraphitePersistentPipelineStorageTestingSink(graphiteConfig,
1015 graphiteOptions);
1016 } else if (graphiteConfig->getTestPipelineTracking()) {
1017 return new GraphitePipelineTrackingSink(graphiteConfig, graphiteOptions);
1018 } else
1019 #if defined(SK_ENABLE_PRECOMPILE)
1020 if (graphiteConfig->getTestPrecompileGraphite()) {
1021 return new GraphitePrecompileTestingSink(graphiteConfig, graphiteOptions);
1022 } else
1023 #endif // SK_ENABLE_PRECOMPILE
1024 {
1025 return new GraphiteSink(graphiteConfig, graphiteOptions);
1026 }
1027 }
1028 }
1029 #endif // SK_GRAPHITE
1030 if (const SkCommandLineConfigSvg* svgConfig = config->asConfigSvg()) {
1031 int pageIndex = svgConfig->getPageIndex();
1032 return new SVGSink(pageIndex);
1033 }
1034
1035 #define SINK(t, sink, ...) if (config->getBackend().equals(t)) return new sink(__VA_ARGS__)
1036
1037 if (FLAGS_cpu) {
1038 SINK("r8", RasterSink, kR8_unorm_SkColorType);
1039 SINK("565", RasterSink, kRGB_565_SkColorType);
1040 SINK("4444", RasterSink, kARGB_4444_SkColorType);
1041 SINK("8888", RasterSink, kN32_SkColorType);
1042 SINK("rgba", RasterSink, kRGBA_8888_SkColorType);
1043 SINK("bgra", RasterSink, kBGRA_8888_SkColorType);
1044 SINK("rgbx", RasterSink, kRGB_888x_SkColorType);
1045 SINK("1010102", RasterSink, kRGBA_1010102_SkColorType);
1046 SINK("101010x", RasterSink, kRGB_101010x_SkColorType);
1047 SINK("bgra1010102", RasterSink, kBGRA_1010102_SkColorType);
1048 SINK("bgr101010x", RasterSink, kBGR_101010x_SkColorType);
1049 SINK("f16", RasterSink, kRGBA_F16_SkColorType);
1050 SINK("f16norm", RasterSink, kRGBA_F16Norm_SkColorType);
1051 SINK("f16f16f16x", RasterSink, kRGB_F16F16F16x_SkColorType);
1052 SINK("f32", RasterSink, kRGBA_F32_SkColorType);
1053 SINK("srgba", RasterSink, kSRGBA_8888_SkColorType);
1054
1055 SINK("pdf", PDFSink, false, SK_ScalarDefaultRasterDPI);
1056 SINK("skp", SKPSink);
1057 SINK("svg", SVGSink);
1058 SINK("null", NullSink);
1059 SINK("xps", XPSSink);
1060 SINK("pdfa", PDFSink, true, SK_ScalarDefaultRasterDPI);
1061 SINK("pdf300", PDFSink, false, 300);
1062 SINK("jsdebug", DebugSink);
1063 }
1064 #undef SINK
1065 return nullptr;
1066 }
1067
1068 static Sink* create_via(const SkString& tag, Sink* wrapped) {
1069 #define VIA(t, via, ...) if (tag.equals(t)) return new via(__VA_ARGS__)
1070 #ifdef TEST_VIA_SVG
1071 VIA("svg", ViaSVG, wrapped);
1072 #endif
1073 VIA("serialize", ViaSerialization, wrapped);
1074 VIA("pic", ViaPicture, wrapped);
1075 VIA("rtblend", ViaRuntimeBlend, wrapped);
1076
1077 if (FLAGS_matrix.size() == 4) {
1078 SkMatrix m;
1079 m.reset();
1080 m.setScaleX((SkScalar)atof(FLAGS_matrix[0]));
1081 m.setSkewX ((SkScalar)atof(FLAGS_matrix[1]));
1082 m.setSkewY ((SkScalar)atof(FLAGS_matrix[2]));
1083 m.setScaleY((SkScalar)atof(FLAGS_matrix[3]));
1084 VIA("matrix", ViaMatrix, m, wrapped);
1085 VIA("upright", ViaUpright, m, wrapped);
1086 }
1087
1088 #undef VIA
1089
1090 return nullptr;
1091 }
1092
1093 static bool gather_sinks(
1094 #if defined(SK_GANESH)
1095 const GrContextOptions& grCtxOptions,
1096 #endif
1097 #if defined(SK_GRAPHITE)
1098 const skiatest::graphite::TestOptions& graphiteOptions,
1099 #endif
1100 bool defaultConfigs) {
1101 if (FLAGS_src.size() == 1 && FLAGS_src.contains("tests")) {
1102 // If we're just running tests skip trying to accumulate sinks. The 'justOneRect' test
1103 // can fail for protected contexts.
1104 return true;
1105 }
1106
1107 SkCommandLineConfigArray configs;
1108 ParseConfigs(FLAGS_config, &configs);
1109 AutoreleasePool pool;
1110 for (int i = 0; i < configs.size(); i++) {
1111 const SkCommandLineConfig& config = *configs[i];
1112 Sink* sink = create_sink(
1113 #if defined(SK_GANESH)
1114 grCtxOptions,
1115 #endif
1116 #if defined(SK_GRAPHITE)
1117 graphiteOptions,
1118 #endif
1119 &config);
1120 if (sink == nullptr) {
1121 info("Skipping config %s: Don't understand '%s'.\n", config.getTag().c_str(),
1122 config.getTag().c_str());
1123 continue;
1124 }
1125
1126 // The command line config already parsed out the via-style color space. Apply it here.
1127 sink->setColorSpace(config.refColorSpace());
1128
1129 const TArray<SkString>& parts = config.getViaParts();
1130 for (int j = parts.size(); j-- > 0;) {
1131 const SkString& part = parts[j];
1132 Sink* next = create_via(part, sink);
1133 if (next == nullptr) {
1134 info("Skipping config %s: Don't understand '%s'.\n", config.getTag().c_str(),
1135 part.c_str());
1136 delete sink;
1137 sink = nullptr;
1138 break;
1139 }
1140 sink = next;
1141 }
1142 if (sink) {
1143 push_sink(config, sink);
1144 }
1145 }
1146
1147 // If no configs were requested (just running tests, perhaps?), then we're okay.
1148 if (configs.size() == 0 ||
1149 // If we're using the default configs, we're okay.
1150 defaultConfigs ||
1151 // Otherwise, make sure that all specified configs have become sinks.
1152 configs.size() == gSinks->size()) {
1153 return true;
1154 }
1155 return false;
1156 }
1157
1158 static bool match(const char* needle, const char* haystack) {
1159 if ('~' == needle[0]) {
1160 return !match(needle + 1, haystack);
1161 }
1162 if (0 == strcmp("_", needle)) {
1163 return true;
1164 }
1165 return nullptr != strstr(haystack, needle);
1166 }
1167
1168 static bool should_skip(const char* sink, const char* src,
1169 const char* srcOptions, const char* name) {
1170 for (int i = 0; i < FLAGS_skip.size() - 3; i += 4) {
1171 if (match(FLAGS_skip[i+0], sink) &&
1172 match(FLAGS_skip[i+1], src) &&
1173 match(FLAGS_skip[i+2], srcOptions) &&
1174 match(FLAGS_skip[i+3], name)) {
1175 return true;
1176 }
1177 }
1178 return false;
1179 }
1180
1181 // Even when a Task Sink reports to be non-threadsafe (e.g. GPU), we know things like
1182 // .png encoding are definitely thread safe. This lets us offload that work to CPU threads.
1183 static SkTaskGroup* gDefinitelyThreadSafeWork = new SkTaskGroup;
1184
1185 // The finest-grained unit of work we can run: draw a single Src into a single Sink,
1186 // report any errors, and perhaps write out the output: a .png of the bitmap, or a raw stream.
1187 struct Task {
1188 Task(const TaggedSrc& src, const TaggedSink& sink) : src(src), sink(sink) {}
1189 const TaggedSrc& src;
1190 const TaggedSink& sink;
1191
1192 static void Run(const Task& task) {
1193 AutoreleasePool pool;
1194 SkString name = task.src->name();
1195
1196 SkString log;
1197 if (!FLAGS_dryRun) {
1198 SkBitmap bitmap;
1199 SkDynamicMemoryWStream stream;
1200 start(task.sink.tag.c_str(), task.src.tag.c_str(),
1201 task.src.options.c_str(), name.c_str());
1202 Result result = task.sink->draw(*task.src, &bitmap, &stream, &log);
1203 if (!log.isEmpty()) {
1204 info("%s %s %s %s:\n%s\n", task.sink.tag.c_str()
1205 , task.src.tag.c_str()
1206 , task.src.options.c_str()
1207 , name.c_str()
1208 , log.c_str());
1209 }
1210 if (result.isSkip()) {
1211 done(task.sink.tag.c_str(), task.src.tag.c_str(),
1212 task.src.options.c_str(), name.c_str());
1213 return;
1214 }
1215 if (result.isFatal()) {
1216 fail(SkStringPrintf("%s %s %s %s: %s",
1217 task.sink.tag.c_str(),
1218 task.src.tag.c_str(),
1219 task.src.options.c_str(),
1220 name.c_str(),
1221 result.c_str()));
1222 }
1223
1224 // We're likely switching threads here, so we must capture by value, [=] or [foo,bar].
1225 SkStreamAsset* data = stream.detachAsStream().release();
1226 gDefinitelyThreadSafeWork->add([task,name,bitmap,data]{
1227 std::unique_ptr<SkStreamAsset> ownedData(data);
1228
1229 std::unique_ptr<HashAndEncode> hashAndEncode;
1230
1231 SkString md5;
1232 if (!FLAGS_writePath.isEmpty() || !FLAGS_readPath.isEmpty()) {
1233 SkMD5 hash;
1234 if (data->getLength()) {
1235 hash.writeStream(data, data->getLength());
1236 data->rewind();
1237 } else {
1238 hashAndEncode = std::make_unique<HashAndEncode>(bitmap);
1239 hashAndEncode->feedHash(&hash);
1240 }
1241 md5 = hash.finish().toLowercaseHexString();
1242 }
1243
1244 if (!FLAGS_readPath.isEmpty() &&
1245 !gGold->contains(Gold(task.sink.tag, task.src.tag,
1246 task.src.options, name, md5))) {
1247 fail(SkStringPrintf("%s not found for %s %s %s %s in %s",
1248 md5.c_str(),
1249 task.sink.tag.c_str(),
1250 task.src.tag.c_str(),
1251 task.src.options.c_str(),
1252 name.c_str(),
1253 FLAGS_readPath[0]));
1254 }
1255
1256 // Tests sometimes use a nullptr ext to indicate no image should be uploaded.
1257 const char* ext = task.sink->fileExtension();
1258 if (ext && !FLAGS_writePath.isEmpty()) {
1259 #if defined(SK_BUILD_FOR_MAC)
1260 if (FLAGS_rasterize_pdf && SkString("pdf").equals(ext)) {
1261 SkASSERT(data->getLength() > 0);
1262
1263 sk_sp<SkData> blob = SkData::MakeFromStream(data, data->getLength());
1264
1265 SkUniqueCFRef<CGDataProviderRef> provider{
1266 CGDataProviderCreateWithData(nullptr,
1267 blob->data(),
1268 blob->size(),
1269 nullptr)};
1270
1271 SkUniqueCFRef<CGPDFDocumentRef> pdf{
1272 CGPDFDocumentCreateWithProvider(provider.get())};
1273
1274 CGPDFPageRef page = CGPDFDocumentGetPage(pdf.get(), 1);
1275
1276 CGRect bounds = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
1277 const int w = (int)CGRectGetWidth (bounds),
1278 h = (int)CGRectGetHeight(bounds);
1279
1280 SkBitmap rasterized;
1281 rasterized.allocPixels(SkImageInfo::Make(
1282 w, h, kRGBA_8888_SkColorType, kPremul_SkAlphaType));
1283 rasterized.eraseColor(SK_ColorWHITE);
1284
1285 SkUniqueCFRef<CGColorSpaceRef> cs{CGColorSpaceCreateDeviceRGB()};
1286 CGBitmapInfo info = kCGBitmapByteOrder32Big |
1287 (CGBitmapInfo)kCGImageAlphaPremultipliedLast;
1288
1289 SkUniqueCFRef<CGContextRef> ctx{CGBitmapContextCreate(
1290 rasterized.getPixels(), w,h,8, rasterized.rowBytes(), cs.get(), info)};
1291 CGContextDrawPDFPage(ctx.get(), page);
1292
1293 // Skip calling hashAndEncode->feedHash(SkMD5*)... we want the .pdf's hash.
1294 hashAndEncode = std::make_unique<HashAndEncode>(rasterized);
1295 WriteToDisk(task, md5, "png", nullptr,0, &rasterized, hashAndEncode.get());
1296 } else
1297 #endif
1298 if (data->getLength()) {
1299 WriteToDisk(task, md5, ext, data, data->getLength(), nullptr, nullptr);
1300 SkASSERT(bitmap.drawsNothing());
1301 } else if (!bitmap.drawsNothing()) {
1302 WriteToDisk(task, md5, ext, nullptr, 0, &bitmap, hashAndEncode.get());
1303 }
1304 }
1305
1306 SkPixmap pm;
1307 if (FLAGS_checkF16 && bitmap.colorType() == kRGBA_F16Norm_SkColorType &&
1308 bitmap.peekPixels(&pm)) {
1309 bool unclamped = false;
1310 for (int y = 0; y < pm.height() && !unclamped; ++y)
1311 for (int x = 0; x < pm.width() && !unclamped; ++x) {
1312 skvx::float4 rgba = from_half(skvx::half4::Load(pm.addr64(x, y)));
1313 float a = rgba[3];
1314 if (a > 1.0f || any(rgba < 0.0f) || any(rgba > a)) {
1315 SkDebugf("[%s] F16Norm pixel [%d, %d] unclamped: (%g, %g, %g, %g)\n",
1316 name.c_str(), x, y, rgba[0], rgba[1], rgba[2], rgba[3]);
1317 unclamped = true;
1318 }
1319 }
1320 }
1321 });
1322 }
1323 done(task.sink.tag.c_str(), task.src.tag.c_str(), task.src.options.c_str(), name.c_str());
1324 }
1325
1326 static SkString identify_gamut(SkColorSpace* cs) {
1327 if (!cs) {
1328 return SkString("untagged");
1329 }
1330
1331 skcms_Matrix3x3 gamut;
1332 if (cs->toXYZD50(&gamut)) {
1333 auto eq = [](skcms_Matrix3x3 x, skcms_Matrix3x3 y) {
1334 for (int i = 0; i < 3; i++)
1335 for (int j = 0; j < 3; j++) {
1336 if (x.vals[i][j] != y.vals[i][j]) { return false; }
1337 }
1338 return true;
1339 };
1340
1341 if (eq(gamut, SkNamedGamut::kSRGB )) { return SkString("sRGB"); }
1342 if (eq(gamut, SkNamedGamut::kAdobeRGB )) { return SkString("Adobe"); }
1343 if (eq(gamut, SkNamedGamut::kDisplayP3)) { return SkString("P3"); }
1344 if (eq(gamut, SkNamedGamut::kRec2020 )) { return SkString("2020"); }
1345 if (eq(gamut, SkNamedGamut::kXYZ )) { return SkString("XYZ"); }
1346 if (eq(gamut, gNarrow_toXYZD50 )) { return SkString("narrow"); }
1347 return SkString("other");
1348 }
1349 return SkString("non-XYZ");
1350 }
1351
1352 static SkString identify_transfer_fn(SkColorSpace* cs) {
1353 if (!cs) {
1354 return SkString("untagged");
1355 }
1356
1357 auto eq = [](skcms_TransferFunction x, skcms_TransferFunction y) {
1358 return x.g == y.g
1359 && x.a == y.a
1360 && x.b == y.b
1361 && x.c == y.c
1362 && x.d == y.d
1363 && x.e == y.e
1364 && x.f == y.f;
1365 };
1366
1367 skcms_TransferFunction tf;
1368 cs->transferFn(&tf);
1369 switch (skcms_TransferFunction_getType(&tf)) {
1370 case skcms_TFType_sRGBish:
1371 if (tf.a == 1 && tf.b == 0 && tf.c == 0 && tf.d == 0 && tf.e == 0 && tf.f == 0) {
1372 return SkStringPrintf("gamma %.3g", tf.g);
1373 }
1374 if (eq(tf, SkNamedTransferFn::kSRGB)) { return SkString("sRGB"); }
1375 if (eq(tf, SkNamedTransferFn::kRec2020)) { return SkString("2020"); }
1376 return SkStringPrintf("%.3g %.3g %.3g %.3g %.3g %.3g %.3g",
1377 tf.g, tf.a, tf.b, tf.c, tf.d, tf.e, tf.f);
1378
1379 case skcms_TFType_PQ:
1380 return SkStringPrintf("PQ %.3g", tf.a);
1381
1382 case skcms_TFType_HLG:
1383 return SkStringPrintf("HLGish %.3g %.3g %.3g", tf.a, tf.b, tf.c);
1384
1385 case skcms_TFType_PQish:
1386 if (eq(tf, SkNamedTransferFn::kPQ)) { return SkString("PQ"); }
1387 return SkStringPrintf("PQish %.3g %.3g %.3g %.3g %.3g %.3g",
1388 tf.a, tf.b, tf.c, tf.d, tf.e, tf.f);
1389
1390 case skcms_TFType_HLGish:
1391 if (eq(tf, SkNamedTransferFn::kHLG)) { return SkString("HLG"); }
1392 return SkStringPrintf("HLGish %.3g %.3g %.3g %.3g %.3g (%.3g)",
1393 tf.a, tf.b, tf.c, tf.d, tf.e, tf.f+1);
1394
1395 default: break;
1396 }
1397 return SkString("non-numeric");
1398 }
1399
1400 static void WriteToDisk(const Task& task,
1401 SkString md5,
1402 const char* ext,
1403 SkStream* data, size_t len,
1404 const SkBitmap* bitmap,
1405 const HashAndEncode* hashAndEncode) {
1406
1407 // Determine whether or not the OldestSupportedSkpVersion extra_config is provided.
1408 bool isOldestSupportedSkp = false;
1409 for (int i = 1; i < FLAGS_key.size(); i += 2) {
1410 if (0 == strcmp(FLAGS_key[i-1], "extra_config") &&
1411 0 == strcmp(FLAGS_key[i], "OldestSupportedSkpVersion")) {
1412 isOldestSupportedSkp = true;
1413 break;
1414 }
1415 }
1416
1417 JsonWriter::BitmapResult result;
1418 result.name = task.src->name();
1419 result.config = task.sink.tag;
1420 result.sourceType = task.src.tag;
1421 // If the OldestSupportedSkpVersion extra_config is provided, override the "skp"
1422 // source_type with "old-skp". This has the effect of grouping the oldest supported SKPs in
1423 // a separate Gold corpus for easier triaging.
1424 if (isOldestSupportedSkp && 0 == strcmp(result.sourceType.c_str(), "skp")) {
1425 result.sourceType = "old-skp";
1426 }
1427 result.sourceOptions = task.src.options;
1428 result.ext = ext;
1429 result.md5 = md5;
1430 if (bitmap) {
1431 result.gamut = identify_gamut (bitmap->colorSpace());
1432 result.transferFn = identify_transfer_fn (bitmap->colorSpace());
1433 result.colorType = ToolUtils::colortype_name (bitmap->colorType());
1434 result.alphaType = ToolUtils::alphatype_name (bitmap->alphaType());
1435 result.colorDepth = ToolUtils::colortype_depth(bitmap->colorType());
1436 }
1437 JsonWriter::AddBitmapResult(result);
1438
1439 // If an MD5 is uninteresting, we want it noted in the JSON file,
1440 // but don't want to dump it out as a .png (or whatever ext is).
1441 if (gUninterestingHashes->contains(md5)) {
1442 return;
1443 }
1444
1445 const char* dir = FLAGS_writePath[0];
1446 SkString resources = GetResourcePath();
1447 if (0 == strcmp(dir, "@")) { // Needed for iOS.
1448 dir = resources.c_str();
1449 }
1450 sk_mkdir(dir);
1451
1452 SkString path;
1453 if (FLAGS_nameByHash) {
1454 path = SkOSPath::Join(dir, result.md5.c_str());
1455 path.append(".");
1456 path.append(ext);
1457 if (sk_exists(path.c_str())) {
1458 return; // Content-addressed. If it exists already, we're done.
1459 }
1460 } else {
1461 path = SkOSPath::Join(dir, task.sink.tag.c_str());
1462 sk_mkdir(path.c_str());
1463 path = SkOSPath::Join(path.c_str(), task.src.tag.c_str());
1464 sk_mkdir(path.c_str());
1465 if (0 != strcmp(task.src.options.c_str(), "")) {
1466 path = SkOSPath::Join(path.c_str(), task.src.options.c_str());
1467 sk_mkdir(path.c_str());
1468 }
1469 path = SkOSPath::Join(path.c_str(), task.src->name().c_str());
1470 path.append(".");
1471 path.append(ext);
1472 }
1473
1474 SkFILEWStream file(path.c_str());
1475 if (!file.isValid()) {
1476 fail(SkStringPrintf("Can't open %s for writing.\n", path.c_str()));
1477 return;
1478 }
1479 if (bitmap) {
1480 SkASSERT(hashAndEncode);
1481 if (!hashAndEncode->encodePNG(&file,
1482 result.md5.c_str(),
1483 FLAGS_key,
1484 FLAGS_properties)) {
1485 fail(SkStringPrintf("Can't encode PNG to %s.\n", path.c_str()));
1486 return;
1487 }
1488 } else {
1489 if (!file.writeStream(data, len)) {
1490 fail(SkStringPrintf("Can't write to %s.\n", path.c_str()));
1491 return;
1492 }
1493 }
1494 }
1495 };
1496
1497 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1498 #if defined(SK_DISABLE_LEGACY_TESTS)
1499 static int gather_tests() { return 0; }
1500 #else
1501 // Unit tests don't fit so well into the Src/Sink model, so we give them special treatment.
1502
1503 static SkTDArray<skiatest::Test>* gCPUTests = new SkTDArray<skiatest::Test>;
1504 static SkTDArray<skiatest::Test>* gCPUSerialTests = new SkTDArray<skiatest::Test>;
1505 static SkTDArray<skiatest::Test>* gGaneshTests = new SkTDArray<skiatest::Test>;
1506 static SkTDArray<skiatest::Test>* gGraphiteTests = new SkTDArray<skiatest::Test>;
1507
1508 static int gather_tests() {
1509 if (!FLAGS_src.contains("tests")) {
1510 return 0;
1511 }
1512 for (const skiatest::Test& test : skiatest::TestRegistry::Range()) {
1513 if (!in_shard()) {
1514 continue;
1515 }
1516 if (CommandLineFlags::ShouldSkip(FLAGS_match, test.fName)) {
1517 continue;
1518 }
1519 if (test.fTestType == TestType::kGanesh && FLAGS_gpu) {
1520 gGaneshTests->push_back(test);
1521 #if defined(SK_GRAPHITE)
1522 } else if (test.fTestType == TestType::kGraphite && FLAGS_graphite) {
1523 gGraphiteTests->push_back(test);
1524 #endif
1525 } else if (test.fTestType == TestType::kCPU && FLAGS_cpu) {
1526 gCPUTests->push_back(test);
1527 } else if (test.fTestType == TestType::kCPUSerial && FLAGS_cpu) {
1528 gCPUSerialTests->push_back(test);
1529 }
1530 }
1531 return gCPUTests->size() + gCPUSerialTests->size() +
1532 gGaneshTests->size() + gGraphiteTests->size();
1533 }
1534
1535 struct DMReporter : public skiatest::Reporter {
1536 void reportFailed(const skiatest::Failure& failure) override {
1537 fail(failure.toString());
1538 }
1539 bool allowExtendedTest() const override {
1540 return FLAGS_pathOpsExtended;
1541 }
1542 bool verbose() const override { return FLAGS_veryVerbose; }
1543 };
1544
1545 static void run_cpu_test(skiatest::Test test) {
1546 DMReporter reporter;
1547 if (!FLAGS_dryRun && !should_skip("_", "tests", "_", test.fName)) {
1548 skiatest::ReporterContext ctx(&reporter, SkString(test.fName));
1549 start("unit", "test", "", test.fName);
1550 test.cpu(&reporter);
1551 }
1552 done("unit", "test", "", test.fName);
1553 }
1554
1555 #if defined(SK_GANESH)
1556 static void run_ganesh_test(skiatest::Test test, const GrContextOptions& grCtxOptions) {
1557 DMReporter reporter;
1558 if (!FLAGS_dryRun && !should_skip("_", "tests", "_", test.fName)) {
1559 AutoreleasePool pool;
1560 GrContextOptions options = grCtxOptions;
1561 test.modifyGrContextOptions(&options);
1562
1563 skiatest::ReporterContext ctx(&reporter, SkString(test.fName));
1564 start("unit", "test", "", test.fName);
1565 test.ganesh(&reporter, options);
1566 }
1567 done("unit", "test", "", test.fName);
1568 }
1569 #endif
1570
1571 #if defined(SK_GRAPHITE)
1572 static void run_graphite_test(skiatest::Test test,
1573 const skiatest::graphite::TestOptions& optionsIn) {
1574 DMReporter reporter;
1575 if (!FLAGS_dryRun && !should_skip("_", "tests", "_", test.fName)) {
1576 AutoreleasePool pool;
1577 skiatest::graphite::TestOptions options = optionsIn;
1578 test.modifyGraphiteContextOptions(&options.fContextOptions);
1579
1580 skiatest::ReporterContext ctx(&reporter, SkString(test.fName));
1581 start("unit", "test", "", test.fName);
1582 test.graphite(&reporter, options);
1583 }
1584 done("unit", "test", "", test.fName);
1585 }
1586 #endif
1587
1588 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1589
1590 TestHarness CurrentTestHarness() {
1591 return TestHarness::kDM;
1592 }
1593
1594 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1595
1596 #endif // !SK_DISABLE_LEGACY_TESTS
1597
1598 int main(int argc, char** argv) {
1599 CommandLineFlags::Parse(argc, argv);
1600
1601 initializeEventTracingForTools();
1602
1603 #if defined(SK_BUILD_FOR_IOS)
1604 cd_Documents();
1605 #endif
1606 setbuf(stdout, nullptr);
1607 setup_crash_handler();
1608
1609 skiatest::SetFontTestDataDirectory();
1610
1611 gSkForceRasterPipelineBlitter = FLAGS_forceRasterPipelineHP || FLAGS_forceRasterPipeline;
1612 gForceHighPrecisionRasterPipeline = FLAGS_forceRasterPipelineHP;
1613 #if defined(SK_GANESH)
1614 gCreateProtectedContext = FLAGS_createProtected;
1615 #endif
1616
1617 // The bots like having a verbose.log to upload, so always touch the file even if --verbose.
1618 if (!FLAGS_writePath.isEmpty()) {
1619 sk_mkdir(FLAGS_writePath[0]);
1620 gVLog = fopen(SkOSPath::Join(FLAGS_writePath[0], "verbose.log").c_str(), "w");
1621 }
1622 if (FLAGS_verbose) {
1623 gVLog = stderr;
1624 }
1625
1626 #if defined(SK_GRAPHITE)
1627 skiatest::graphite::TestOptions graphiteOptions;
1628 CommonFlags::SetTestOptions(&graphiteOptions);
1629 #endif
1630
1631 #if defined(SK_GANESH)
1632 GrContextOptions grCtxOptions;
1633 CommonFlags::SetCtxOptions(&grCtxOptions);
1634 #endif
1635
1636 dump_json(); // It's handy for the bots to assume this is ~never missing.
1637
1638 SkGraphics::Init();
1639 #if defined(SK_ENABLE_SVG)
1640 SkGraphics::SetOpenTypeSVGDecoderFactory(SkSVGOpenTypeSVGDecoder::Make);
1641 #endif
1642 SkTaskGroup::Enabler enabled(FLAGS_threads);
1643 CodecUtils::RegisterAllAvailable();
1644 ToolUtils::RegisterAvailableTypefaceFactories();
1645
1646 if (nullptr == GetResourceAsData("images/color_wheel.png")) {
1647 info("Some resources are missing. Do you need to set --resourcePath?\n");
1648 }
1649 gather_gold();
1650 gather_uninteresting_hashes();
1651
1652 if (!gather_srcs()) {
1653 return 1;
1654 }
1655 bool defaultConfigs = true;
1656 for (int i = 0; i < argc; i++) {
1657 if (strcmp(argv[i], "--config") == 0) {
1658 defaultConfigs = false;
1659 break;
1660 }
1661 }
1662 if (!gather_sinks(
1663 #if defined(SK_GANESH)
1664 grCtxOptions,
1665 #endif
1666 #if defined(SK_GRAPHITE)
1667 graphiteOptions,
1668 #endif
1669 defaultConfigs)) {
1670 return 1;
1671 }
1672
1673 const int testCount = gather_tests();
1674 gPending = gSrcs->size() * gSinks->size() + testCount;
1675 gTotalCounts = gPending;
1676 gLastUpdate = SkTime::GetNSecs();
1677 info("%d srcs * %d sinks + %d tests == %d tasks\n",
1678 gSrcs->size(), gSinks->size(), testCount,
1679 gPending);
1680
1681 #if !defined(SK_DISABLE_LEGACY_TESTS)
1682 // Kick off as much parallel work as we can, making note of any serial work we'll need to do.
1683 // However, execute all CPU-serial tests first so that they don't have races with parallel tests
1684 for (skiatest::Test& test : *gCPUSerialTests) { run_cpu_test(test); }
1685 #endif
1686
1687 SkTaskGroup parallel;
1688 TArray<Task> serial;
1689
1690 for (TaggedSink& sink : *gSinks) {
1691 for (TaggedSrc& src : *gSrcs) {
1692 if (src->veto(sink->flags()) ||
1693 should_skip(sink.tag.c_str(), src.tag.c_str(),
1694 src.options.c_str(), src->name().c_str())) {
1695 SkAutoSpinlock lock(gMutex);
1696 gPending--;
1697 continue;
1698 }
1699
1700 Task task(src, sink);
1701 if (src->serial() || sink->serial()) {
1702 serial.push_back(task);
1703 } else {
1704 parallel.add([task] { Task::Run(task); });
1705 }
1706 }
1707 }
1708
1709 #if !defined(SK_DISABLE_LEGACY_TESTS)
1710 for (skiatest::Test& test : *gCPUTests) {
1711 parallel.add([test] { run_cpu_test(test); });
1712 }
1713 #endif // !SK_DISABLE_LEGACY_TESTS
1714
1715 // With the parallel work running, run serial tasks and tests here on main thread.
1716 for (Task& task : serial) { Task::Run(task); }
1717
1718 #if !defined(SK_DISABLE_LEGACY_TESTS)
1719 #if defined(SK_GANESH)
1720 for (skiatest::Test& test : *gGaneshTests) { run_ganesh_test(test, grCtxOptions); }
1721 #endif
1722
1723 #if defined(SK_GRAPHITE)
1724 for (skiatest::Test& test : *gGraphiteTests) { run_graphite_test(test, graphiteOptions); }
1725 #endif
1726 #endif // !SK_DISABLE_LEGACY_TESTS
1727
1728 // Wait for any remaining parallel work to complete (including any spun off of serial tasks).
1729 parallel.wait();
1730 gDefinitelyThreadSafeWork->wait();
1731
1732 for (const TaggedSink& sink : *gSinks) {
1733 sink->done();
1734 }
1735
1736 // At this point we're back in single-threaded land.
1737
1738 // We'd better have run everything.
1739 SkASSERT(gPending == 0);
1740 // Make sure we've flushed all our results to disk.
1741 dump_json();
1742
1743 if (!gFailures->empty()) {
1744 info("Failures:\n");
1745 for (const SkString& fail : *gFailures) {
1746 info("\t%s\n", fail.c_str());
1747 }
1748 info("%d failures\n", gFailures->size());
1749 return 1;
1750 }
1751
1752 SkGraphics::PurgeAllCaches();
1753 info("Finished!\n");
1754
1755 return 0;
1756 }