Debian Codegraph @

src/gpu/graphite/Recorder.cpp

raw
1 /*
2 * Copyright 2021 Google LLC
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 #include "include/gpu/graphite/Recorder.h"
8
9 #include "include/core/SkBitmap.h"
10 #include "include/core/SkCPURecorder.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkImage.h"
13 #include "include/core/SkImageInfo.h"
14 #include "include/core/SkPixmap.h"
15 #include "include/core/SkRect.h"
16 #include "include/core/SkSize.h"
17 #include "include/core/SkSurface.h"
18 #include "include/core/SkTypes.h"
19 #include "include/gpu/GpuTypes.h"
20 #include "include/gpu/graphite/BackendTexture.h"
21 #include "include/gpu/graphite/Context.h"
22 #include "include/gpu/graphite/GraphiteTypes.h"
23 #include "include/gpu/graphite/ImageProvider.h"
24 #include "include/gpu/graphite/Recording.h"
25 #include "include/gpu/graphite/TextureInfo.h"
26 #include "src/core/SkMipmap.h"
27 #include "src/core/SkTraceEvent.h"
28 #include "src/gpu/AtlasTypes.h"
29 #include "src/gpu/GpuTypesPriv.h"
30 #include "src/gpu/RefCntedCallback.h"
31 #include "src/gpu/Token.h"
32 #include "src/gpu/graphite/AtlasProvider.h"
33 #include "src/gpu/graphite/BufferManager.h"
34 #include "src/gpu/graphite/Caps.h"
35 #include "src/gpu/graphite/CommandBuffer.h"
36 #include "src/gpu/graphite/ContextPriv.h"
37 #include "src/gpu/graphite/Device.h"
38 #include "src/gpu/graphite/Log.h"
39 #include "src/gpu/graphite/PaintParamsKey.h"
40 #include "src/gpu/graphite/PipelineData.h"
41 #include "src/gpu/graphite/ProxyCache.h"
42 #include "src/gpu/graphite/QueueManager.h"
43 #include "src/gpu/graphite/RecorderPriv.h"
44 #include "src/gpu/graphite/RecordingPriv.h"
45 #include "src/gpu/graphite/ResourceProvider.h"
46 #include "src/gpu/graphite/ResourceTypes.h"
47 #include "src/gpu/graphite/RuntimeEffectDictionary.h"
48 #include "src/gpu/graphite/ScratchResourceManager.h"
49 #include "src/gpu/graphite/SharedContext.h"
50 #include "src/gpu/graphite/Texture.h"
51 #include "src/gpu/graphite/TextureProxy.h"
52 #include "src/gpu/graphite/UploadBufferManager.h"
53 #include "src/gpu/graphite/task/Task.h"
54 #include "src/gpu/graphite/task/TaskList.h"
55 #include "src/gpu/graphite/task/UploadTask.h"
56 #include "src/image/SkImage_Base.h"
57 #include "src/text/gpu/StrikeCache.h"
58 #include "src/text/gpu/TextBlobRedrawCoordinator.h"
59
60 #include <algorithm>
61 #include <atomic>
62 #include <functional>
63 #include <string_view>
64 #include <unordered_set>
65 #include <utility>
66 #include <vector>
67
68 #if defined(GPU_TEST_UTILS)
69 #include "src/gpu/graphite/RecorderOptionsPriv.h"
70 #endif
71
72 enum SkColorType : int;
73
74 namespace skgpu::graphite {
75
76 #define ASSERT_SINGLE_OWNER SKGPU_ASSERT_SINGLE_OWNER(this->singleOwner())
77 #define ASSERT_SINGLE_OWNER_PRIV SKGPU_ASSERT_SINGLE_OWNER(fRecorder->singleOwner())
78
79 /*
80 * The default image provider doesn't perform any conversion so, by default, Graphite won't
81 * draw any non-Graphite-backed images.
82 */
83 class DefaultImageProvider final : public ImageProvider {
84 public:
85 static sk_sp<DefaultImageProvider> Make() { return sk_sp(new DefaultImageProvider); }
86
87 sk_sp<SkImage> findOrCreate(Recorder* recorder,
88 const SkImage* image,
89 SkImage::RequiredProperties) override {
90 SkASSERT(!as_IB(image)->isGraphiteBacked());
91
92 return nullptr;
93 }
94
95 private:
96 DefaultImageProvider() {}
97 };
98
99 /**************************************************************************************************/
100 RecorderOptions::RecorderOptions() = default;
101 RecorderOptions::RecorderOptions(const RecorderOptions&) = default;
102 RecorderOptions::~RecorderOptions() = default;
103
104 /**************************************************************************************************/
105
106 namespace {
107
108 uint32_t next_id() {
109 static std::atomic<uint32_t> nextID{SK_InvalidGenID + 1};
110 uint32_t id;
111 do {
112 id = nextID.fetch_add(1, std::memory_order_relaxed);
113 } while (id == SK_InvalidGenID);
114 return id;
115 }
116
117 } // anonymous namespace
118
119 Recorder::Recorder(sk_sp<SharedContext> sharedContext,
120 const RecorderOptions& options,
121 const Context* context)
122 : fSharedContext(std::move(sharedContext))
123 , fRuntimeEffectDict(sk_make_sp<RuntimeEffectDictionary>())
124 , fRootTaskList(new TaskList)
125 , fRootUploads(new UploadList)
126 , fFloatStorageManager(sk_make_sp<FloatStorageManager>())
127 , fProxyReadCounts(new ProxyReadCountMap)
128 , fUniqueID(next_id())
129 , fRequireOrderedRecordings(options.fRequireOrderedRecordings.has_value()
130 ? *options.fRequireOrderedRecordings
131 : fSharedContext->caps()->requireOrderedRecordings())
132 , fAtlasProvider(std::make_unique<AtlasProvider>(this))
133 , fTokenTracker(std::make_unique<TokenTracker>())
134 , fStrikeCache(std::make_unique<sktext::gpu::StrikeCache>())
135 , fTextBlobCache(std::make_unique<sktext::gpu::TextBlobRedrawCoordinator>(fUniqueID)) {
136 fClientImageProvider = options.fImageProvider;
137 if (!fClientImageProvider) {
138 fClientImageProvider = DefaultImageProvider::Make();
139 }
140
141 if (context) {
142 fOwnedResourceProvider = nullptr;
143 fResourceProvider = context->priv().resourceProvider();
144 } else {
145 fOwnedResourceProvider = fSharedContext->makeResourceProvider(
146 this->singleOwner(),
147 fUniqueID,
148 options.fGpuBudgetInBytes);
149 fResourceProvider = fOwnedResourceProvider.get();
150 }
151 fUploadBufferManager = std::make_unique<UploadBufferManager>(fResourceProvider,
152 fSharedContext->caps());
153
154 DrawBufferManager::Options dbmOpts = {};
155 #if defined(GPU_TEST_UTILS)
156 if (options.fRecorderOptionsPriv && options.fRecorderOptionsPriv->fDbmOptions.has_value()) {
157 dbmOpts = *options.fRecorderOptionsPriv->fDbmOptions;
158 }
159 #endif
160
161 fDrawBufferManager = std::make_unique<DrawBufferManager>(fResourceProvider,
162 fSharedContext->caps(),
163 fUploadBufferManager.get(),
164 dbmOpts);
165
166 SkASSERT(fResourceProvider);
167 }
168
169 Recorder::~Recorder() {
170 ASSERT_SINGLE_OWNER
171 // Any finished procs that haven't been passed to a Recording fail
172 for (int i = 0; i < fFinishedProcs.size(); ++i) {
173 fFinishedProcs[i]->setFailureResult();
174 }
175
176 for (auto& device : fTrackedDevices) {
177 // deregisterDevice() may have left an entry as null previously.
178 if (device) {
179 device->abandonRecorder();
180 }
181 }
182
183 #if defined(GPU_TEST_UTILS)
184 if (fContext) {
185 fContext->priv().deregisterRecorder(this);
186 }
187 #endif
188 }
189
190 BackendApi Recorder::backend() const { return fSharedContext->backend(); }
191
192 skcpu::Recorder* Recorder::cpuRecorder() {
193 return skcpu::Recorder::TODO();
194 }
195
196 std::unique_ptr<Recording> Recorder::snap() {
197 TRACE_EVENT0_ALWAYS("skia.gpu", TRACE_FUNC);
198 ASSERT_SINGLE_OWNER
199
200 if (fTargetProxyData) {
201 // Normally devices are marked immutable when their owning Surface goes away, but the
202 // deferred canvas+device do not have a surface so mimic that operation. Do this before
203 // flushing all other tracked devices to avoid a redundant flush.
204 fTargetProxyDevice->setImmutable();
205 fTargetProxyDevice.reset();
206 fTargetProxyCanvas.reset();
207 }
208 // Collect all pending tasks on the deferred recording canvas and any other tracked device.
209 this->priv().flushTrackedDevices(SK_DUMP_TASKS_CODE("Recorder::Snap"));
210
211 // The scratch resources only need to be tracked until prepareResources() is finished, so
212 // Recorder doesn't hold a persistent manager and it can be deleted when snap() returns.
213 ScratchResourceManager scratchManager{fResourceProvider, std::move(fProxyReadCounts)};
214 std::unique_ptr<Recording> recording(new Recording(fNextRecordingID++,
215 fRequireOrderedRecordings ? fUniqueID
216 : SK_InvalidGenID,
217 std::move(fTargetProxyData),
218 std::move(fFinishedProcs)));
219 // Allow the buffer managers to add any collected tasks for data transfer or initialization
220 // before moving the root task list to the Recording.
221 bool valid = fFloatStorageManager->finalize(fDrawBufferManager.get());
222 valid &= fDrawBufferManager->transferToRecording(recording.get());
223
224 // We create the Recording's full task list even if the DrawBufferManager failed because it is
225 // a convenient way to ensure everything else is unmapped and reset for the next Recording.
226 fUploadBufferManager->transferToRecording(recording.get());
227 // Add one task for all root uploads before the rest of the rendering tasks might depend on them
228 if (fRootUploads->size() > 0) {
229 sk_sp<Task> uploadTask = UploadTask::Make(fRootUploads.get());
230
231 // If we are dumping tasks, we want to be able to associate each task with the current flush
232 // count, so each task gets a flushToken---just an int---to track this.
233 SK_DUMP_TASKS_CODE(uploadTask->fFlushToken =
234 this->priv().tokenTracker()->currentFlushToken();)
235
236 recording->priv().taskList()->add(std::move(uploadTask));
237 SkASSERT(fRootUploads->size() == 0); // Drained by the newly added task
238 }
239 recording->priv().taskList()->add(std::move(*fRootTaskList));
240 SkASSERT(!fRootTaskList->hasTasks());
241
242 SK_DUMP_TASKS_CODE(this->dumpTasks(recording->priv().taskList()));
243
244 // In both the "task failed" case and the "everything is discarded" case, there's no work that
245 // needs to be done in insertRecording(). However, we use nullptr as a failure signal, so
246 // kDiscard will return a non-null Recording that has no tasks in it.
247 valid &= recording->priv().prepareResources(fResourceProvider,
248 &scratchManager,
249 fRuntimeEffectDict);
250 if (!valid) {
251 recording = nullptr;
252 fAtlasProvider->invalidateAtlases();
253 }
254
255 // Process the return queue at least once to keep it from growing too large, as otherwise
256 // it's only processed during an explicit cleanup or a cache miss.
257 fResourceProvider->forceProcessReturnedResources();
258
259 // Remaining cleanup that must always happen regardless of success or failure
260 fRuntimeEffectDict = sk_make_sp<RuntimeEffectDictionary>();
261 fProxyReadCounts = std::make_unique<ProxyReadCountMap>();
262 fFloatStorageManager = sk_make_sp<FloatStorageManager>();
263 if (!fRequireOrderedRecordings) {
264 fAtlasProvider->invalidateAtlases();
265 }
266
267 // For each KeyAndDataBuilder owned by the Recorder, check if the high watermark of data usage
268 // over the lifetime snap is less than half of allocated capacity. If so, shrink the capacity.
269 for (const std::unique_ptr<KeyAndDataBuilder>& keyDB : fKeyAndDataBuilders) {
270 SkASSERT(keyDB);
271 keyDB->first.tryShrinkCapacity();
272 keyDB->second.tryShrinkCapacity();
273 }
274 return recording;
275 }
276
277 SkCanvas* Recorder::makeDeferredCanvas(const SkImageInfo& imageInfo,
278 const TextureInfo& textureInfo) {
279 if (fTargetProxyCanvas) {
280 // Require snapping before requesting another canvas.
281 SKGPU_LOG_W("Requested a new deferred canvas before snapping the previous one");
282 return nullptr;
283 }
284
285 fTargetProxyData = std::make_unique<Recording::LazyProxyData>(
286 this->priv().caps(), imageInfo.dimensions(), textureInfo);
287 // Use kLoad for the initial load op since the purpose of a deferred canvas is to draw on top
288 // of an existing, late-bound texture.
289 fTargetProxyDevice = Device::Make(this,
290 fTargetProxyData->refLazyProxy(),
291 imageInfo.dimensions(),
292 imageInfo.colorInfo(),
293 {},
294 LoadOp::kLoad);
295 fTargetProxyCanvas = std::make_unique<SkCanvas>(fTargetProxyDevice);
296 return fTargetProxyCanvas.get();
297 }
298
299 SkCanvas* Recorder::makeCaptureCanvas(SkCanvas* canvas) {
300 if (fSharedContext->captureManager()) {
301 return fSharedContext->captureManager()->makeCaptureCanvas(canvas);
302 }
303 return nullptr;
304 }
305
306 void Recorder::createCaptureBreakpoint(SkSurface* surface) {
307 if (fSharedContext->captureManager()) {
308 fSharedContext->captureManager()->snapPicture(surface);
309 }
310 }
311
312 void Recorder::registerDevice(sk_sp<Device> device) {
313 ASSERT_SINGLE_OWNER
314
315 SkASSERT(device);
316
317 // By taking a ref on tracked devices, the Recorder prevents the Device from being deleted on
318 // another thread unless the Recorder has been destroyed or the device has abandoned its
319 // recorder (e.g. was marked immutable).
320 fTrackedDevices.emplace_back(std::move(device));
321 }
322
323 void Recorder::deregisterDevice(const Device* device) {
324 ASSERT_SINGLE_OWNER
325 for (int i = 0; i < fTrackedDevices.size(); ++i) {
326 if (fTrackedDevices[i].get() == device) {
327 // Don't modify the list structure of fTrackedDevices within this loop
328 fTrackedDevices[i] = nullptr;
329 break;
330 }
331 }
332 }
333
334 int Recorder::maxTextureSize() const {
335 return this->priv().caps()->maxTextureSize();
336 }
337
338 BackendTexture Recorder::createBackendTexture(SkISize dimensions, const TextureInfo& info) {
339 ASSERT_SINGLE_OWNER
340
341 if (!info.isValid() || info.backend() != this->backend()) {
342 return {};
343 }
344 return fResourceProvider->createBackendTexture(dimensions, info);
345 }
346
347 #ifdef SK_BUILD_FOR_ANDROID
348
349 BackendTexture Recorder::createBackendTexture(AHardwareBuffer* hardwareBuffer,
350 bool isRenderable,
351 bool isProtectedContent,
352 SkISize dimensions,
353 bool fromAndroidWindow) const {
354 if (fSharedContext->backend() != BackendApi::kVulkan) {
355 SKGPU_LOG_W("Creating an AHardwareBuffer-backed BackendTexture is only supported with the"
356 "Vulkan backend.");
357 return {};
358 }
359 return fResourceProvider->createBackendTexture(hardwareBuffer,
360 isRenderable,
361 isProtectedContent,
362 dimensions,
363 fromAndroidWindow);
364 }
365
366 #endif // SK_BUILD_FOR_ANDROID
367
368 bool Recorder::updateBackendTexture(const BackendTexture& backendTex,
369 const SkPixmap srcData[],
370 int numLevels,
371 GpuFinishedProc finishedProc,
372 GpuFinishedContext finishedContext) {
373 ASSERT_SINGLE_OWNER
374
375 auto releaseHelper = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
376
377 if (!backendTex.isValid() || backendTex.backend() != this->backend()) {
378 return false;
379 }
380
381 if (!srcData || numLevels <= 0) {
382 return false;
383 }
384
385 // If the texture has MIP levels then we require that the full set is overwritten.
386 int numExpectedLevels = 1;
387 if (backendTex.info().mipmapped() == Mipmapped::kYes) {
388 numExpectedLevels = SkMipmap::ComputeLevelCount(backendTex.dimensions()) + 1;
389 }
390 if (numLevels != numExpectedLevels) {
391 return false;
392 }
393
394 SkColorType ct = srcData[0].colorType();
395
396 if (!this->priv().caps()->areColorTypeAndTextureInfoCompatible(ct, backendTex.info())) {
397 return false;
398 }
399
400 sk_sp<Texture> texture = this->priv().resourceProvider()->createWrappedTexture(backendTex, "");
401 if (!texture) {
402 return false;
403 }
404 texture->setReleaseCallback(std::move(releaseHelper));
405
406 std::vector<MipLevel> mipLevels;
407 mipLevels.resize(numLevels);
408
409 for (int i = 0; i < numLevels; ++i) {
410 SkASSERT(srcData[i].addr());
411 SkASSERT(srcData[i].info().colorInfo() == srcData[0].info().colorInfo());
412
413 mipLevels[i].fPixels = srcData[i].addr();
414 mipLevels[i].fRowBytes = srcData[i].rowBytes();
415 }
416
417 sk_sp<TextureProxy> proxy = TextureProxy::Wrap(std::move(texture));
418
419 // Src and dst colorInfo are the same
420 const SkColorInfo& colorInfo = srcData[0].info().colorInfo();
421
422 const SkIRect dimensions = SkIRect::MakeSize(backendTex.dimensions());
423 UploadSource uploadSource = UploadSource::Make(
424 this->priv().caps(), *proxy, colorInfo, colorInfo, mipLevels, dimensions);
425 if (!uploadSource.isValid()) {
426 SKGPU_LOG_E("Recorder::updateBackendTexture: Could not create UploadSource");
427 return false;
428 }
429
430 // Attempt to update the texture directly on the host if possible.
431 if (uploadSource.canUploadOnHost()) {
432 return proxy->texture()->uploadDataOnHost(uploadSource, dimensions);
433 }
434
435 // Add UploadTask to Recorder
436 UploadInstance upload = UploadInstance::Make(this,
437 std::move(proxy),
438 colorInfo,
439 colorInfo,
440 uploadSource,
441 dimensions,
442 std::make_unique<ImageUploadContext>());
443 if (!upload.isValid()) {
444 SKGPU_LOG_E("Recorder::updateBackendTexture: Could not create UploadInstance");
445 return false;
446 }
447 sk_sp<Task> uploadTask = UploadTask::Make(std::move(upload));
448
449 // Need to flush any pending work in case it depends on this texture
450 this->priv().flushTrackedDevices(
451 SK_DUMP_TASKS_CODE("Recorder::updateBackendTexture: Update Backend Texture"));
452
453 this->priv().add(std::move(uploadTask));
454
455 return true;
456 }
457
458 bool Recorder::updateCompressedBackendTexture(const BackendTexture& backendTex,
459 const void* data,
460 size_t dataSize,
461 GpuFinishedProc finishedProc,
462 GpuFinishedContext finishedContext) {
463 ASSERT_SINGLE_OWNER
464
465 auto releaseHelper = skgpu::RefCntedCallback::Make(finishedProc, finishedContext);
466
467 if (!backendTex.isValid() || backendTex.backend() != this->backend()) {
468 return false;
469 }
470
471 if (!data) {
472 return false;
473 }
474
475 sk_sp<Texture> texture = this->priv().resourceProvider()->createWrappedTexture(backendTex, "");
476 if (!texture) {
477 return false;
478 }
479 texture->setReleaseCallback(std::move(releaseHelper));
480
481 sk_sp<TextureProxy> proxy = TextureProxy::Wrap(std::move(texture));
482
483 UploadSource uploadSource =
484 UploadSource::MakeCompressed(this->priv().caps(), *proxy, data, dataSize);
485 if (!uploadSource.isValid()) {
486 SKGPU_LOG_E("Recorder::updateBackendTexture: Could not create compressed UploadSource");
487 return false;
488 }
489
490 // Attempt to update the texture directly on the host if possible.
491 if (uploadSource.canUploadOnHost()) {
492 return proxy->texture()->uploadDataOnHost(uploadSource,
493 SkIRect::MakeSize(proxy->dimensions()));
494 }
495
496 // Add UploadTask to Recorder
497 UploadInstance upload = UploadInstance::MakeCompressed(this, std::move(proxy), uploadSource);
498 if (!upload.isValid()) {
499 SKGPU_LOG_E("Recorder::updateBackendTexture: Could not create compressed UploadInstance");
500 return false;
501 }
502 sk_sp<Task> uploadTask = UploadTask::Make(std::move(upload));
503
504 // Need to flush any pending work in case it depends on this texture
505 this->priv().flushTrackedDevices(SK_DUMP_TASKS_CODE(
506 "Recorder::updateCompressedBackendTexture Update Compressed Backend Texture"));
507
508 this->priv().add(std::move(uploadTask));
509
510 return true;
511 }
512
513 void Recorder::deleteBackendTexture(const BackendTexture& texture) {
514 ASSERT_SINGLE_OWNER
515
516 if (!texture.isValid() || texture.backend() != this->backend()) {
517 return;
518 }
519 fResourceProvider->deleteBackendTexture(texture);
520 }
521
522 void Recorder::addFinishInfo(const InsertFinishInfo& info) {
523 if (info.fFinishedProc) {
524 sk_sp<RefCntedCallback> callback =
525 RefCntedCallback::Make(info.fFinishedProc, info.fFinishedContext);
526 fFinishedProcs.push_back(std::move(callback));
527 }
528 }
529
530 void Recorder::freeGpuResources() {
531 ASSERT_SINGLE_OWNER
532
533 // We don't want to free the Uniform or the Draw/UploadBufferManagers sinceall their resources
534 // need to be held on to until a Recording is snapped. And once snapped, all their held
535 // resources are released. The StrikeCache and TextBlobCache don't hold onto any Gpu resources.
536
537 // Notify the atlas and resource provider to free any resources it can (does not include
538 // resources that are locked due to pending work).
539 fAtlasProvider->freeGpuResources();
540
541 fResourceProvider->freeGpuResources();
542
543 // This is technically not GPU memory, but there's no other place for the client to tell us to
544 // clean this up, and without any cleanup it can grow unbounded.
545 fStrikeCache->freeAll();
546 }
547
548 void Recorder::performDeferredCleanup(std::chrono::milliseconds msNotUsed) {
549 ASSERT_SINGLE_OWNER
550
551 auto purgeTime = skgpu::StdSteadyClock::now() - msNotUsed;
552 fResourceProvider->purgeResourcesNotUsedSince(purgeTime);
553 }
554
555 size_t Recorder::currentBudgetedBytes() const {
556 ASSERT_SINGLE_OWNER
557 return fResourceProvider->getResourceCacheCurrentBudgetedBytes();
558 }
559
560 size_t Recorder::currentPurgeableBytes() const {
561 ASSERT_SINGLE_OWNER
562 return fResourceProvider->getResourceCacheCurrentPurgeableBytes();
563 }
564
565 size_t Recorder::maxBudgetedBytes() const {
566 ASSERT_SINGLE_OWNER
567 return fResourceProvider->getResourceCacheLimit();
568 }
569
570 void Recorder::setMaxBudgetedBytes(size_t bytes) {
571 ASSERT_SINGLE_OWNER
572 return fResourceProvider->setResourceCacheLimit(bytes);
573 }
574
575 void Recorder::dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const {
576 ASSERT_SINGLE_OWNER
577 fResourceProvider->dumpMemoryStatistics(traceMemoryDump);
578 // TODO: What is the graphite equivalent for the text blob cache and how do we print out its
579 // used bytes here (see Ganesh implementation).
580 }
581
582 #if defined(SK_DUMP_TASKS)
583 void Recorder::dumpTasks(TaskList* taskList) const {
584 ASSERT_SINGLE_OWNER
585 SkDebugf("\n=========== RECORDING %u ===========\n", fUniqueID);
586 int taskIndex = 0;
587 uint64_t lastToken = skgpu::Token::InvalidToken().value();
588 taskList->visit([&](const Task* task, bool isLast) {
589 if (!task) {
590 return;
591 }
592 uint64_t currToken = task->fFlushToken.value();
593 if (currToken != lastToken) {
594 SkDebugf("**** FLUSH TOKEN %llu %s ****\n", currToken, fFlushSources[currToken - 1]);
595 lastToken = currToken;
596 }
597 task->dump(taskIndex++, "");
598 });
599 SkDebugf("--------------- END ---------------\n");
600 }
601 #endif
602
603 sk_sp<RuntimeEffectDictionary> RecorderPriv::runtimeEffectDictionary() {
604 return fRecorder->fRuntimeEffectDict;
605 }
606
607 void RecorderPriv::addPendingRead(const TextureProxy* proxy) {
608 ASSERT_SINGLE_OWNER_PRIV
609 fRecorder->fProxyReadCounts->increment(proxy);
610 }
611
612 void RecorderPriv::add(sk_sp<Task> task) {
613 ASSERT_SINGLE_OWNER_PRIV
614 // Associate each task with current flush count.
615 SK_DUMP_TASKS_CODE(task->fFlushToken = fRecorder->fTokenTracker->nextFlushToken();)
616 fRecorder->fRootTaskList->add(std::move(task));
617 }
618
619 void RecorderPriv::flushTrackedDevices(const TextureProxy* dependency) {
620 // This version of flushTrackedDevices() must be re-entrant because it is entirely possible for
621 // client-owned surfaces to read and write to each other, where this will be called with
622 // different textures for `dependency`. The recursion stops once the encountered surfaces have
623 // snapped remaining pending work from their DrawContext. But because we might recurse, we do
624 // not perform any cleanup of the fTrackedDevices list. That is deferred until snap() time.
625
626 for (int i = 0; i < fRecorder->fTrackedDevices.size(); ++i) {
627 // Entries may be set to null from a call to deregisterDevice(), which will be cleaned up
628 // along with any immutable or uniquely held Devices once everything is snapped.
629 Device* device = fRecorder->fTrackedDevices[i].get();
630 if (device && device->hasPendingReads(dependency)) {
631 device->flushPendingWork(/*drawContext=*/nullptr);
632 }
633 }
634
635 // TODO(michaelludwig): These flushes are currently only triggered for client-owned surfaces
636 // drawn into other surfaces. This function could be used to flush a more targeted set of
637 // devices when an atlas fills up; in that case we could increment the flush token as part of
638 // that work. As-is, we don't increment the flush token because there could be a tracked atlas
639 // that depended on the atlas's texture state that did *not* depend on `dependency` so it still
640 // requires the atlas to be using the old flush token. The surfaces that were flushed here could
641 // advance to a new token but the token tracking isn't that precise. This all may be moot
642 // anyways if we can successfully switch to a rolling atlas page system.
643 }
644
645 void RecorderPriv::flushTrackedDevices(SK_DUMP_TASKS_CODE(const char* flushSource)) {
646 ASSERT_SINGLE_OWNER_PRIV
647 SkASSERT(!fRecorder->fIsFlushingTrackedDevices);
648 SkDEBUGCODE(fRecorder->fIsFlushingTrackedDevices = true);
649
650 for (int i = 0; i < fRecorder->fTrackedDevices.size(); ++i) {
651 // Entries may be set to null from a call to deregisterDevice(), which will be cleaned up
652 // along with any immutable or uniquely held Devices once everything is flushed.
653 Device* device = fRecorder->fTrackedDevices[i].get();
654 if (device) {
655 device->flushPendingWork(/*drawContext=*/nullptr);
656 }
657 }
658
659 // Issue next upload flush token. This is only used by the atlasing code which
660 // always uses this method. Calling in Device::flushPendingWorkToRecorder may
661 // miss parent device flushes, increment too often, and lead to atlas corruption.
662 this->tokenTracker()->issueFlushToken();
663 #if defined(SK_DUMP_TASKS)
664 fRecorder->fFlushSources.push_back(flushSource);
665 SkASSERT(this->tokenTracker()->currentFlushToken().value() ==
666 static_cast<uint64_t>(fRecorder->fFlushSources.size()));
667 #endif
668
669 // This version of flushTrackedDevices() is not re-entrant, so it *does* perform the final
670 // cleanup on the fTrackedDevices.
671 int i = 0;
672 while (i < fRecorder->fTrackedDevices.size()) {
673 Device* device = fRecorder->fTrackedDevices[i].get();
674 if (!device || !device->recorder() || device->unique()) {
675 if (device) {
676 device->abandonRecorder(); // Keep ~Device() happy
677 }
678 fRecorder->fTrackedDevices.removeShuffle(i);
679 // Keep i as-is to process what was just shuffled to the ith index.
680 } else {
681 i++;
682 }
683 }
684
685 SkDEBUGCODE(fRecorder->fIsFlushingTrackedDevices = false);
686 }
687
688 std::unique_ptr<KeyAndDataBuilder> RecorderPriv::popOrCreateKeyAndDataBuilder() {
689 if (!fRecorder->fKeyAndDataBuilders.empty()) {
690 std::unique_ptr<KeyAndDataBuilder> keyDB = std::move(fRecorder->fKeyAndDataBuilders.back());
691 fRecorder->fKeyAndDataBuilders.pop_back();
692 return keyDB;
693 }
694
695 const bool useStorageBuffers = this->caps()->storageBufferSupport();
696 const auto& bindingReq = this->caps()->resourceBindingRequirements();
697 auto gathererLayout = useStorageBuffers ? bindingReq.fStorageBufferLayout
698 : bindingReq.fUniformBufferLayout;
699
700 return std::make_unique<KeyAndDataBuilder>(
701 PipelineDataGatherer(gathererLayout),
702 PaintParamsKeyBuilder(this->shaderCodeDictionary()));
703 }
704
705 void RecorderPriv::pushKeyAndDataBuilder(std::unique_ptr<KeyAndDataBuilder> keyDB) {
706 SkASSERT(keyDB);
707
708 if (fRecorder->fKeyAndDataBuilders.size() < Recorder::kMaxKeyAndDataBuilders) {
709 fRecorder->fKeyAndDataBuilders.push_back(std::move(keyDB));
710 return;
711 }
712 // If no empty slot was found, the "keyDB" unique_ptr goes out of scope here.
713 }
714
715 sk_sp<TextureProxy> RecorderPriv::CreateCachedProxy(Recorder* recorder,
716 const SkBitmap& bitmap,
717 std::string_view label) {
718 SkASSERT(!bitmap.isNull());
719
720 if (!recorder) {
721 return nullptr;
722 }
723 return recorder->priv().proxyCache()->findOrCreateCachedProxy(recorder, bitmap, label);
724 }
725
726 size_t RecorderPriv::getResourceCacheLimit() const {
727 return fRecorder->fResourceProvider->getResourceCacheLimit();
728 }
729
730 #if defined(GPU_TEST_UTILS)
731 bool RecorderPriv::deviceIsRegistered(Device* device) const {
732 ASSERT_SINGLE_OWNER_PRIV
733 for (const sk_sp<Device>& currentDevice : fRecorder->fTrackedDevices) {
734 if (device == currentDevice.get()) {
735 return true;
736 }
737 }
738 return false;
739 }
740
741 // used by the Context that created this Recorder to set a back pointer
742 void RecorderPriv::setContext(Context* context) {
743 fRecorder->fContext = context;
744 }
745
746 void RecorderPriv::issueFlushToken() {
747 fRecorder->fTokenTracker->issueFlushToken();
748 }
749 #endif
750
751 } // namespace skgpu::graphite