Debian Codegraph @

tools/skpbench/skpbench.cpp

raw
1 /*
2 * Copyright 2016 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 "bench/BigPath.h"
9 #include "include/codec/SkCodec.h"
10 #include "include/codec/SkJpegDecoder.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkGraphics.h"
13 #include "include/core/SkPicture.h"
14 #include "include/core/SkPictureRecorder.h"
15 #include "include/core/SkStream.h"
16 #include "include/core/SkSurface.h"
17 #include "include/core/SkSurfaceProps.h"
18 #include "include/docs/SkMultiPictureDocument.h"
19 #include "include/effects/SkPerlinNoiseShader.h"
20 #include "include/gpu/ganesh/GrDirectContext.h"
21 #include "include/gpu/ganesh/SkSurfaceGanesh.h"
22 #include "include/private/chromium/GrDeferredDisplayList.h"
23 #include "src/core/SkOSFile.h"
24 #include "src/core/SkTaskGroup.h"
25 #include "src/gpu/ganesh/GrCaps.h"
26 #include "src/gpu/ganesh/GrDirectContextPriv.h"
27 #include "src/gpu/ganesh/SkGr.h"
28 #include "src/gpu/ganesh/image/GrImageUtils.h"
29 #include "src/utils/SkOSPath.h"
30 #include "tools/DeserialProcsUtils.h"
31 #include "tools/EncodeUtils.h"
32 #include "tools/SkSharingProc.h"
33 #include "tools/flags/CommandLineFlags.h"
34 #include "tools/flags/CommonFlags.h"
35 #include "tools/flags/CommonFlagsConfig.h"
36 #include "tools/flags/CommonFlagsGanesh.h"
37 #include "tools/fonts/FontToolUtils.h"
38 #include "tools/ganesh/DDLPromiseImageHelper.h"
39 #include "tools/ganesh/DDLTileHelper.h"
40 #include "tools/ganesh/GpuTimer.h"
41 #include "tools/ganesh/GrContextFactory.h"
42 #include "tools/gpu/FlushFinishTracker.h"
43
44 #if defined(SK_ENABLE_SVG)
45 #include "modules/skshaper/utils/FactoryHelpers.h"
46 #include "modules/svg/include/SkSVGDOM.h"
47 #include "src/xml/SkDOM.h"
48 #endif
49
50 #if defined(SK_CODEC_DECODES_PNG_WITH_RUST)
51 #include "include/codec/SkPngRustDecoder.h"
52 #else
53 #include "include/codec/SkPngDecoder.h"
54 #endif
55
56 #include <stdlib.h>
57 #include <algorithm>
58 #include <array>
59 #include <chrono>
60 #include <cinttypes>
61 #include <cmath>
62 #include <vector>
63
64 /**
65 * This is a minimalist program whose sole purpose is to open a .skp or .svg file, benchmark it on a
66 * single config, and exit. It is intended to be used through skpbench.py rather than invoked
67 * directly. Limiting the entire process to a single config/skp pair helps to keep the results
68 * repeatable.
69 *
70 * No tiling, looping, or other fanciness is used; it just draws the skp whole into a size-matched
71 * render target and syncs the GPU after each draw.
72 *
73 * Well, maybe a little fanciness, MSKP's can be loaded and played. The animation is played as many
74 * times as necessary to reach the target sample duration and FPS is reported.
75 *
76 * Currently, only GPU configs are supported.
77 */
78
79 static DEFINE_bool(ddl, false, "record the skp into DDLs before rendering");
80 static DEFINE_int(ddlNumRecordingThreads, 0, "number of DDL recording threads (0=num_cores)");
81 static DEFINE_int(ddlTilingWidthHeight, 0, "number of tiles along one edge when in DDL mode");
82
83 static DEFINE_bool(comparableDDL, false, "render in a way that is comparable to 'comparableSKP'");
84 static DEFINE_bool(comparableSKP, false, "report in a way that is comparable to 'comparableDDL'");
85
86 static DEFINE_int(duration, 5000, "number of milliseconds to run the benchmark");
87 static DEFINE_int(sampleMs, 50, "minimum duration of a sample");
88 static DEFINE_bool(gpuClock, false, "time on the gpu clock (gpu work only)");
89 static DEFINE_bool(fps, false, "use fps instead of ms");
90 static DEFINE_string(src, "",
91 "path to a single .skp or .svg file, or 'warmup' for a builtin warmup run");
92 static DEFINE_string(png, "", "if set, save a .png proof to disk at this file location");
93 static DEFINE_int(verbosity, 4, "level of verbosity (0=none to 5=debug)");
94 static DEFINE_bool(suppressHeader, false, "don't print a header row before the results");
95 static DEFINE_double(scale, 1, "Scale the size of the canvas and the zoom level by this factor.");
96 static DEFINE_bool(dumpSamples, false, "print the individual samples to stdout");
97
98 static const char header[] =
99 " accum median max min stddev samples sample_ms clock metric config bench";
100
101 static const char resultFormat[] =
102 "%8.4g %8.4g %8.4g %8.4g %6.3g%% %7zu %9i %-5s %-6s %-9s %s";
103
104 static constexpr int kNumFlushesToPrimeCache = 3;
105
106 struct Sample {
107 using duration = std::chrono::nanoseconds;
108
109 Sample() : fFrames(0), fDuration(0) {}
110 double seconds() const { return std::chrono::duration<double>(fDuration).count(); }
111 double ms() const { return std::chrono::duration<double, std::milli>(fDuration).count(); }
112 double value() const { return FLAGS_fps ? fFrames / this->seconds() : this->ms() / fFrames; }
113 static const char* metric() { return FLAGS_fps ? "fps" : "ms"; }
114
115 int fFrames;
116 duration fDuration;
117 };
118
119 class GpuSync {
120 public:
121 GpuSync() {}
122 ~GpuSync() {}
123
124 void waitIfNeeded();
125
126 sk_gpu_test::FlushFinishTracker* newFlushTracker(GrDirectContext* context);
127
128 private:
129 enum { kMaxFrameLag = 3 };
130 sk_sp<sk_gpu_test::FlushFinishTracker> fFinishTrackers[kMaxFrameLag - 1];
131 int fCurrentFlushIdx = 0;
132 };
133
134 enum class ExitErr {
135 kOk = 0,
136 kUsage = 64,
137 kData = 65,
138 kUnavailable = 69,
139 kIO = 74,
140 kSoftware = 70
141 };
142
143 static void flush_with_sync(GrDirectContext*, GpuSync&);
144 static void draw_skp_and_flush_with_sync(GrDirectContext*, SkSurface*, const SkPicture*, GpuSync&);
145 static sk_sp<SkPicture> create_warmup_skp();
146 static sk_sp<SkPicture> create_skp_from_svg(SkStream*, const char* filename);
147 static bool mkdir_p(const SkString& name);
148 static SkString join(const CommandLineFlags::StringArray&);
149 static void exitf(ExitErr, const char* format, ...);
150
151 // An interface used by both static SKPs and animated SKPs
152 class SkpProducer {
153 public:
154 virtual ~SkpProducer() {}
155 // Draw an SkPicture to the provided surface, flush the surface, and sync the GPU.
156 // You may use the static draw_skp_and_flush_with_sync declared above.
157 // returned int tells how many draw/flush/sync were done.
158 virtual int drawAndFlushAndSync(GrDirectContext*, SkSurface* surface, GpuSync& gpuSync) = 0;
159 };
160
161 class StaticSkp : public SkpProducer {
162 public:
163 StaticSkp(sk_sp<SkPicture> skp) : fSkp(skp) {}
164
165 int drawAndFlushAndSync(GrDirectContext* context,
166 SkSurface* surface,
167 GpuSync& gpuSync) override {
168 draw_skp_and_flush_with_sync(context, surface, fSkp.get(), gpuSync);
169 return 1;
170 }
171
172 private:
173 sk_sp<SkPicture> fSkp;
174 };
175
176 // A class for playing/benchmarking a multi frame SKP file.
177 // the recorded frames are looped over repeatedly.
178 // This type of benchmark may have a much higher std dev in frame times.
179 class MultiFrameSkp : public SkpProducer {
180 public:
181 MultiFrameSkp(const std::vector<SkDocumentPage>& frames) : fFrames(frames){}
182
183 static std::unique_ptr<MultiFrameSkp> MakeFromFile(const SkString& path) {
184 // Load the multi frame skp at the given filename.
185 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(path.c_str());
186 if (!stream) { return nullptr; }
187
188 // Attempt to deserialize with an image sharing serial proc.
189 auto deserialContext = std::make_unique<SkSharingDeserialContext>();
190 SkDeserialProcs procs;
191 procs.fImageProc = SkSharingDeserialContext::deserializeImage;
192 procs.fImageCtx = deserialContext.get();
193
194 // The outer format of multi-frame skps is the multi-picture document, which is a
195 // skp file containing subpictures separated by annotations.
196 int page_count = SkMultiPictureDocument::ReadPageCount(stream.get());
197 if (!page_count) {
198 return nullptr;
199 }
200 std::vector<SkDocumentPage> frames(page_count); // can't call reserve, why?
201 if (!SkMultiPictureDocument::Read(stream.get(), frames.data(), page_count, &procs)) {
202 return nullptr;
203 }
204
205 return std::make_unique<MultiFrameSkp>(frames);
206 }
207
208 // Draw the whole animation once.
209 int drawAndFlushAndSync(GrDirectContext* context,
210 SkSurface* surface,
211 GpuSync& gpuSync) override {
212 for (int i=0; i<this->count(); i++){
213 draw_skp_and_flush_with_sync(context, surface, this->frame(i).get(), gpuSync);
214 }
215 return this->count();
216 }
217 // Return the requested frame.
218 sk_sp<SkPicture> frame(int n) const { return fFrames[n].fPicture; }
219 // Return the number of frames in the recording.
220 int count() const { return fFrames.size(); }
221 private:
222 std::vector<SkDocumentPage> fFrames;
223 };
224
225 static void ddl_sample(GrDirectContext* dContext, DDLTileHelper* tiles, GpuSync& gpuSync,
226 Sample* sample, SkTaskGroup* recordingTaskGroup, SkTaskGroup* gpuTaskGroup,
227 std::chrono::high_resolution_clock::time_point* startStopTime,
228 SkPicture* picture) {
229 using clock = std::chrono::high_resolution_clock;
230
231 clock::time_point start = *startStopTime;
232
233 if (FLAGS_comparableDDL) {
234 SkASSERT(!FLAGS_comparableSKP);
235
236 // In this mode we simply alternate between creating a DDL and drawing it - all on one
237 // thread. The interleaving is so that we don't starve the GPU.
238 // One unfortunate side effect of this is that we can't delete the DDLs until after
239 // the GPU work is flushed.
240 tiles->interleaveDDLCreationAndDraw(dContext, picture);
241 } else if (FLAGS_comparableSKP) {
242 // In this mode simply draw the re-inflated per-tile SKPs directly to the GPU w/o going
243 // through a DDL.
244 tiles->drawAllTilesDirectly(dContext, picture);
245 } else {
246 tiles->kickOffThreadedWork(recordingTaskGroup, gpuTaskGroup, dContext, picture);
247 recordingTaskGroup->wait();
248 }
249
250 if (gpuTaskGroup) {
251 gpuTaskGroup->add([&]{
252 flush_with_sync(dContext, gpuSync);
253 });
254 gpuTaskGroup->wait();
255 } else {
256 flush_with_sync(dContext, gpuSync);
257 }
258
259 *startStopTime = clock::now();
260
261 if (sample) {
262 sample->fDuration += *startStopTime - start;
263 sample->fFrames++;
264 }
265 }
266
267 static void run_ddl_benchmark(sk_gpu_test::TestContext* testContext,
268 GrDirectContext* dContext,
269 sk_sp<SkSurface> dstSurface,
270 SkPicture* inputPicture,
271 std::vector<Sample>* samples) {
272 using clock = std::chrono::high_resolution_clock;
273 const Sample::duration sampleDuration = std::chrono::milliseconds(FLAGS_sampleMs);
274 const clock::duration benchDuration = std::chrono::milliseconds(FLAGS_duration);
275
276 GrSurfaceCharacterization dstCharacterization;
277 SkAssertResult(dstSurface->characterize(&dstCharacterization));
278
279 SkIRect viewport = dstSurface->imageInfo().bounds();
280
281 auto supportedYUVADataTypes = skgpu::ganesh::SupportedTextureFormats(*dContext);
282 DDLPromiseImageHelper promiseImageHelper(supportedYUVADataTypes);
283 sk_sp<SkPicture> newSKP = promiseImageHelper.recreateSKP(dContext, inputPicture);
284 if (!newSKP) {
285 exitf(ExitErr::kUnavailable, "DDL: conversion of skp failed");
286 }
287
288 promiseImageHelper.uploadAllToGPU(nullptr, dContext);
289
290 DDLTileHelper tiles(dContext, dstCharacterization, viewport,
291 FLAGS_ddlTilingWidthHeight, FLAGS_ddlTilingWidthHeight,
292 /* addRandomPaddingToDst */ false);
293
294 tiles.createBackendTextures(nullptr, dContext);
295
296 // In comparable modes, there is no GPU thread. The following pointers are all null.
297 // Otherwise, we transfer testContext onto the GPU thread until after the bench.
298 std::unique_ptr<SkExecutor> gpuThread;
299 std::unique_ptr<SkTaskGroup> gpuTaskGroup;
300 std::unique_ptr<SkExecutor> recordingThreadPool;
301 std::unique_ptr<SkTaskGroup> recordingTaskGroup;
302 if (!FLAGS_comparableDDL && !FLAGS_comparableSKP) {
303 gpuThread = SkExecutor::MakeFIFOThreadPool(1, false);
304 gpuTaskGroup = std::make_unique<SkTaskGroup>(*gpuThread);
305 recordingThreadPool = SkExecutor::MakeFIFOThreadPool(FLAGS_ddlNumRecordingThreads, false);
306 recordingTaskGroup = std::make_unique<SkTaskGroup>(*recordingThreadPool);
307 testContext->makeNotCurrent();
308 gpuTaskGroup->add([=]{ testContext->makeCurrent(); });
309 }
310
311 clock::time_point startStopTime = clock::now();
312
313 GpuSync gpuSync;
314 ddl_sample(dContext, &tiles, gpuSync, nullptr, recordingTaskGroup.get(),
315 gpuTaskGroup.get(), &startStopTime, newSKP.get());
316
317 clock::duration cumulativeDuration = std::chrono::milliseconds(0);
318
319 do {
320 samples->emplace_back();
321 Sample& sample = samples->back();
322
323 do {
324 tiles.resetAllTiles();
325 ddl_sample(dContext, &tiles, gpuSync, &sample, recordingTaskGroup.get(),
326 gpuTaskGroup.get(), &startStopTime, newSKP.get());
327 } while (sample.fDuration < sampleDuration);
328
329 cumulativeDuration += sample.fDuration;
330 } while (cumulativeDuration < benchDuration || 0 == samples->size() % 2);
331
332 // Move the context back to this thread now that we're done benching.
333 if (gpuTaskGroup) {
334 gpuTaskGroup->add([=]{
335 testContext->makeNotCurrent();
336 });
337 gpuTaskGroup->wait();
338 testContext->makeCurrent();
339 }
340
341 if (!FLAGS_png.isEmpty()) {
342 // The user wants to see the final result
343 skgpu::ganesh::DrawDDL(dstSurface, tiles.composeDDL());
344 dContext->flushAndSubmit(dstSurface.get(), GrSyncCpu::kNo);
345 }
346
347 tiles.resetAllTiles();
348
349 // Make sure the gpu has finished all its work before we exit this function and delete the
350 // fence.
351 dContext->flush();
352 dContext->submit(GrSyncCpu::kYes);
353
354 promiseImageHelper.deleteAllFromGPU(nullptr, dContext);
355
356 tiles.deleteBackendTextures(nullptr, dContext);
357 }
358
359 static void run_benchmark(GrDirectContext* context,
360 sk_sp<SkSurface> surface,
361 SkpProducer* skpp,
362 std::vector<Sample>* samples) {
363 using clock = std::chrono::high_resolution_clock;
364 const Sample::duration sampleDuration = std::chrono::milliseconds(FLAGS_sampleMs);
365 const clock::duration benchDuration = std::chrono::milliseconds(FLAGS_duration);
366
367 GpuSync gpuSync;
368 int i = 0;
369 do {
370 i += skpp->drawAndFlushAndSync(context, surface.get(), gpuSync);
371 } while(i < kNumFlushesToPrimeCache);
372
373 clock::time_point now = clock::now();
374 const clock::time_point endTime = now + benchDuration;
375
376 do {
377 clock::time_point sampleStart = now;
378 samples->emplace_back();
379 Sample& sample = samples->back();
380
381 do {
382 sample.fFrames += skpp->drawAndFlushAndSync(context, surface.get(), gpuSync);
383 now = clock::now();
384 sample.fDuration = now - sampleStart;
385 } while (sample.fDuration < sampleDuration);
386 } while (now < endTime || 0 == samples->size() % 2);
387
388 // Make sure the gpu has finished all its work before we exit this function and delete the
389 // fence.
390 context->flush(surface.get());
391 context->submit(GrSyncCpu::kYes);
392 }
393
394 static void run_gpu_time_benchmark(sk_gpu_test::GpuTimer* gpuTimer,
395 GrDirectContext* context,
396 sk_sp<SkSurface> surface,
397 const SkPicture* skp,
398 std::vector<Sample>* samples) {
399 using sk_gpu_test::PlatformTimerQuery;
400 using clock = std::chrono::steady_clock;
401 const clock::duration sampleDuration = std::chrono::milliseconds(FLAGS_sampleMs);
402 const clock::duration benchDuration = std::chrono::milliseconds(FLAGS_duration);
403
404 if (!gpuTimer->disjointSupport()) {
405 fprintf(stderr, "WARNING: GPU timer cannot detect disjoint operations; "
406 "results may be unreliable\n");
407 }
408
409 GpuSync gpuSync;
410 draw_skp_and_flush_with_sync(context, surface.get(), skp, gpuSync);
411
412 PlatformTimerQuery previousTime = 0;
413 for (int i = 1; i < kNumFlushesToPrimeCache; ++i) {
414 gpuTimer->queueStart();
415 draw_skp_and_flush_with_sync(context, surface.get(), skp, gpuSync);
416 previousTime = gpuTimer->queueStop();
417 }
418
419 clock::time_point now = clock::now();
420 const clock::time_point endTime = now + benchDuration;
421
422 do {
423 const clock::time_point sampleEndTime = now + sampleDuration;
424 samples->emplace_back();
425 Sample& sample = samples->back();
426
427 do {
428 gpuTimer->queueStart();
429 draw_skp_and_flush_with_sync(context, surface.get(), skp, gpuSync);
430 PlatformTimerQuery time = gpuTimer->queueStop();
431
432 switch (gpuTimer->checkQueryStatus(previousTime)) {
433 using QueryStatus = sk_gpu_test::GpuTimer::QueryStatus;
434 case QueryStatus::kInvalid:
435 exitf(ExitErr::kUnavailable, "GPU timer failed");
436 break;
437 case QueryStatus::kPending:
438 exitf(ExitErr::kUnavailable, "timer query still not ready after fence sync");
439 break;
440 case QueryStatus::kDisjoint:
441 if (FLAGS_verbosity >= 4) {
442 fprintf(stderr, "discarding timer query due to disjoint operations.\n");
443 }
444 break;
445 case QueryStatus::kAccurate:
446 sample.fDuration += gpuTimer->getTimeElapsed(previousTime);
447 ++sample.fFrames;
448 break;
449 }
450 gpuTimer->deleteQuery(previousTime);
451 previousTime = time;
452 now = clock::now();
453 } while (now < sampleEndTime || 0 == sample.fFrames);
454 } while (now < endTime || 0 == samples->size() % 2);
455
456 gpuTimer->deleteQuery(previousTime);
457
458 // Make sure the gpu has finished all its work before we exit this function and delete the
459 // fence.
460 context->flush(surface.get());
461 context->submit(GrSyncCpu::kYes);
462 }
463
464 void print_result(const std::vector<Sample>& samples, const char* config, const char* bench) {
465 if (0 == (samples.size() % 2)) {
466 exitf(ExitErr::kSoftware, "attempted to gather stats on even number of samples");
467 }
468
469 if (FLAGS_dumpSamples) {
470 printf("Samples: ");
471 for (const Sample& sample : samples) {
472 printf("%" PRId64 " ", static_cast<int64_t>(sample.fDuration.count()));
473 }
474 printf("%s\n", bench);
475 }
476
477 Sample accum = Sample();
478 std::vector<double> values;
479 values.reserve(samples.size());
480 for (const Sample& sample : samples) {
481 accum.fFrames += sample.fFrames;
482 accum.fDuration += sample.fDuration;
483 values.push_back(sample.value());
484 }
485 std::sort(values.begin(), values.end());
486
487 const double accumValue = accum.value();
488 double variance = 0;
489 for (double value : values) {
490 const double delta = value - accumValue;
491 variance += delta * delta;
492 }
493 variance /= values.size();
494 // Technically, this is the relative standard deviation.
495 const double stddev = 100/*%*/ * sqrt(variance) / accumValue;
496
497 printf(resultFormat, accumValue, values[values.size() / 2], values.back(), values.front(),
498 stddev, values.size(), FLAGS_sampleMs, FLAGS_gpuClock ? "gpu" : "cpu", Sample::metric(),
499 config, bench);
500 printf("\n");
501 fflush(stdout);
502 }
503
504 int main(int argc, char** argv) {
505 CommandLineFlags::SetUsage(
506 "Use skpbench.py instead. "
507 "You usually don't want to use this program directly.");
508 CommandLineFlags::Parse(argc, argv);
509
510 if (!FLAGS_suppressHeader) {
511 printf("%s\n", header);
512 }
513 if (FLAGS_duration <= 0) {
514 exit(0); // This can be used to print the header and quit.
515 }
516
517 // Parse the config.
518 const SkCommandLineConfigGpu* config = nullptr; // Initialize for spurious warning.
519 SkCommandLineConfigArray configs;
520 ParseConfigs(FLAGS_config, &configs);
521 if (configs.size() != 1 || !(config = configs[0]->asConfigGpu())) {
522 exitf(ExitErr::kUsage, "invalid config '%s': must specify one (and only one) GPU config",
523 join(FLAGS_config).c_str());
524 }
525
526 // Parse the skp.
527 if (FLAGS_src.size() != 1) {
528 exitf(ExitErr::kUsage,
529 "invalid input '%s': must specify a single .skp or .svg file, or 'warmup'",
530 join(FLAGS_src).c_str());
531 }
532
533 SkGraphics::Init();
534 #if defined(SK_CODEC_DECODES_PNG_WITH_RUST)
535 SkCodecs::Register(SkPngRustDecoder::Decoder());
536 #else
537 SkCodecs::Register(SkPngDecoder::Decoder());
538 #endif
539 SkCodecs::Register(SkJpegDecoder::Decoder());
540
541 sk_sp<SkPicture> skp;
542 std::unique_ptr<MultiFrameSkp> mskp; // populated if the file is multi frame.
543 SkString srcname;
544 if (0 == strcmp(FLAGS_src[0], "warmup")) {
545 skp = create_warmup_skp();
546 srcname = "warmup";
547 } else {
548 SkString srcfile(FLAGS_src[0]);
549 std::unique_ptr<SkStream> srcstream(SkStream::MakeFromFile(srcfile.c_str()));
550 if (!srcstream) {
551 exitf(ExitErr::kIO, "failed to open file %s", srcfile.c_str());
552 }
553 if (srcfile.endsWith(".svg")) {
554 skp = create_skp_from_svg(srcstream.get(), srcfile.c_str());
555 } else if (srcfile.endsWith(".mskp")) {
556 mskp = MultiFrameSkp::MakeFromFile(srcfile);
557 // populate skp with it's first frame, for width height determination.
558 skp = mskp->frame(0);
559 } else {
560 SkDeserialProcs procs = ToolUtils::get_default_skp_deserial_procs();
561 skp = SkPicture::MakeFromStream(srcstream.get(), &procs);
562 }
563 if (!skp) {
564 exitf(ExitErr::kData, "failed to parse file %s", srcfile.c_str());
565 }
566 srcname = SkOSPath::Basename(srcfile.c_str());
567 }
568 int width = std::min(SkScalarCeilToInt(skp->cullRect().width()), 2048),
569 height = std::min(SkScalarCeilToInt(skp->cullRect().height()), 2048);
570 if (FLAGS_verbosity >= 3 &&
571 (width != skp->cullRect().width() || height != skp->cullRect().height())) {
572 fprintf(stderr, "%s is too large (%ix%i), cropping to %ix%i.\n",
573 srcname.c_str(), SkScalarCeilToInt(skp->cullRect().width()),
574 SkScalarCeilToInt(skp->cullRect().height()), width, height);
575 }
576 if (FLAGS_scale != 1) {
577 width *= FLAGS_scale;
578 height *= FLAGS_scale;
579 if (FLAGS_verbosity >= 3) {
580 fprintf(stderr, "Scale factor of %.2f: scaling to %ix%i.\n",
581 FLAGS_scale, width, height);
582 }
583 }
584
585 if (config->getSurfType() != SkCommandLineConfigGpu::SurfType::kDefault) {
586 exitf(ExitErr::kUnavailable, "This tool only supports the default surface type. (%s)",
587 config->getTag().c_str());
588 }
589
590 // Create a context.
591 GrContextOptions ctxOptions;
592 CommonFlags::SetCtxOptions(&ctxOptions);
593 sk_gpu_test::GrContextFactory factory(ctxOptions);
594 sk_gpu_test::ContextInfo ctxInfo =
595 factory.getContextInfo(config->getContextType(), config->getContextOverrides());
596 auto ctx = ctxInfo.directContext();
597 if (!ctx) {
598 exitf(ExitErr::kUnavailable, "failed to create context for config %s",
599 config->getTag().c_str());
600 }
601 if (ctx->maxRenderTargetSize() < std::max(width, height)) {
602 exitf(ExitErr::kUnavailable, "render target size %ix%i not supported by platform (max: %i)",
603 width, height, ctx->maxRenderTargetSize());
604 }
605 GrBackendFormat format = ctx->defaultBackendFormat(config->getColorType(), GrRenderable::kYes);
606 if (!format.isValid()) {
607 exitf(ExitErr::kUnavailable, "failed to get GrBackendFormat from SkColorType: %d",
608 config->getColorType());
609 }
610 int supportedSampleCount = ctx->priv().caps()->getRenderTargetSampleCount(
611 config->getSamples(), format);
612 if (supportedSampleCount != config->getSamples()) {
613 exitf(ExitErr::kUnavailable, "sample count %i not supported by platform",
614 config->getSamples());
615 }
616 sk_gpu_test::TestContext* testCtx = ctxInfo.testContext();
617 if (!testCtx) {
618 exitf(ExitErr::kSoftware, "testContext is null");
619 }
620 if (!testCtx->fenceSyncSupport()) {
621 exitf(ExitErr::kUnavailable, "GPU does not support fence sync");
622 }
623
624 // Create a render target.
625 SkImageInfo info = SkImageInfo::Make(
626 width, height, config->getColorType(), config->getAlphaType(), config->refColorSpace());
627 SkSurfaceProps props(config->getSurfaceFlags(), kRGB_H_SkPixelGeometry);
628 sk_sp<SkSurface> surface =
629 SkSurfaces::RenderTarget(ctx, skgpu::Budgeted::kNo, info, config->getSamples(), &props);
630 if (!surface) {
631 exitf(ExitErr::kUnavailable, "failed to create %ix%i render target for config %s",
632 width, height, config->getTag().c_str());
633 }
634
635 // Run the benchmark.
636 std::vector<Sample> samples;
637 if (FLAGS_sampleMs > 0) {
638 // +1 because we might take one more sample in order to have an odd number.
639 samples.reserve(1 + (FLAGS_duration + FLAGS_sampleMs - 1) / FLAGS_sampleMs);
640 } else {
641 samples.reserve(2 * FLAGS_duration);
642 }
643 SkCanvas* canvas = surface->getCanvas();
644 canvas->translate(-skp->cullRect().x(), -skp->cullRect().y());
645 if (FLAGS_scale != 1) {
646 canvas->scale(FLAGS_scale, FLAGS_scale);
647 }
648 if (!FLAGS_gpuClock) {
649 if (FLAGS_ddl) {
650 run_ddl_benchmark(testCtx, ctx, surface, skp.get(), &samples);
651 } else if (!mskp) {
652 auto s = std::make_unique<StaticSkp>(skp);
653 run_benchmark(ctx, surface, s.get(), &samples);
654 } else {
655 run_benchmark(ctx, surface, mskp.get(), &samples);
656 }
657 } else {
658 if (FLAGS_ddl) {
659 exitf(ExitErr::kUnavailable, "DDL: GPU-only timing not supported");
660 }
661 if (!testCtx->gpuTimingSupport()) {
662 exitf(ExitErr::kUnavailable, "GPU does not support timing");
663 }
664 run_gpu_time_benchmark(testCtx->gpuTimer(), ctx, surface, skp.get(), &samples);
665 }
666 print_result(samples, config->getTag().c_str(), srcname.c_str());
667
668 // Save a proof (if one was requested).
669 if (!FLAGS_png.isEmpty()) {
670 SkBitmap bmp;
671 bmp.allocPixels(info);
672 if (!surface->getCanvas()->readPixels(bmp, 0, 0)) {
673 exitf(ExitErr::kUnavailable, "failed to read canvas pixels for png");
674 }
675 if (!mkdir_p(SkOSPath::Dirname(FLAGS_png[0]))) {
676 exitf(ExitErr::kIO, "failed to create directory for png \"%s\"", FLAGS_png[0]);
677 }
678 if (!ToolUtils::EncodeImageToPngFile(FLAGS_png[0], bmp)) {
679 exitf(ExitErr::kIO, "failed to save png to \"%s\"", FLAGS_png[0]);
680 }
681 }
682
683 return(0);
684 }
685
686 static void flush_with_sync(GrDirectContext* context, GpuSync& gpuSync) {
687 gpuSync.waitIfNeeded();
688
689 GrFlushInfo flushInfo;
690 flushInfo.fFinishedProc = sk_gpu_test::FlushFinishTracker::FlushFinished;
691 flushInfo.fFinishedContext = gpuSync.newFlushTracker(context);
692
693 context->flush(flushInfo);
694 context->submit();
695 }
696
697 static void draw_skp_and_flush_with_sync(GrDirectContext* context, SkSurface* surface,
698 const SkPicture* skp, GpuSync& gpuSync) {
699 auto canvas = surface->getCanvas();
700 canvas->drawPicture(skp);
701
702 flush_with_sync(context, gpuSync);
703 }
704
705 static sk_sp<SkPicture> create_warmup_skp() {
706 static constexpr SkRect bounds{0, 0, 500, 500};
707 SkPictureRecorder recorder;
708 SkCanvas* recording = recorder.beginRecording(bounds);
709
710 recording->clear(SK_ColorWHITE);
711
712 SkPaint stroke;
713 stroke.setStyle(SkPaint::kStroke_Style);
714 stroke.setStrokeWidth(2);
715
716 // Use a big path to (theoretically) warmup the CPU.
717 SkPath bigPath = BenchUtils::make_big_path();
718 recording->drawPath(bigPath, stroke);
719
720 // Use a perlin shader to warmup the GPU.
721 SkPaint perlin;
722 perlin.setShader(SkShaders::MakeTurbulence(0.1f, 0.1f, 1, 0, nullptr));
723 recording->drawRect(bounds, perlin);
724
725 return recorder.finishRecordingAsPicture();
726 }
727
728 static sk_sp<SkPicture> create_skp_from_svg(SkStream* stream, const char* filename) {
729 #if defined(SK_ENABLE_SVG)
730 sk_sp<SkSVGDOM> svg = SkSVGDOM::Builder()
731 .setFontManager(ToolUtils::TestFontMgr())
732 .setTextShapingFactory(SkShapers::BestAvailable())
733 .make(*stream);
734 if (!svg) {
735 exitf(ExitErr::kData, "failed to build svg dom from file %s", filename);
736 }
737
738 static constexpr SkRect bounds{0, 0, 1200, 1200};
739 SkPictureRecorder recorder;
740 SkCanvas* recording = recorder.beginRecording(bounds);
741
742 svg->setContainerSize(SkSize::Make(recording->getBaseLayerSize()));
743 svg->render(recording);
744
745 return recorder.finishRecordingAsPicture();
746 #endif
747 exitf(ExitErr::kData, "SK_ENABLE_SVG is disabled; cannot open svg file %s", filename);
748 return nullptr;
749 }
750
751 bool mkdir_p(const SkString& dirname) {
752 if (dirname.isEmpty() || dirname == SkString("/")) {
753 return true;
754 }
755 return mkdir_p(SkOSPath::Dirname(dirname.c_str())) && sk_mkdir(dirname.c_str());
756 }
757
758 static SkString join(const CommandLineFlags::StringArray& stringArray) {
759 SkString joined;
760 for (int i = 0; i < stringArray.size(); ++i) {
761 joined.appendf(i ? " %s" : "%s", stringArray[i]);
762 }
763 return joined;
764 }
765
766 static void exitf(ExitErr err, const char* format, ...) SK_PRINTF_LIKE(2, 3);
767
768 static void exitf(ExitErr err, const char* format, ...) {
769 fprintf(stderr, ExitErr::kSoftware == err ? "INTERNAL ERROR: " : "ERROR: ");
770 va_list args;
771 va_start(args, format);
772 vfprintf(stderr, format, args);
773 va_end(args);
774 fprintf(stderr, ExitErr::kSoftware == err ? "; this should never happen.\n": ".\n");
775 exit((int)err);
776 }
777
778 void GpuSync::waitIfNeeded() {
779 if (fFinishTrackers[fCurrentFlushIdx]) {
780 fFinishTrackers[fCurrentFlushIdx]->waitTillFinished();
781 }
782 }
783
784 sk_gpu_test::FlushFinishTracker* GpuSync::newFlushTracker(GrDirectContext* context) {
785 fFinishTrackers[fCurrentFlushIdx].reset(new sk_gpu_test::FlushFinishTracker(context));
786
787 sk_gpu_test::FlushFinishTracker* tracker = fFinishTrackers[fCurrentFlushIdx].get();
788 // We add an additional ref to the current flush tracker here. This ref is owned by the finish
789 // callback on the flush call. The finish callback will unref the tracker when called.
790 tracker->ref();
791
792 fCurrentFlushIdx = (fCurrentFlushIdx + 1) % std::size(fFinishTrackers);
793 return tracker;
794 }