• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "DDLPromiseImageHelper.h"
9 #include "DDLTileHelper.h"
10 #include "GpuTimer.h"
11 #include "GrCaps.h"
12 #include "GrContextFactory.h"
13 #include "GrContextPriv.h"
14 #include "SkCanvas.h"
15 #include "SkCommonFlags.h"
16 #include "SkCommonFlagsGpu.h"
17 #include "SkDeferredDisplayList.h"
18 #include "SkGraphics.h"
19 #include "SkGr.h"
20 #include "SkOSFile.h"
21 #include "SkOSPath.h"
22 #include "SkPerlinNoiseShader.h"
23 #include "SkPicture.h"
24 #include "SkPictureRecorder.h"
25 #include "SkStream.h"
26 #include "SkSurface.h"
27 #include "SkSurfaceProps.h"
28 #include "SkTaskGroup.h"
29 #include "flags/SkCommandLineFlags.h"
30 #include "flags/SkCommonFlagsConfig.h"
31 #include "sk_tool_utils.h"
32 
33 #ifdef SK_XML
34 #include "SkDOM.h"
35 #include "../experimental/svg/model/SkSVGDOM.h"
36 #endif
37 
38 #include <stdlib.h>
39 #include <algorithm>
40 #include <array>
41 #include <chrono>
42 #include <cmath>
43 #include <vector>
44 
45 /**
46  * This is a minimalist program whose sole purpose is to open a .skp or .svg file, benchmark it on a
47  * single config, and exit. It is intended to be used through skpbench.py rather than invoked
48  * directly. Limiting the entire process to a single config/skp pair helps to keep the results
49  * repeatable.
50  *
51  * No tiling, looping, or other fanciness is used; it just draws the skp whole into a size-matched
52  * render target and syncs the GPU after each draw.
53  *
54  * Currently, only GPU configs are supported.
55  */
56 
57 DEFINE_bool(ddl, false, "record the skp into DDLs before rendering");
58 DEFINE_int32(ddlNumAdditionalThreads, 0, "number of DDL recording threads in addition to main one");
59 DEFINE_int32(ddlTilingWidthHeight, 0, "number of tiles along one edge when in DDL mode");
60 DEFINE_bool(ddlRecordTime, false, "report just the cpu time spent recording DDLs");
61 
62 DEFINE_int32(duration, 5000, "number of milliseconds to run the benchmark");
63 DEFINE_int32(sampleMs, 50, "minimum duration of a sample");
64 DEFINE_bool(gpuClock, false, "time on the gpu clock (gpu work only)");
65 DEFINE_bool(fps, false, "use fps instead of ms");
66 DEFINE_string(src, "", "path to a single .skp or .svg file, or 'warmup' for a builtin warmup run");
67 DEFINE_string(png, "", "if set, save a .png proof to disk at this file location");
68 DEFINE_int32(verbosity, 4, "level of verbosity (0=none to 5=debug)");
69 DEFINE_bool(suppressHeader, false, "don't print a header row before the results");
70 
71 static const char* header =
72 "   accum    median       max       min   stddev  samples  sample_ms  clock  metric  config    bench";
73 
74 static const char* resultFormat =
75 "%8.4g  %8.4g  %8.4g  %8.4g  %6.3g%%  %7li  %9i  %-5s  %-6s  %-9s %s";
76 
77 static constexpr int kNumFlushesToPrimeCache = 3;
78 
79 struct Sample {
80     using duration = std::chrono::nanoseconds;
81 
SampleSample82     Sample() : fFrames(0), fDuration(0) {}
secondsSample83     double seconds() const { return std::chrono::duration<double>(fDuration).count(); }
msSample84     double ms() const { return std::chrono::duration<double, std::milli>(fDuration).count(); }
valueSample85     double value() const { return FLAGS_fps ? fFrames / this->seconds() : this->ms() / fFrames; }
metricSample86     static const char* metric() { return FLAGS_fps ? "fps" : "ms"; }
87 
88     int        fFrames;
89     duration   fDuration;
90 };
91 
92 class GpuSync {
93 public:
94     GpuSync(const sk_gpu_test::FenceSync* fenceSync);
95     ~GpuSync();
96 
97     void syncToPreviousFrame();
98 
99 private:
100     void updateFence();
101 
102     const sk_gpu_test::FenceSync* const   fFenceSync;
103     sk_gpu_test::PlatformFence            fFence;
104 };
105 
106 enum class ExitErr {
107     kOk           = 0,
108     kUsage        = 64,
109     kData         = 65,
110     kUnavailable  = 69,
111     kIO           = 74,
112     kSoftware     = 70
113 };
114 
115 static void draw_skp_and_flush(SkSurface*, const SkPicture*);
116 static sk_sp<SkPicture> create_warmup_skp();
117 static sk_sp<SkPicture> create_skp_from_svg(SkStream*, const char* filename);
118 static bool mkdir_p(const SkString& name);
119 static SkString join(const SkCommandLineFlags::StringArray&);
120 static void exitf(ExitErr, const char* format, ...);
121 
ddl_sample(GrContext * context,DDLTileHelper * tiles,GpuSync * gpuSync,Sample * sample,std::chrono::high_resolution_clock::time_point * startStopTime)122 static void ddl_sample(GrContext* context, DDLTileHelper* tiles, GpuSync* gpuSync, Sample* sample,
123                        std::chrono::high_resolution_clock::time_point* startStopTime) {
124     using clock = std::chrono::high_resolution_clock;
125 
126     clock::time_point start = *startStopTime;
127 
128     tiles->createDDLsInParallel();
129 
130     if (!FLAGS_ddlRecordTime) {
131         tiles->drawAllTilesAndFlush(context, true);
132         if (gpuSync) {
133             gpuSync->syncToPreviousFrame();
134         }
135     }
136 
137     *startStopTime = clock::now();
138 
139     tiles->resetAllTiles();
140 
141     if (sample) {
142         SkASSERT(gpuSync);
143         sample->fDuration += *startStopTime - start;
144         sample->fFrames++;
145     }
146 }
147 
run_ddl_benchmark(const sk_gpu_test::FenceSync * fenceSync,GrContext * context,SkCanvas * finalCanvas,SkPicture * inputPicture,std::vector<Sample> * samples)148 static void run_ddl_benchmark(const sk_gpu_test::FenceSync* fenceSync,
149                               GrContext* context, SkCanvas* finalCanvas,
150                               SkPicture* inputPicture, std::vector<Sample>* samples) {
151     using clock = std::chrono::high_resolution_clock;
152     const Sample::duration sampleDuration = std::chrono::milliseconds(FLAGS_sampleMs);
153     const clock::duration benchDuration = std::chrono::milliseconds(FLAGS_duration);
154 
155     SkIRect viewport = finalCanvas->imageInfo().bounds();
156 
157     DDLPromiseImageHelper promiseImageHelper;
158     sk_sp<SkData> compressedPictureData = promiseImageHelper.deflateSKP(inputPicture);
159     if (!compressedPictureData) {
160         exitf(ExitErr::kUnavailable, "DDL: conversion of skp failed");
161     }
162 
163     promiseImageHelper.uploadAllToGPU(context);
164 
165     DDLTileHelper tiles(finalCanvas, viewport, FLAGS_ddlTilingWidthHeight);
166 
167     tiles.createSKPPerTile(compressedPictureData.get(), promiseImageHelper);
168 
169     SkTaskGroup::Enabler enabled(FLAGS_ddlNumAdditionalThreads);
170 
171     clock::time_point startStopTime = clock::now();
172 
173     ddl_sample(context, &tiles, nullptr, nullptr, &startStopTime);
174     GpuSync gpuSync(fenceSync);
175     ddl_sample(context, &tiles, &gpuSync, nullptr, &startStopTime);
176 
177     clock::duration cumulativeDuration = std::chrono::milliseconds(0);
178 
179     do {
180         samples->emplace_back();
181         Sample& sample = samples->back();
182 
183         do {
184             ddl_sample(context, &tiles, &gpuSync, &sample, &startStopTime);
185         } while (sample.fDuration < sampleDuration);
186 
187         cumulativeDuration += sample.fDuration;
188     } while (cumulativeDuration < benchDuration || 0 == samples->size() % 2);
189 
190     if (!FLAGS_png.isEmpty()) {
191         // The user wants to see the final result
192         tiles.composeAllTiles(finalCanvas);
193     }
194 }
195 
run_benchmark(const sk_gpu_test::FenceSync * fenceSync,SkSurface * surface,const SkPicture * skp,std::vector<Sample> * samples)196 static void run_benchmark(const sk_gpu_test::FenceSync* fenceSync, SkSurface* surface,
197                           const SkPicture* skp, std::vector<Sample>* samples) {
198     using clock = std::chrono::high_resolution_clock;
199     const Sample::duration sampleDuration = std::chrono::milliseconds(FLAGS_sampleMs);
200     const clock::duration benchDuration = std::chrono::milliseconds(FLAGS_duration);
201 
202     draw_skp_and_flush(surface, skp); // draw 1
203     GpuSync gpuSync(fenceSync);
204 
205     for (int i = 1; i < kNumFlushesToPrimeCache; ++i) {
206         draw_skp_and_flush(surface, skp); // draw N
207         // Waits for draw N-1 to finish (after draw N's cpu work is done).
208         gpuSync.syncToPreviousFrame();
209     }
210 
211     clock::time_point now = clock::now();
212     const clock::time_point endTime = now + benchDuration;
213 
214     do {
215         clock::time_point sampleStart = now;
216         samples->emplace_back();
217         Sample& sample = samples->back();
218 
219         do {
220             draw_skp_and_flush(surface, skp);
221             gpuSync.syncToPreviousFrame();
222 
223             now = clock::now();
224             sample.fDuration = now - sampleStart;
225             ++sample.fFrames;
226         } while (sample.fDuration < sampleDuration);
227     } while (now < endTime || 0 == samples->size() % 2);
228 }
229 
run_gpu_time_benchmark(sk_gpu_test::GpuTimer * gpuTimer,const sk_gpu_test::FenceSync * fenceSync,SkSurface * surface,const SkPicture * skp,std::vector<Sample> * samples)230 static void run_gpu_time_benchmark(sk_gpu_test::GpuTimer* gpuTimer,
231                                    const sk_gpu_test::FenceSync* fenceSync, SkSurface* surface,
232                                    const SkPicture* skp, std::vector<Sample>* samples) {
233     using sk_gpu_test::PlatformTimerQuery;
234     using clock = std::chrono::steady_clock;
235     const clock::duration sampleDuration = std::chrono::milliseconds(FLAGS_sampleMs);
236     const clock::duration benchDuration = std::chrono::milliseconds(FLAGS_duration);
237 
238     if (!gpuTimer->disjointSupport()) {
239         fprintf(stderr, "WARNING: GPU timer cannot detect disjoint operations; "
240                         "results may be unreliable\n");
241     }
242 
243     draw_skp_and_flush(surface, skp);
244     GpuSync gpuSync(fenceSync);
245 
246     PlatformTimerQuery previousTime = 0;
247     for (int i = 1; i < kNumFlushesToPrimeCache; ++i) {
248         gpuTimer->queueStart();
249         draw_skp_and_flush(surface, skp);
250         previousTime = gpuTimer->queueStop();
251         gpuSync.syncToPreviousFrame();
252     }
253 
254     clock::time_point now = clock::now();
255     const clock::time_point endTime = now + benchDuration;
256 
257     do {
258         const clock::time_point sampleEndTime = now + sampleDuration;
259         samples->emplace_back();
260         Sample& sample = samples->back();
261 
262         do {
263             gpuTimer->queueStart();
264             draw_skp_and_flush(surface, skp);
265             PlatformTimerQuery time = gpuTimer->queueStop();
266             gpuSync.syncToPreviousFrame();
267 
268             switch (gpuTimer->checkQueryStatus(previousTime)) {
269                 using QueryStatus = sk_gpu_test::GpuTimer::QueryStatus;
270                 case QueryStatus::kInvalid:
271                     exitf(ExitErr::kUnavailable, "GPU timer failed");
272                 case QueryStatus::kPending:
273                     exitf(ExitErr::kUnavailable, "timer query still not ready after fence sync");
274                 case QueryStatus::kDisjoint:
275                     if (FLAGS_verbosity >= 4) {
276                         fprintf(stderr, "discarding timer query due to disjoint operations.\n");
277                     }
278                     break;
279                 case QueryStatus::kAccurate:
280                     sample.fDuration += gpuTimer->getTimeElapsed(previousTime);
281                     ++sample.fFrames;
282                     break;
283             }
284             gpuTimer->deleteQuery(previousTime);
285             previousTime = time;
286             now = clock::now();
287         } while (now < sampleEndTime || 0 == sample.fFrames);
288     } while (now < endTime || 0 == samples->size() % 2);
289 
290     gpuTimer->deleteQuery(previousTime);
291 }
292 
print_result(const std::vector<Sample> & samples,const char * config,const char * bench)293 void print_result(const std::vector<Sample>& samples, const char* config, const char* bench)  {
294     if (0 == (samples.size() % 2)) {
295         exitf(ExitErr::kSoftware, "attempted to gather stats on even number of samples");
296     }
297 
298     Sample accum = Sample();
299     std::vector<double> values;
300     values.reserve(samples.size());
301     for (const Sample& sample : samples) {
302         accum.fFrames += sample.fFrames;
303         accum.fDuration += sample.fDuration;
304         values.push_back(sample.value());
305     }
306     std::sort(values.begin(), values.end());
307 
308     const double accumValue = accum.value();
309     double variance = 0;
310     for (double value : values) {
311         const double delta = value - accumValue;
312         variance += delta * delta;
313     }
314     variance /= values.size();
315     // Technically, this is the relative standard deviation.
316     const double stddev = 100/*%*/ * sqrt(variance) / accumValue;
317 
318     printf(resultFormat, accumValue, values[values.size() / 2], values.back(), values.front(),
319            stddev, values.size(), FLAGS_sampleMs, FLAGS_gpuClock ? "gpu" : "cpu", Sample::metric(),
320            config, bench);
321     printf("\n");
322     fflush(stdout);
323 }
324 
main(int argc,char ** argv)325 int main(int argc, char** argv) {
326     SkCommandLineFlags::SetUsage("Use skpbench.py instead. "
327                                  "You usually don't want to use this program directly.");
328     SkCommandLineFlags::Parse(argc, argv);
329 
330     if (!FLAGS_suppressHeader) {
331         printf("%s\n", header);
332     }
333     if (FLAGS_duration <= 0) {
334         exit(0); // This can be used to print the header and quit.
335     }
336 
337     // Parse the config.
338     const SkCommandLineConfigGpu* config = nullptr; // Initialize for spurious warning.
339     SkCommandLineConfigArray configs;
340     ParseConfigs(FLAGS_config, &configs);
341     if (configs.count() != 1 || !(config = configs[0]->asConfigGpu())) {
342         exitf(ExitErr::kUsage, "invalid config '%s': must specify one (and only one) GPU config",
343                                join(FLAGS_config).c_str());
344     }
345 
346     // Parse the skp.
347     if (FLAGS_src.count() != 1) {
348         exitf(ExitErr::kUsage,
349               "invalid input '%s': must specify a single .skp or .svg file, or 'warmup'",
350               join(FLAGS_src).c_str());
351     }
352 
353     SkGraphics::Init();
354 
355     sk_sp<SkPicture> skp;
356     SkString srcname;
357     if (0 == strcmp(FLAGS_src[0], "warmup")) {
358         skp = create_warmup_skp();
359         srcname = "warmup";
360     } else {
361         SkString srcfile(FLAGS_src[0]);
362         std::unique_ptr<SkStream> srcstream(SkStream::MakeFromFile(srcfile.c_str()));
363         if (!srcstream) {
364             exitf(ExitErr::kIO, "failed to open file %s", srcfile.c_str());
365         }
366         if (srcfile.endsWith(".svg")) {
367             skp = create_skp_from_svg(srcstream.get(), srcfile.c_str());
368         } else {
369             skp = SkPicture::MakeFromStream(srcstream.get());
370         }
371         if (!skp) {
372             exitf(ExitErr::kData, "failed to parse file %s", srcfile.c_str());
373         }
374         srcname = SkOSPath::Basename(srcfile.c_str());
375     }
376     int width = SkTMin(SkScalarCeilToInt(skp->cullRect().width()), 2048),
377         height = SkTMin(SkScalarCeilToInt(skp->cullRect().height()), 2048);
378     if (FLAGS_verbosity >= 3 &&
379         (width != skp->cullRect().width() || height != skp->cullRect().height())) {
380         fprintf(stderr, "%s is too large (%ix%i), cropping to %ix%i.\n",
381                         srcname.c_str(), SkScalarCeilToInt(skp->cullRect().width()),
382                         SkScalarCeilToInt(skp->cullRect().height()), width, height);
383     }
384 
385     if (config->getSurfType() != SkCommandLineConfigGpu::SurfType::kDefault) {
386         exitf(ExitErr::kUnavailable, "This tool only supports the default surface type. (%s)",
387               config->getTag().c_str());
388     }
389 
390     // Create a context.
391     GrContextOptions ctxOptions;
392     SetCtxOptionsFromCommonFlags(&ctxOptions);
393     sk_gpu_test::GrContextFactory factory(ctxOptions);
394     sk_gpu_test::ContextInfo ctxInfo =
395         factory.getContextInfo(config->getContextType(), config->getContextOverrides());
396     GrContext* ctx = ctxInfo.grContext();
397     if (!ctx) {
398         exitf(ExitErr::kUnavailable, "failed to create context for config %s",
399                                      config->getTag().c_str());
400     }
401     if (ctx->maxRenderTargetSize() < SkTMax(width, height)) {
402         exitf(ExitErr::kUnavailable, "render target size %ix%i not supported by platform (max: %i)",
403               width, height, ctx->maxRenderTargetSize());
404     }
405     GrPixelConfig grPixConfig = SkColorType2GrPixelConfig(config->getColorType());
406     if (kUnknown_GrPixelConfig == grPixConfig) {
407         exitf(ExitErr::kUnavailable, "failed to get GrPixelConfig from SkColorType: %d",
408                                      config->getColorType());
409     }
410     int supportedSampleCount = ctx->priv().caps()->getRenderTargetSampleCount(
411             config->getSamples(), grPixConfig);
412     if (supportedSampleCount != config->getSamples()) {
413         exitf(ExitErr::kUnavailable, "sample count %i not supported by platform",
414                                      config->getSamples());
415     }
416     sk_gpu_test::TestContext* testCtx = ctxInfo.testContext();
417     if (!testCtx) {
418         exitf(ExitErr::kSoftware, "testContext is null");
419     }
420     if (!testCtx->fenceSyncSupport()) {
421         exitf(ExitErr::kUnavailable, "GPU does not support fence sync");
422     }
423 
424     // Create a render target.
425     SkImageInfo info =
426             SkImageInfo::Make(width, height, config->getColorType(), config->getAlphaType(),
427                               sk_ref_sp(config->getColorSpace()));
428     uint32_t flags = config->getUseDIText() ? SkSurfaceProps::kUseDeviceIndependentFonts_Flag : 0;
429     SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType);
430     sk_sp<SkSurface> surface =
431         SkSurface::MakeRenderTarget(ctx, SkBudgeted::kNo, info, config->getSamples(), &props);
432     if (!surface) {
433         exitf(ExitErr::kUnavailable, "failed to create %ix%i render target for config %s",
434                                      width, height, config->getTag().c_str());
435     }
436 
437     // Run the benchmark.
438     std::vector<Sample> samples;
439     if (FLAGS_sampleMs > 0) {
440         // +1 because we might take one more sample in order to have an odd number.
441         samples.reserve(1 + (FLAGS_duration + FLAGS_sampleMs - 1) / FLAGS_sampleMs);
442     } else {
443         samples.reserve(2 * FLAGS_duration);
444     }
445     SkCanvas* canvas = surface->getCanvas();
446     canvas->translate(-skp->cullRect().x(), -skp->cullRect().y());
447     if (!FLAGS_gpuClock) {
448         if (FLAGS_ddl) {
449             run_ddl_benchmark(testCtx->fenceSync(), ctx, canvas, skp.get(), &samples);
450         } else {
451             run_benchmark(testCtx->fenceSync(), surface.get(), skp.get(), &samples);
452         }
453     } else {
454         if (FLAGS_ddl) {
455             exitf(ExitErr::kUnavailable, "DDL: GPU-only timing not supported");
456         }
457         if (!testCtx->gpuTimingSupport()) {
458             exitf(ExitErr::kUnavailable, "GPU does not support timing");
459         }
460         run_gpu_time_benchmark(testCtx->gpuTimer(), testCtx->fenceSync(), surface.get(), skp.get(),
461                                &samples);
462     }
463     print_result(samples, config->getTag().c_str(), srcname.c_str());
464 
465     // Save a proof (if one was requested).
466     if (!FLAGS_png.isEmpty()) {
467         SkBitmap bmp;
468         bmp.allocPixels(info);
469         if (!surface->getCanvas()->readPixels(bmp, 0, 0)) {
470             exitf(ExitErr::kUnavailable, "failed to read canvas pixels for png");
471         }
472         if (!mkdir_p(SkOSPath::Dirname(FLAGS_png[0]))) {
473             exitf(ExitErr::kIO, "failed to create directory for png \"%s\"", FLAGS_png[0]);
474         }
475         if (!sk_tool_utils::EncodeImageToFile(FLAGS_png[0], bmp, SkEncodedImageFormat::kPNG, 100)) {
476             exitf(ExitErr::kIO, "failed to save png to \"%s\"", FLAGS_png[0]);
477         }
478     }
479 
480     exit(0);
481 }
482 
draw_skp_and_flush(SkSurface * surface,const SkPicture * skp)483 static void draw_skp_and_flush(SkSurface* surface, const SkPicture* skp) {
484     auto canvas = surface->getCanvas();
485     canvas->drawPicture(skp);
486     surface->flush();
487 }
488 
create_warmup_skp()489 static sk_sp<SkPicture> create_warmup_skp() {
490     static constexpr SkRect bounds{0, 0, 500, 500};
491     SkPictureRecorder recorder;
492     SkCanvas* recording = recorder.beginRecording(bounds);
493 
494     recording->clear(SK_ColorWHITE);
495 
496     SkPaint stroke;
497     stroke.setStyle(SkPaint::kStroke_Style);
498     stroke.setStrokeWidth(2);
499 
500     // Use a big path to (theoretically) warmup the CPU.
501     SkPath bigPath;
502     sk_tool_utils::make_big_path(bigPath);
503     recording->drawPath(bigPath, stroke);
504 
505     // Use a perlin shader to warmup the GPU.
506     SkPaint perlin;
507     perlin.setShader(SkPerlinNoiseShader::MakeTurbulence(0.1f, 0.1f, 1, 0, nullptr));
508     recording->drawRect(bounds, perlin);
509 
510     return recorder.finishRecordingAsPicture();
511 }
512 
create_skp_from_svg(SkStream * stream,const char * filename)513 static sk_sp<SkPicture> create_skp_from_svg(SkStream* stream, const char* filename) {
514 #ifdef SK_XML
515     SkDOM xml;
516     if (!xml.build(*stream)) {
517         exitf(ExitErr::kData, "failed to parse xml in file %s", filename);
518     }
519     sk_sp<SkSVGDOM> svg = SkSVGDOM::MakeFromDOM(xml);
520     if (!svg) {
521         exitf(ExitErr::kData, "failed to build svg dom from file %s", filename);
522     }
523 
524     static constexpr SkRect bounds{0, 0, 1200, 1200};
525     SkPictureRecorder recorder;
526     SkCanvas* recording = recorder.beginRecording(bounds);
527 
528     svg->setContainerSize(SkSize::Make(recording->getBaseLayerSize()));
529     svg->render(recording);
530 
531     return recorder.finishRecordingAsPicture();
532 #endif
533     exitf(ExitErr::kData, "SK_XML is disabled; cannot open svg file %s", filename);
534     return nullptr;
535 }
536 
mkdir_p(const SkString & dirname)537 bool mkdir_p(const SkString& dirname) {
538     if (dirname.isEmpty()) {
539         return true;
540     }
541     return mkdir_p(SkOSPath::Dirname(dirname.c_str())) && sk_mkdir(dirname.c_str());
542 }
543 
join(const SkCommandLineFlags::StringArray & stringArray)544 static SkString join(const SkCommandLineFlags::StringArray& stringArray) {
545     SkString joined;
546     for (int i = 0; i < stringArray.count(); ++i) {
547         joined.appendf(i ? " %s" : "%s", stringArray[i]);
548     }
549     return joined;
550 }
551 
exitf(ExitErr err,const char * format,...)552 static void exitf(ExitErr err, const char* format, ...) {
553     fprintf(stderr, ExitErr::kSoftware == err ? "INTERNAL ERROR: " : "ERROR: ");
554     va_list args;
555     va_start(args, format);
556     vfprintf(stderr, format, args);
557     va_end(args);
558     fprintf(stderr, ExitErr::kSoftware == err ? "; this should never happen.\n": ".\n");
559     exit((int)err);
560 }
561 
GpuSync(const sk_gpu_test::FenceSync * fenceSync)562 GpuSync::GpuSync(const sk_gpu_test::FenceSync* fenceSync)
563     : fFenceSync(fenceSync) {
564     this->updateFence();
565 }
566 
~GpuSync()567 GpuSync::~GpuSync() {
568     fFenceSync->deleteFence(fFence);
569 }
570 
syncToPreviousFrame()571 void GpuSync::syncToPreviousFrame() {
572     if (sk_gpu_test::kInvalidFence == fFence) {
573         exitf(ExitErr::kSoftware, "attempted to sync with invalid fence");
574     }
575     if (!fFenceSync->waitFence(fFence)) {
576         exitf(ExitErr::kUnavailable, "failed to wait for fence");
577     }
578     fFenceSync->deleteFence(fFence);
579     this->updateFence();
580 }
581 
updateFence()582 void GpuSync::updateFence() {
583     fFence = fFenceSync->insertFence();
584     if (sk_gpu_test::kInvalidFence == fFence) {
585         exitf(ExitErr::kUnavailable, "failed to insert fence");
586     }
587 }
588