Debian Codegraph @

src/gpu/graphite/Context.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/Context.h"
8
9 #include "include/core/SkAlphaType.h"
10 #include "include/core/SkBlendMode.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkColorFilter.h"
13 #include "include/core/SkColorSpace.h"
14 #include "include/core/SkColorType.h"
15 #include "include/core/SkImage.h"
16 #include "include/core/SkImageInfo.h"
17 #include "include/core/SkMatrix.h"
18 #include "include/core/SkPaint.h"
19 #include "include/core/SkPixmap.h"
20 #include "include/core/SkRect.h"
21 #include "include/core/SkRefCnt.h"
22 #include "include/core/SkSamplingOptions.h"
23 #include "include/core/SkShader.h"
24 #include "include/core/SkSize.h"
25 #include "include/core/SkSurface.h"
26 #include "include/core/SkTileMode.h"
27 #include "include/core/SkTypes.h"
28 #include "include/gpu/GpuTypes.h"
29 #include "include/gpu/graphite/BackendTexture.h"
30 #include "include/gpu/graphite/ContextOptions.h"
31 #include "include/gpu/graphite/GraphiteTypes.h"
32 #include "include/gpu/graphite/PrecompileContext.h"
33 #include "include/gpu/graphite/Recorder.h"
34 #include "include/gpu/graphite/Surface.h"
35 #include "include/private/base/SingleOwner.h"
36 #include "include/private/base/SkAlign.h"
37 #include "include/private/base/SkMutex.h"
38 #include "include/private/base/SkOnce.h"
39 #include "include/private/base/SkTArray.h"
40 #include "include/private/base/SkTo.h"
41 #include "src/base/SkEnumBitMask.h"
42 #include "src/base/SkRectMemcpy.h"
43 #include "src/capture/SkCapture.h"
44 #include "src/capture/SkCaptureManager.h"
45 #include "src/core/SkAutoPixmapStorage.h"
46 #include "src/core/SkCPUContextImpl.h"
47 #include "src/core/SkCPURecorderImpl.h"
48 #include "src/core/SkConvertPixels.h"
49 #include "src/core/SkImageInfoPriv.h"
50 #include "src/core/SkTraceEvent.h"
51 #include "src/core/SkYUVMath.h"
52 #include "src/gpu/AsyncReadTypes.h"
53 #include "src/gpu/GpuTypesPriv.h"
54 #include "src/gpu/SkBackingFit.h"
55 #include "src/gpu/graphite/AtlasProvider.h"
56 #include "src/gpu/graphite/Buffer.h"
57 #include "src/gpu/graphite/BufferManager.h"
58 #include "src/gpu/graphite/Caps.h"
59 #include "src/gpu/graphite/ClientMappedBufferManager.h"
60 #include "src/gpu/graphite/ContextPriv.h"
61 #include "src/gpu/graphite/GlobalCache.h"
62 #include "src/gpu/graphite/Image_Graphite.h"
63 #include "src/gpu/graphite/Log.h"
64 #include "src/gpu/graphite/QueueManager.h"
65 #include "src/gpu/graphite/RecorderPriv.h"
66 #include "src/gpu/graphite/RendererProvider.h"
67 #include "src/gpu/graphite/ResourceProvider.h"
68 #include "src/gpu/graphite/ResourceTypes.h"
69 #include "src/gpu/graphite/RuntimeEffectDictionary.h"
70 #include "src/gpu/graphite/SharedContext.h"
71 #include "src/gpu/graphite/Surface_Graphite.h"
72 #include "src/gpu/graphite/TextureProxy.h"
73 #include "src/gpu/graphite/TextureProxyView.h"
74 #include "src/gpu/graphite/TextureUtils.h"
75 #include "src/gpu/graphite/task/CopyTask.h"
76 #include "src/gpu/graphite/task/SynchronizeToCpuTask.h"
77 #include "src/gpu/graphite/task/Task.h"
78 #include "src/image/SkSurface_Base.h"
79 #include "src/sksl/SkSLGraphiteModules.h"
80
81 #include <algorithm>
82 #include <array>
83 #include <atomic>
84 #include <chrono>
85 #include <cstdint>
86 #include <cstring>
87 #include <forward_list>
88 #include <functional>
89 #include <memory>
90 #include <optional>
91 #include <string_view>
92 #include <tuple>
93 #include <utility>
94 #include <vector>
95
96 #if defined(GPU_TEST_UTILS)
97 #include "src/gpu/graphite/ContextOptionsPriv.h"
98 #endif
99
100 class SkTraceMemoryDump;
101
102 namespace skgpu::graphite { class Recording; }
103
104 namespace skgpu::graphite {
105
106 #define ASSERT_SINGLE_OWNER SKGPU_ASSERT_SINGLE_OWNER(this->singleOwner())
107
108 Context::ContextID Context::ContextID::Next() {
109 static std::atomic<uint32_t> nextID{1};
110 uint32_t id;
111 do {
112 id = nextID.fetch_add(1, std::memory_order_relaxed);
113 } while (id == SK_InvalidUniqueID);
114 return ContextID(id);
115 }
116
117 //--------------------------------------------------------------------------------------------------
118 Context::Context(sk_sp<SharedContext> sharedContext,
119 std::unique_ptr<QueueManager> queueManager,
120 const ContextOptions& options)
121 : fSharedContext(std::move(sharedContext))
122 , fQueueManager(std::move(queueManager))
123 , fContextID(ContextID::Next()) {
124 // We need to move the Graphite SkSL code into the central SkSL data loader at least once
125 // (but preferrably only once) before we try to use it. We assume that there's no way to
126 // use the SkSL code without making a context, so we initialize it here.
127 static SkOnce once;
128 once([] { SkSL::Loader::SetGraphiteModuleData(SkSL::Loader::GetGraphiteModules()); });
129
130 // We have to create this outside the initializer list because we need to pass in the Context's
131 // SingleOwner object and it is declared last
132 fResourceProvider = fSharedContext->makeResourceProvider(&fSingleOwner,
133 SK_InvalidGenID,
134 options.fGpuBudgetInBytes);
135 fMappedBufferManager = std::make_unique<ClientMappedBufferManager>(this->contextID());
136 #if defined(GPU_TEST_UTILS)
137 if (options.fOptionsPriv) {
138 fStoreContextRefInRecorder = options.fOptionsPriv->fStoreContextRefInRecorder;
139 }
140 #endif
141
142 fSharedContext->globalCache()->setPipelineCallback(options.fPipelineCallbackContext,
143 options.fPipelineCachingCallback,
144 options.fPipelineCallback);
145
146 fCPUContext = std::make_unique<skcpu::ContextImpl>();
147 if (options.fEnableCapture) {
148 fSharedContext->setCaptureManager(sk_make_sp<SkCaptureManager>());
149 }
150
151 fPersistentPipelineStorage = options.fPersistentPipelineStorage;
152 }
153
154 Context::~Context() {
155 #if defined(GPU_TEST_UTILS)
156 SkAutoMutexExclusive lock(fTestingLock);
157 for (auto& recorder : fTrackedRecorders) {
158 recorder->priv().setContext(nullptr);
159 }
160 #endif
161 }
162
163 Context::PixelTransferResult::PixelTransferResult() = default;
164 Context::PixelTransferResult::PixelTransferResult(const PixelTransferResult&) = default;
165 Context::PixelTransferResult::PixelTransferResult(PixelTransferResult&&) = default;
166 Context::PixelTransferResult& Context::PixelTransferResult::operator=(const PixelTransferResult&) = default;
167 Context::PixelTransferResult::~PixelTransferResult() = default;
168
169 bool Context::finishInitialization() {
170 SkASSERT(!fSharedContext->rendererProvider()); // Can only initialize once
171
172 if (!fSharedContext->globalCache()->initializeDynamicSamplers(fResourceProvider.get(),
173 fSharedContext->caps())) {
174 return false;
175 }
176
177 StaticBufferManager bufferManager{fResourceProvider.get(), fSharedContext->caps()};
178 std::unique_ptr<RendererProvider> renderers{
179 new RendererProvider(fSharedContext->caps(), &bufferManager)};
180
181 auto result = bufferManager.finalize(this, fQueueManager.get(), fSharedContext->globalCache());
182 if (result == StaticBufferManager::FinishResult::kFailure) {
183 // If something went wrong filling out the static vertex buffers, any Renderer that would
184 // use it will draw incorrectly, so it's better to fail the Context creation.
185 return false;
186 }
187 if (result == StaticBufferManager::FinishResult::kSuccess &&
188 !fQueueManager->submitToGpu(/*submitInfo=*/{})) {
189 SKGPU_LOG_W("Failed to submit initial command buffer for Context creation.\n");
190 return false;
191 } // else result was kNoWork so skip submitting to the GPU
192 fSharedContext->setRendererProvider(std::move(renderers));
193 return true;
194 }
195
196 BackendApi Context::backend() const { return fSharedContext->backend(); }
197
198 std::unique_ptr<Recorder> Context::makeRecorder(const RecorderOptions& options) {
199 ASSERT_SINGLE_OWNER
200
201 // This is a client-owned Recorder so pass a null context so it creates its own ResourceProvider
202 auto recorder = std::unique_ptr<Recorder>(new Recorder(fSharedContext, options, nullptr));
203 #if defined(GPU_TEST_UTILS)
204 if (fStoreContextRefInRecorder) {
205 recorder->priv().setContext(this);
206 }
207 #endif
208 return recorder;
209 }
210
211 std::unique_ptr<skcpu::Recorder> Context::makeCPURecorder() {
212 ASSERT_SINGLE_OWNER
213
214 return std::make_unique<skcpu::RecorderImpl>(fCPUContext.get());
215 }
216
217 std::unique_ptr<PrecompileContext> Context::makePrecompileContext() {
218 ASSERT_SINGLE_OWNER
219
220 return std::unique_ptr<PrecompileContext>(new PrecompileContext(fSharedContext));
221 }
222
223 std::unique_ptr<Recorder> Context::makeInternalRecorder() const {
224 ASSERT_SINGLE_OWNER
225
226 // Unlike makeRecorder(), this Recorder is meant to be short-lived and go away before a Context
227 // public API function returns to the caller. As such it shares the Context's resource provider
228 // (no separate budget) and does not get tracked. The internal drawing performed with an
229 // internal recorder should not require a client image provider.
230 //
231 // Explicitly overrides fRequiresOrderedRecordings to false so that these Recorders do not
232 // inherit any global policy from the ContextOptions. Since they will only produce one Recording
233 // there's no need to require subsequent recordings be ordered.
234 RecorderOptions options = {};
235 options.fRequireOrderedRecordings = false;
236 return std::unique_ptr<Recorder>(new Recorder(fSharedContext, options, this));
237 }
238
239 InsertStatus Context::insertRecording(const InsertRecordingInfo& info) {
240 ASSERT_SINGLE_OWNER
241
242 return fQueueManager->addRecording(info, this);
243 }
244
245 bool Context::submit(SubmitInfo submitInfo) {
246 ASSERT_SINGLE_OWNER
247
248 if (submitInfo.fSync == SyncToCpu::kYes && !fSharedContext->caps()->allowCpuSync()) {
249 SKGPU_LOG_E("SyncToCpu::kYes not supported with ContextOptions::fNeverYieldToWebGPU. "
250 "The parameter is ignored and no synchronization will occur.");
251 submitInfo.fSync = SyncToCpu::kNo;
252 }
253 bool success = fQueueManager->submitToGpu(submitInfo);
254 this->checkForFinishedWork(submitInfo.fSync);
255 return success;
256 }
257
258 bool Context::hasUnfinishedGpuWork() const { return fQueueManager->hasUnfinishedGpuWork(); }
259
260 template <typename SrcPixels>
261 struct Context::AsyncParams {
262 const SrcPixels* fSrcImage;
263 SkIRect fSrcRect;
264 SkImageInfo fDstImageInfo;
265
266 SkImage::ReadPixelsCallback* fCallback;
267 SkImage::ReadPixelsContext fCallbackContext;
268
269 template <typename S>
270 AsyncParams<S> withNewSource(const S* newPixels, const SkIRect& newSrcRect) const {
271 return AsyncParams<S>{newPixels, newSrcRect,
272 fDstImageInfo, fCallback, fCallbackContext};
273 }
274
275 void fail() const {
276 (*fCallback)(fCallbackContext, nullptr);
277 }
278
279 bool validate() const {
280 if (!fSrcImage) {
281 return false;
282 }
283 // SkImage::isProtected() -> bool, TextureProxy::isProtected() -> Protected enum.
284 // The explicit cast makes this function work for both template instantiations since
285 // the Protected enum is backed by a bool.
286 if ((bool) fSrcImage->isProtected()) {
287 return false;
288 }
289 if (!SkIRect::MakeSize(fSrcImage->dimensions()).contains(fSrcRect)) {
290 return false;
291 }
292 if (!SkImageInfoIsValid(fDstImageInfo)) {
293 return false;
294 }
295 return true;
296 }
297 };
298
299 template <typename ReadFn, typename... ExtraArgs>
300 void Context::asyncRescaleAndReadImpl(ReadFn Context::* asyncRead,
301 SkImage::RescaleGamma rescaleGamma,
302 SkImage::RescaleMode rescaleMode,
303 const AsyncParams<SkImage>& params,
304 ExtraArgs... extraParams) {
305 if (!params.validate()) {
306 return params.fail();
307 }
308
309 if (params.fSrcRect.size() == params.fDstImageInfo.dimensions()) {
310 // No need to rescale so do a direct readback
311 return (this->*asyncRead)(/*recorder=*/nullptr, params, extraParams...);
312 }
313
314 // Make a recorder to collect the rescale drawing commands and the copy commands
315 std::unique_ptr<Recorder> recorder = this->makeInternalRecorder();
316 sk_sp<SkImage> scaledImage = RescaleImage(recorder.get(),
317 params.fSrcImage,
318 params.fSrcRect,
319 params.fDstImageInfo,
320 rescaleGamma,
321 rescaleMode);
322 if (!scaledImage) {
323 SKGPU_LOG_W("AsyncRead failed because rescaling failed");
324 return params.fail();
325 }
326 (this->*asyncRead)(std::move(recorder),
327 params.withNewSource(scaledImage.get(), params.fDstImageInfo.bounds()),
328 extraParams...);
329 }
330
331 void Context::asyncRescaleAndReadPixels(const SkImage* src,
332 const SkImageInfo& dstImageInfo,
333 const SkIRect& srcRect,
334 SkImage::RescaleGamma rescaleGamma,
335 SkImage::RescaleMode rescaleMode,
336 SkImage::ReadPixelsCallback callback,
337 SkImage::ReadPixelsContext callbackContext) {
338 this->asyncRescaleAndReadImpl(&Context::asyncReadPixels,
339 rescaleGamma, rescaleMode,
340 {src, srcRect, dstImageInfo, callback, callbackContext});
341 }
342
343 void Context::asyncRescaleAndReadPixels(const SkSurface* src,
344 const SkImageInfo& dstImageInfo,
345 const SkIRect& srcRect,
346 SkImage::RescaleGamma rescaleGamma,
347 SkImage::RescaleMode rescaleMode,
348 SkImage::ReadPixelsCallback callback,
349 SkImage::ReadPixelsContext callbackContext) {
350 sk_sp<SkImage> surfaceImage = SkSurfaces::AsImage(sk_ref_sp(src));
351 if (!surfaceImage) {
352 // The source surface is not texturable, so the only supported readback is if there's
353 // no rescaling
354 if (src && asConstSB(src)->isGraphiteBacked() &&
355 srcRect.size() == dstImageInfo.dimensions()) {
356 TextureProxy* proxy = static_cast<const Surface*>(src)->backingTextureProxy();
357 return this->asyncReadTexture(/*recorder=*/nullptr,
358 {proxy, srcRect, dstImageInfo, callback, callbackContext},
359 src->imageInfo().colorInfo());
360 }
361 // else fall through and let asyncRescaleAndReadPixels() invoke the callback when it detects
362 // the null image.
363 }
364 this->asyncRescaleAndReadPixels(surfaceImage.get(),
365 dstImageInfo,
366 srcRect,
367 rescaleGamma,
368 rescaleMode,
369 callback,
370 callbackContext);
371 }
372
373 void Context::asyncReadPixels(std::unique_ptr<Recorder> recorder,
374 const AsyncParams<SkImage>& params) {
375 TRACE_EVENT2("skia.gpu", TRACE_FUNC,
376 "width", params.fSrcRect.width(),
377 "height", params.fSrcRect.height());
378 SkASSERT(params.validate()); // all paths to here are already validated
379 SkASSERT(params.fSrcRect.size() == params.fDstImageInfo.dimensions());
380
381 const Caps* caps = fSharedContext->caps();
382 TextureProxyView view = AsView(params.fSrcImage);
383 if (!view || !caps->supportsReadPixels(view.proxy()->textureInfo())) {
384 // This is either a YUVA image (null view) or the texture can't be read directly, so
385 // perform a draw into a compatible texture format and/or flatten any YUVA planes to RGBA.
386 if (!recorder) {
387 recorder = this->makeInternalRecorder();
388 }
389 sk_sp<SkImage> flattened = CopyAsDraw(recorder.get(),
390 /*drawContext=*/nullptr,
391 params.fSrcImage,
392 params.fSrcRect,
393 params.fDstImageInfo.colorInfo(),
394 Budgeted::kYes,
395 Mipmapped::kNo,
396 SkBackingFit::kApprox,
397 "AsyncReadPixelsFallbackTexture");
398 if (!flattened) {
399 SKGPU_LOG_W("AsyncRead failed because copy-as-drawing into a readable format failed");
400 return params.fail();
401 }
402 // Use the original fSrcRect and not flattened's size since it's approx-fit.
403 return this->asyncReadPixels(std::move(recorder),
404 params.withNewSource(flattened.get(),
405 SkIRect::MakeSize(params.fSrcRect.size())));
406 }
407
408 // Can copy directly from the image's texture
409 this->asyncReadTexture(std::move(recorder), params.withNewSource(view.proxy(), params.fSrcRect),
410 params.fSrcImage->imageInfo().colorInfo());
411 }
412
413 void Context::asyncReadTexture(std::unique_ptr<Recorder> recorder,
414 const AsyncParams<TextureProxy>& params,
415 const SkColorInfo& srcColorInfo) {
416 SkASSERT(params.fSrcRect.size() == params.fDstImageInfo.dimensions());
417
418 // We can get here directly from surface or testing-only read pixels, so re-validate
419 if (!params.validate()) {
420 return params.fail();
421 }
422 PixelTransferResult transferResult = this->transferPixels(recorder.get(),
423 params.fSrcImage,
424 srcColorInfo,
425 params.fDstImageInfo.colorInfo(),
426 params.fSrcRect);
427
428 if (!transferResult.fTransferBuffer) {
429 // TODO: try to do a synchronous readPixels instead
430 return params.fail();
431 }
432
433 this->finalizeAsyncReadPixels(std::move(recorder),
434 {&transferResult, 1},
435 params.fCallback,
436 params.fCallbackContext);
437 }
438
439 void Context::asyncRescaleAndReadPixelsYUV420(const SkImage* src,
440 SkYUVColorSpace yuvColorSpace,
441 sk_sp<SkColorSpace> dstColorSpace,
442 const SkIRect& srcRect,
443 const SkISize& dstSize,
444 SkImage::RescaleGamma rescaleGamma,
445 SkImage::RescaleMode rescaleMode,
446 SkImage::ReadPixelsCallback callback,
447 SkImage::ReadPixelsContext callbackContext) {
448 // Use kOpaque alpha type to signal that we don't read back the alpha channel
449 SkImageInfo dstImageInfo = SkImageInfo::Make(dstSize,
450 kRGBA_8888_SkColorType,
451 kOpaque_SkAlphaType,
452 std::move(dstColorSpace));
453 this->asyncRescaleAndReadImpl(&Context::asyncReadPixelsYUV420,
454 rescaleGamma, rescaleMode,
455 {src, srcRect, dstImageInfo, callback, callbackContext},
456 yuvColorSpace);
457 }
458
459 void Context::asyncRescaleAndReadPixelsYUV420(const SkSurface* src,
460 SkYUVColorSpace yuvColorSpace,
461 sk_sp<SkColorSpace> dstColorSpace,
462 const SkIRect& srcRect,
463 const SkISize& dstSize,
464 SkImage::RescaleGamma rescaleGamma,
465 SkImage::RescaleMode rescaleMode,
466 SkImage::ReadPixelsCallback callback,
467 SkImage::ReadPixelsContext callbackContext) {
468 // YUV[A] readback requires the surface to be texturable since the plane conversion is performed
469 // by draws. If AsImage() returns null, the image version of asyncRescaleAndReadback will
470 // automatically fail.
471 // TODO: Is it worth performing an extra copy from 'surface' into a texture in order to succeed?
472 sk_sp<SkImage> surfaceImage = SkSurfaces::AsImage(sk_ref_sp(src));
473 this->asyncRescaleAndReadPixelsYUV420(surfaceImage.get(),
474 yuvColorSpace,
475 dstColorSpace,
476 srcRect,
477 dstSize,
478 rescaleGamma,
479 rescaleMode,
480 callback,
481 callbackContext);
482 }
483
484 void Context::asyncRescaleAndReadPixelsYUVA420(const SkImage* src,
485 SkYUVColorSpace yuvColorSpace,
486 sk_sp<SkColorSpace> dstColorSpace,
487 const SkIRect& srcRect,
488 const SkISize& dstSize,
489 SkImage::RescaleGamma rescaleGamma,
490 SkImage::RescaleMode rescaleMode,
491 SkImage::ReadPixelsCallback callback,
492 SkImage::ReadPixelsContext callbackContext) {
493 SkImageInfo dstImageInfo = SkImageInfo::Make(dstSize,
494 kRGBA_8888_SkColorType,
495 kPremul_SkAlphaType,
496 std::move(dstColorSpace));
497 this->asyncRescaleAndReadImpl(&Context::asyncReadPixelsYUV420,
498 rescaleGamma, rescaleMode,
499 {src, srcRect, dstImageInfo, callback, callbackContext},
500 yuvColorSpace);
501 }
502
503 void Context::asyncRescaleAndReadPixelsYUVA420(const SkSurface* src,
504 SkYUVColorSpace yuvColorSpace,
505 sk_sp<SkColorSpace> dstColorSpace,
506 const SkIRect& srcRect,
507 const SkISize& dstSize,
508 SkImage::RescaleGamma rescaleGamma,
509 SkImage::RescaleMode rescaleMode,
510 SkImage::ReadPixelsCallback callback,
511 SkImage::ReadPixelsContext callbackContext) {
512 sk_sp<SkImage> surfaceImage = SkSurfaces::AsImage(sk_ref_sp(src));
513 this->asyncRescaleAndReadPixelsYUVA420(surfaceImage.get(),
514 yuvColorSpace,
515 dstColorSpace,
516 srcRect,
517 dstSize,
518 rescaleGamma,
519 rescaleMode,
520 callback,
521 callbackContext);
522 }
523
524 void Context::asyncReadPixelsYUV420(std::unique_ptr<Recorder> recorder,
525 const AsyncParams<SkImage>& params,
526 SkYUVColorSpace yuvColorSpace) {
527 TRACE_EVENT2("skia.gpu", TRACE_FUNC,
528 "width", params.fSrcRect.width(),
529 "height", params.fSrcRect.height());
530 // This is only called by asyncRescaleAndReadImpl which already validates its parameters
531 SkASSERT(params.validate());
532 SkASSERT(params.fSrcRect.size() == params.fDstImageInfo.dimensions());
533
534 // The planes are always extracted via drawing, so create the Recorder if there isn't one yet.
535 if (!recorder) {
536 recorder = this->makeInternalRecorder();
537 }
538
539 // copyPlane renders the source image into an A8 image and sets up a transfer stored in 'result'
540 auto copyPlane = [&](SkImageInfo planeInfo,
541 std::string_view label,
542 float rgb2yuv[20],
543 const SkMatrix& texMatrix,
544 PixelTransferResult* result) {
545 sk_sp<Surface> dstSurface = Surface::MakeScratch(recorder.get(),
546 planeInfo,
547 label,
548 Budgeted::kYes,
549 Mipmapped::kNo,
550 SkBackingFit::kApprox);
551 if (!dstSurface) {
552 return false;
553 }
554
555 // Render the plane defined by rgb2yuv from srcImage into dstSurface
556 SkPaint paint;
557 const SkSamplingOptions sampling(SkFilterMode::kLinear, SkMipmapMode::kNone);
558 sk_sp<SkShader> imgShader = params.fSrcImage->makeShader(
559 SkTileMode::kClamp, SkTileMode::kClamp, sampling, texMatrix);
560 paint.setShader(std::move(imgShader));
561 paint.setBlendMode(SkBlendMode::kSrc);
562
563 if (rgb2yuv) {
564 // NOTE: The dstSurface's color space is set to the requested RGB dstColorSpace, so
565 // the rendered image is automatically converted to that RGB color space before the
566 // RGB->YUV color filter is evaluated, putting the plane data into the alpha channel.
567 paint.setColorFilter(SkColorFilters::Matrix(rgb2yuv));
568 }
569
570 SkCanvas* canvas = dstSurface->getCanvas();
571 canvas->drawPaint(paint);
572
573 // Manually flush the surface before transferPixels() is called to ensure the rendering
574 // operations run before the CopyTextureToBuffer task.
575 Flush(dstSurface);
576 // Must use planeInfo.bounds() for srcRect since dstSurface is kApprox-fit.
577 *result = this->transferPixels(recorder.get(),
578 dstSurface->backingTextureProxy(),
579 dstSurface->imageInfo().colorInfo(),
580 planeInfo.colorInfo(),
581 planeInfo.bounds());
582 return SkToBool(result->fTransferBuffer);
583 };
584
585 // Set up draws and transfers. This interleaves the drawing to a plane and the copy to the
586 // transfer buffer, which will allow the scratch A8 surface to be reused for each plane.
587 // TODO: Use one transfer buffer for all three planes to reduce map/unmap cost?
588 const bool readAlpha = params.fDstImageInfo.colorInfo().alphaType() != kOpaque_SkAlphaType;
589 SkImageInfo yaInfo = params.fDstImageInfo.makeColorType(kAlpha_8_SkColorType)
590 .makeAlphaType(kPremul_SkAlphaType);
591 SkImageInfo uvInfo = yaInfo.makeWH(yaInfo.width()/2, yaInfo.height()/2);
592 PixelTransferResult transfers[4];
593
594 float baseM[20];
595 SkColorMatrix_RGB2YUV(yuvColorSpace, baseM);
596 SkMatrix texMatrix = SkMatrix::Translate(-params.fSrcRect.fLeft, -params.fSrcRect.fTop);
597
598 // This matrix generates (r,g,b,a) = (0, 0, 0, y)
599 float yM[20];
600 std::fill_n(yM, 15, 0.f);
601 std::copy_n(baseM + 0, 5, yM + 15);
602 if (!copyPlane(yaInfo, "AsyncReadPixelsYPlane", yM, texMatrix, &transfers[0])) {
603 return params.fail();
604 }
605
606 // No matrix, straight copy of alpha channel
607 SkASSERT(baseM[15] == 0 &&
608 baseM[16] == 0 &&
609 baseM[17] == 0 &&
610 baseM[18] == 1 &&
611 baseM[19] == 0);
612 if (readAlpha &&
613 !copyPlane(yaInfo, "AsyncReadPixelsAPlane", nullptr, texMatrix, &transfers[3])) {
614 return params.fail();
615 }
616
617 // The UV planes are at half resolution compared to Y and A in 4:2:0
618 texMatrix.postScale(0.5f, 0.5f);
619
620 // This matrix generates (r,g,b,a) = (0, 0, 0, u)
621 float uM[20];
622 std::fill_n(uM, 15, 0.f);
623 std::copy_n(baseM + 5, 5, uM + 15);
624 if (!copyPlane(uvInfo, "AsyncReadPixelsUPlane", uM, texMatrix, &transfers[1])) {
625 return params.fail();
626 }
627
628 // This matrix generates (r,g,b,a) = (0, 0, 0, v)
629 float vM[20];
630 std::fill_n(vM, 15, 0.f);
631 std::copy_n(baseM + 10, 5, vM + 15);
632 if (!copyPlane(uvInfo, "AsyncReadPixelsVPlane", vM, texMatrix, &transfers[2])) {
633 return params.fail();
634 }
635
636 this->finalizeAsyncReadPixels(std::move(recorder),
637 {transfers, readAlpha ? 4u : 3u},
638 params.fCallback,
639 params.fCallbackContext);
640 }
641
642 void Context::finalizeAsyncReadPixels(std::unique_ptr<Recorder> recorder,
643 SkSpan<PixelTransferResult> transferResults,
644 SkImage::ReadPixelsCallback callback,
645 SkImage::ReadPixelsContext callbackContext) {
646 // If the async readback work required a Recorder, insert the recording with all of the
647 // accumulated work (which includes any copies). Otherwise, for pure copy readbacks,
648 // transferPixels() already added the tasks directly to the QueueManager.
649 if (recorder) {
650 std::unique_ptr<Recording> recording = recorder->snap();
651 if (!recording) {
652 callback(callbackContext, nullptr);
653 return;
654 }
655 InsertRecordingInfo recordingInfo;
656 recordingInfo.fRecording = recording.get();
657 if (!this->insertRecording(recordingInfo)) {
658 callback(callbackContext, nullptr);
659 return;
660 }
661 }
662
663 // Set up FinishContext and add transfer commands to queue
664 struct AsyncReadFinishContext {
665 SkImage::ReadPixelsCallback* fClientCallback;
666 SkImage::ReadPixelsContext fClientContext;
667 ClientMappedBufferManager* fMappedBufferManager;
668 std::array<PixelTransferResult, 4> fTransferResults;
669 };
670
671 auto finishContext = std::make_unique<AsyncReadFinishContext>();
672 finishContext->fClientCallback = callback;
673 finishContext->fClientContext = callbackContext;
674 finishContext->fMappedBufferManager = fMappedBufferManager.get();
675
676 SkASSERT(transferResults.size() <= std::size(finishContext->fTransferResults));
677 skia_private::STArray<4, sk_sp<Buffer>> buffersToAsyncMap;
678 for (size_t i = 0; i < transferResults.size(); ++i) {
679 finishContext->fTransferResults[i] = std::move(transferResults[i]);
680 if (fSharedContext->caps()->bufferMapsAreAsync()) {
681 buffersToAsyncMap.push_back(finishContext->fTransferResults[i].fTransferBuffer);
682 }
683 }
684
685 InsertFinishInfo info;
686 info.fFinishedContext = finishContext.release();
687 info.fFinishedProc = [](GpuFinishedContext c, CallbackResult status) {
688 std::unique_ptr<const AsyncReadFinishContext> context(
689 reinterpret_cast<const AsyncReadFinishContext*>(c));
690 using AsyncReadResult = skgpu::TAsyncReadResult<Buffer, ContextID, PixelTransferResult>;
691
692 ClientMappedBufferManager* manager = context->fMappedBufferManager;
693 std::unique_ptr<AsyncReadResult> result;
694 if (status == CallbackResult::kSuccess) {
695 result = std::make_unique<AsyncReadResult>(manager->ownerID());
696 }
697 for (const auto& r : context->fTransferResults) {
698 if (!r.fTransferBuffer) {
699 break;
700 }
701 if (result && !result->addTransferResult(r, r.fSize, r.fRowBytes, manager)) {
702 result.reset();
703 }
704 // If we didn't get this buffer into the mapped buffer manager then make sure it gets
705 // unmapped if it has a pending or completed async map.
706 if (!result && r.fTransferBuffer->isUnmappable()) {
707 r.fTransferBuffer->unmap();
708 }
709 }
710 (*context->fClientCallback)(context->fClientContext, std::move(result));
711 };
712
713 // If addFinishInfo() fails, it invokes the finish callback automatically, which handles all the
714 // required clean up for us, just log an error message. The buffers will never be mapped and
715 // thus don't need an unmap.
716 if (!fQueueManager->addFinishInfo(info, fResourceProvider.get(), buffersToAsyncMap)) {
717 SKGPU_LOG_E("Failed to register finish callbacks for asyncReadPixels.");
718 return;
719 }
720 }
721
722 Context::PixelTransferResult Context::transferPixels(Recorder* recorder,
723 const TextureProxy* srcProxy,
724 const SkColorInfo& srcColorInfo,
725 const SkColorInfo& dstColorInfo,
726 const SkIRect& srcRect) {
727 SkASSERT(SkIRect::MakeSize(srcProxy->dimensions()).contains(srcRect));
728 SkASSERT(SkColorInfoIsValid(dstColorInfo));
729
730 const Caps* caps = fSharedContext->caps();
731 if (!srcProxy || !caps->supportsReadPixels(srcProxy->textureInfo())) {
732 return {};
733 }
734
735 const SkColorType srcColorType = srcColorInfo.colorType();
736 SkColorType supportedColorType;
737 bool isRGB888Format;
738 std::tie(supportedColorType, isRGB888Format) =
739 caps->supportedTransferColorType(srcColorType, srcProxy->textureInfo());
740 if (supportedColorType == kUnknown_SkColorType) {
741 return {};
742 }
743
744 // Fail if read color type does not have all of dstCT's color channels and those missing color
745 // channels are in the src.
746 uint32_t dstChannels = SkColorTypeChannelFlags(dstColorInfo.colorType());
747 uint32_t legalReadChannels = SkColorTypeChannelFlags(supportedColorType);
748 uint32_t srcChannels = SkColorTypeChannelFlags(srcColorType);
749 if ((~legalReadChannels & dstChannels) & srcChannels) {
750 return {};
751 }
752
753 int bpp = isRGB888Format ? 3 : SkColorTypeBytesPerPixel(supportedColorType);
754 size_t rowBytes = caps->getAlignedTextureDataRowBytes(bpp * srcRect.width());
755 size_t size = SkAlignTo(rowBytes * srcRect.height(), caps->requiredTransferBufferAlignment());
756 sk_sp<Buffer> buffer = fResourceProvider->findOrCreateNonShareableBuffer(
757 size, BufferType::kXferGpuToCpu, AccessPattern::kHostVisible, "TransferToCpu");
758 if (!buffer) {
759 return {};
760 }
761
762 // Set up copy task. Since we always use a new buffer the offset can be 0 and we don't need to
763 // worry about aligning it to the required transfer buffer alignment.
764 sk_sp<CopyTextureToBufferTask> copyTask = CopyTextureToBufferTask::Make(sk_ref_sp(srcProxy),
765 srcRect,
766 buffer,
767 /*bufferOffset=*/0,
768 rowBytes);
769 const bool addTasksDirectly = !SkToBool(recorder);
770 Protected contextIsProtected = fSharedContext->isProtected();
771 if (!copyTask || (addTasksDirectly && !fQueueManager->addTask(copyTask.get(),
772 this,
773 contextIsProtected))) {
774 return {};
775 } else if (!addTasksDirectly) {
776 // Add the task to the Recorder instead of the QueueManager if that's been required for
777 // collecting tasks to prepare the copied textures.
778 recorder->priv().add(std::move(copyTask));
779 }
780 sk_sp<SynchronizeToCpuTask> syncTask = SynchronizeToCpuTask::Make(buffer);
781 if (!syncTask || (addTasksDirectly && !fQueueManager->addTask(syncTask.get(),
782 this,
783 contextIsProtected))) {
784 return {};
785 } else if (!addTasksDirectly) {
786 recorder->priv().add(std::move(syncTask));
787 }
788
789 PixelTransferResult result;
790 result.fTransferBuffer = std::move(buffer);
791 result.fSize = srcRect.size();
792 // srcColorInfo describes the texture; readColorInfo describes the result of the copy-to-buffer,
793 // which may be different; dstColorInfo is what we have to transform it into when invoking the
794 // async callbacks.
795 SkColorInfo readColorInfo = srcColorInfo.makeColorType(supportedColorType);
796 if (readColorInfo != dstColorInfo || isRGB888Format) {
797 SkISize dims = srcRect.size();
798 SkImageInfo srcInfo = SkImageInfo::Make(dims, readColorInfo);
799 SkImageInfo dstInfo = SkImageInfo::Make(dims, dstColorInfo);
800 result.fRowBytes = dstInfo.minRowBytes();
801 result.fPixelConverter = [dstInfo, srcInfo, rowBytes, isRGB888Format](
802 void* dst, const void* src) {
803 SkAutoPixmapStorage temp;
804 size_t srcRowBytes = rowBytes;
805 if (isRGB888Format) {
806 temp.alloc(srcInfo);
807 size_t tRowBytes = temp.rowBytes();
808 auto* sRow = reinterpret_cast<const char*>(src);
809 auto* tRow = reinterpret_cast<char*>(temp.writable_addr());
810 for (int y = 0; y < srcInfo.height(); ++y, sRow += srcRowBytes, tRow += tRowBytes) {
811 for (int x = 0; x < srcInfo.width(); ++x) {
812 auto s = sRow + x*3;
813 auto t = tRow + x*sizeof(uint32_t);
814 memcpy(t, s, 3);
815 t[3] = static_cast<char>(0xFF);
816 }
817 }
818 src = temp.addr();
819 srcRowBytes = tRowBytes;
820 }
821 SkAssertResult(SkConvertPixels(dstInfo, dst, dstInfo.minRowBytes(),
822 srcInfo, src, srcRowBytes));
823 };
824 } else {
825 result.fRowBytes = rowBytes;
826 }
827
828 return result;
829 }
830
831 void Context::checkForFinishedWork(SyncToCpu syncToCpu) {
832 ASSERT_SINGLE_OWNER
833
834 fQueueManager->checkForFinishedWork(syncToCpu);
835 fMappedBufferManager->process();
836 // Process the return queue periodically to make sure it doesn't get too big
837 fResourceProvider->forceProcessReturnedResources();
838 fSharedContext->forceProcessReturnedResources();
839 }
840
841 void Context::checkAsyncWorkCompletion() {
842 this->checkForFinishedWork(SyncToCpu::kNo);
843 }
844
845 void Context::deleteBackendTexture(const BackendTexture& texture) {
846 ASSERT_SINGLE_OWNER
847
848 if (!texture.isValid() || texture.backend() != this->backend()) {
849 return;
850 }
851 fResourceProvider->deleteBackendTexture(texture);
852 }
853
854 void Context::freeGpuResources() {
855 ASSERT_SINGLE_OWNER
856
857 this->checkAsyncWorkCompletion();
858
859 fResourceProvider->freeGpuResources();
860 fSharedContext->freeGpuResources();
861 }
862
863 void Context::performDeferredCleanup(std::chrono::milliseconds msNotUsed) {
864 ASSERT_SINGLE_OWNER
865
866 this->checkAsyncWorkCompletion();
867
868 auto purgeTime = skgpu::StdSteadyClock::now() - msNotUsed;
869 fResourceProvider->purgeResourcesNotUsedSince(purgeTime);
870 fSharedContext->purgeResourcesNotUsedSince(purgeTime);
871 }
872
873 size_t Context::currentBudgetedBytes() const {
874 ASSERT_SINGLE_OWNER
875 SkASSERT(fSharedContext->getResourceCacheCurrentBudgetedBytes() == 0);
876 return fResourceProvider->getResourceCacheCurrentBudgetedBytes();
877 }
878
879 size_t Context::currentPurgeableBytes() const {
880 ASSERT_SINGLE_OWNER
881 SkASSERT(fSharedContext->getResourceCacheCurrentPurgeableBytes() == 0);
882 return fResourceProvider->getResourceCacheCurrentPurgeableBytes();
883 }
884
885 size_t Context::maxBudgetedBytes() const {
886 ASSERT_SINGLE_OWNER
887 SkASSERT(fSharedContext->getResourceCacheLimit() == SharedContext::kThreadedSafeResourceBudget);
888 return fResourceProvider->getResourceCacheLimit();
889 }
890
891 void Context::setMaxBudgetedBytes(size_t bytes) {
892 ASSERT_SINGLE_OWNER
893 return fResourceProvider->setResourceCacheLimit(bytes);
894 }
895
896 void Context::dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const {
897 ASSERT_SINGLE_OWNER
898 fResourceProvider->dumpMemoryStatistics(traceMemoryDump);
899 fSharedContext->dumpMemoryStatistics(traceMemoryDump);
900 // TODO: What is the graphite equivalent for the text blob cache and how do we print out its
901 // used bytes here (see Ganesh implementation).
902 }
903
904 bool Context::isDeviceLost() const {
905 return fSharedContext->isDeviceLost();
906 }
907
908 int Context::maxTextureSize() const {
909 return fSharedContext->caps()->maxTextureSize();
910 }
911
912 bool Context::supportsProtectedContent() const {
913 return fSharedContext->isProtected() == Protected::kYes;
914 }
915
916 GpuStatsFlags Context::supportedGpuStats() const {
917 return fSharedContext->caps()->supportedGpuStats();
918 }
919
920 void Context::syncPipelineData(size_t maxSize) {
921 ASSERT_SINGLE_OWNER
922
923 if (fPersistentPipelineStorage) {
924 fSharedContext->syncPipelineData(fPersistentPipelineStorage, maxSize);
925 }
926 }
927
928 void Context::startCapture() {
929 if (fSharedContext->captureManager()) {
930 fSharedContext->captureManager()->toggleCapture(true);
931 }
932 }
933
934 sk_sp<SkCapture> Context::endCapture() {
935 if (fSharedContext->captureManager()) {
936 fSharedContext->captureManager()->toggleCapture(false);
937 return fSharedContext->captureManager()->getLastCapture();
938 }
939 return nullptr;
940 }
941
942 ///////////////////////////////////////////////////////////////////////////////////
943
944 #if defined(GPU_TEST_UTILS)
945 void Context::deregisterRecorder(const Recorder* recorder) {
946 SkAutoMutexExclusive lock(fTestingLock);
947 for (auto it = fTrackedRecorders.begin();
948 it != fTrackedRecorders.end();
949 it++) {
950 if (*it == recorder) {
951 fTrackedRecorders.erase(it);
952 return;
953 }
954 }
955 }
956
957 bool ContextPriv::readPixels(const SkPixmap& pm,
958 const TextureProxy* textureProxy,
959 const SkImageInfo& srcImageInfo,
960 int srcX, int srcY) {
961 auto rect = SkIRect::MakeXYWH(srcX, srcY, pm.width(), pm.height());
962 struct AsyncContext {
963 bool fCalled = false;
964 std::unique_ptr<const SkImage::AsyncReadResult> fResult;
965 } asyncContext;
966
967 auto asyncCallback = [](void* c, std::unique_ptr<const SkImage::AsyncReadResult> out) {
968 auto context = static_cast<AsyncContext*>(c);
969 context->fResult = std::move(out);
970 context->fCalled = true;
971 };
972
973 const SkColorInfo& srcColorInfo = srcImageInfo.colorInfo();
974
975 // This is roughly equivalent to the logic taken in asyncRescaleAndRead(SkSurface) to either
976 // try the image-based readback (with copy-as-draw fallbacks) or read the texture directly
977 // if it supports reading.
978 if (!fContext->fSharedContext->caps()->supportsReadPixels(textureProxy->textureInfo())) {
979 // Since this is a synchronous testing-only API, callers should have flushed any pending
980 // work that modifies this texture proxy already. This means we don't have to worry about
981 // re-wrapping the proxy in a new Image (that wouldn't tbe connected to any Device, etc.).
982 sk_sp<SkImage> image{new Image(TextureProxyView(sk_ref_sp(textureProxy)), srcColorInfo)};
983 Context::AsyncParams<SkImage> params {image.get(), rect, pm.info(),
984 asyncCallback, &asyncContext};
985 if (!params.validate()) {
986 params.fail();
987 } else {
988 fContext->asyncReadPixels(/*recorder=*/nullptr, params);
989 }
990 } else {
991 fContext->asyncReadTexture(/*recorder=*/nullptr,
992 {textureProxy, rect, pm.info(), asyncCallback, &asyncContext},
993 srcImageInfo.colorInfo());
994 }
995
996 if (fContext->fSharedContext->caps()->allowCpuSync()) {
997 fContext->submit(SyncToCpu::kYes);
998 } else {
999 fContext->submit(SyncToCpu::kNo);
1000 if (fContext->fSharedContext->backend() == BackendApi::kDawn) {
1001 while (!asyncContext.fCalled) {
1002 fContext->fSharedContext->deviceTick(fContext);
1003 }
1004 } else {
1005 SK_ABORT("Only Dawn supports non-syncing contexts.");
1006 }
1007 }
1008 SkASSERT(asyncContext.fCalled);
1009 if (!asyncContext.fResult) {
1010 return false;
1011 }
1012 SkRectMemcpy(pm.writable_addr(), pm.rowBytes(), asyncContext.fResult->data(0),
1013 asyncContext.fResult->rowBytes(0), pm.info().minRowBytes(),
1014 pm.height());
1015 return true;
1016 }
1017 #endif // GPU_TEST_UTILS
1018
1019 ///////////////////////////////////////////////////////////////////////////////////
1020
1021 std::unique_ptr<Context> ContextCtorAccessor::MakeContext(
1022 sk_sp<SharedContext> sharedContext,
1023 std::unique_ptr<QueueManager> queueManager,
1024 const ContextOptions& options) {
1025 auto context = std::unique_ptr<Context>(new Context(std::move(sharedContext),
1026 std::move(queueManager),
1027 options));
1028 if (context && context->finishInitialization()) {
1029 return context;
1030 } else {
1031 return nullptr;
1032 }
1033 }
1034
1035 } // namespace skgpu::graphite