blob: 9709cd1d6bf81b5a1688dd24898588736e9deeb6 [file] [log] [blame]
John Reck67b1e2b2020-08-26 13:17:24 -07001/*
2 * Copyright 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
John Reck67b1e2b2020-08-26 13:17:24 -070017#undef LOG_TAG
18#define LOG_TAG "RenderEngine"
19#define ATRACE_TAG ATRACE_TAG_GRAPHICS
20
rnleec6a73642021-06-04 14:16:42 -070021#include "SkiaRenderEngine.h"
22
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070023#include <GrBackendSemaphore.h>
24#include <GrContextOptions.h>
Kevin Lubick4011eb92023-09-12 14:18:19 +000025#include <GrTypes.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070026#include <SkBlendMode.h>
27#include <SkCanvas.h>
28#include <SkColor.h>
29#include <SkColorFilter.h>
30#include <SkColorMatrix.h>
31#include <SkColorSpace.h>
32#include <SkData.h>
33#include <SkGraphics.h>
34#include <SkImage.h>
35#include <SkImageFilters.h>
36#include <SkImageInfo.h>
37#include <SkM44.h>
38#include <SkMatrix.h>
39#include <SkPaint.h>
40#include <SkPath.h>
41#include <SkPoint.h>
42#include <SkPoint3.h>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000043#include <SkRRect.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070044#include <SkRect.h>
45#include <SkRefCnt.h>
46#include <SkRegion.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070047#include <SkRuntimeEffect.h>
48#include <SkSamplingOptions.h>
49#include <SkScalar.h>
50#include <SkShader.h>
51#include <SkShadowUtils.h>
52#include <SkString.h>
53#include <SkSurface.h>
54#include <SkTileMode.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070055#include <android-base/stringprintf.h>
Leon Scroggins IIIdf8166e2024-01-25 15:50:56 -050056#include <common/FlagManager.h>
Vishnu Nair40d80012024-07-13 23:25:06 +000057#include <common/trace.h>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000058#include <gui/FenceMonitor.h>
Sally Qif6918d42023-08-07 15:28:30 -070059#include <include/gpu/ganesh/SkSurfaceGanesh.h>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000060#include <pthread.h>
61#include <src/core/SkTraceEventCommon.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070062#include <sync/sync.h>
63#include <ui/BlurRegion.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070064#include <ui/DebugUtils.h>
65#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070066#include <ui/HdrRenderTypeUtils.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070067
68#include <cmath>
69#include <cstdint>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000070#include <deque>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070071#include <memory>
72#include <numeric>
73
74#include "Cache.h"
75#include "ColorSpaces.h"
Nolan Scobiefc125ec2024-03-11 20:08:27 -040076#include "compat/SkiaGpuContext.h"
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070077#include "filters/BlurFilter.h"
78#include "filters/GaussianBlurFilter.h"
79#include "filters/KawaseBlurFilter.h"
80#include "filters/LinearEffect.h"
Alec Mourif2ea10c2024-05-24 19:13:21 +000081#include "filters/MouriMap.h"
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070082#include "log/log_main.h"
Nolan Scobieca050282024-03-15 13:27:06 -040083#include "skia/compat/SkiaBackendTexture.h"
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070084#include "skia/debug/SkiaCapture.h"
85#include "skia/debug/SkiaMemoryReporter.h"
86#include "skia/filters/StretchShaderFactory.h"
87#include "system/graphics-base-v1.0.h"
88
89namespace {
90
91// Debugging settings
92static const bool kPrintLayerSettings = false;
Nolan Scobie1e06f2d2024-03-21 14:56:38 -040093static const bool kGaneshFlushAfterEveryLayer = kPrintLayerSettings;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070094
95} // namespace
96
97// Utility functions related to SkRect
98
99namespace {
100
101static inline SkRect getSkRect(const android::FloatRect& rect) {
102 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
103}
104
105static inline SkRect getSkRect(const android::Rect& rect) {
106 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
107}
108
109/**
110 * Verifies that common, simple bounds + clip combinations can be converted into
111 * a single RRect draw call returning true if possible. If true the radii parameter
112 * will be filled with the correct radii values that combined with bounds param will
113 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
114 */
115static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
116 const SkRect& insetCrop, const android::vec2& cornerRadius,
117 SkVector radii[4]) {
118 const bool leftEqual = bounds.fLeft == crop.fLeft;
119 const bool topEqual = bounds.fTop == crop.fTop;
120 const bool rightEqual = bounds.fRight == crop.fRight;
121 const bool bottomEqual = bounds.fBottom == crop.fBottom;
122
123 // In the event that the corners of the bounds only partially align with the crop we
124 // need to ensure that the resulting shape can still be represented as a round rect.
125 // In particular the round rect implementation will scale the value of all corner radii
126 // if the sum of the radius along any edge is greater than the length of that edge.
127 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
128 const bool requiredWidth = bounds.width() > (cornerRadius.x * 2);
129 const bool requiredHeight = bounds.height() > (cornerRadius.y * 2);
130 if (!requiredWidth || !requiredHeight) {
131 return false;
132 }
133
134 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
135 // contained within the cropped shape and does not need rounded.
136 // compute the UpperLeft corner radius
137 if (leftEqual && topEqual) {
138 radii[0].set(cornerRadius.x, cornerRadius.y);
139 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
140 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
141 radii[0].set(0, 0);
142 } else {
143 return false;
144 }
145 // compute the UpperRight corner radius
146 if (rightEqual && topEqual) {
147 radii[1].set(cornerRadius.x, cornerRadius.y);
148 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
149 (topEqual && bounds.fRight <= insetCrop.fRight)) {
150 radii[1].set(0, 0);
151 } else {
152 return false;
153 }
154 // compute the BottomRight corner radius
155 if (rightEqual && bottomEqual) {
156 radii[2].set(cornerRadius.x, cornerRadius.y);
157 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
158 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
159 radii[2].set(0, 0);
160 } else {
161 return false;
162 }
163 // compute the BottomLeft corner radius
164 if (leftEqual && bottomEqual) {
165 radii[3].set(cornerRadius.x, cornerRadius.y);
166 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
167 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
168 radii[3].set(0, 0);
169 } else {
170 return false;
171 }
172
173 return true;
174}
175
176static inline std::pair<SkRRect, SkRRect> getBoundsAndClip(const android::FloatRect& boundsRect,
177 const android::FloatRect& cropRect,
178 const android::vec2& cornerRadius) {
179 const SkRect bounds = getSkRect(boundsRect);
180 const SkRect crop = getSkRect(cropRect);
181
182 SkRRect clip;
183 if (cornerRadius.x > 0 && cornerRadius.y > 0) {
184 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
185 if (bounds == crop || crop.isEmpty()) {
186 return {SkRRect::MakeRectXY(bounds, cornerRadius.x, cornerRadius.y), clip};
187 }
188
189 // This makes an effort to speed up common, simple bounds + clip combinations by
190 // converting them to a single RRect draw. It is possible there are other cases
191 // that can be converted.
192 if (crop.contains(bounds)) {
193 const auto insetCrop = crop.makeInset(cornerRadius.x, cornerRadius.y);
194 if (insetCrop.contains(bounds)) {
195 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
196 }
197
198 SkVector radii[4];
199 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
200 SkRRect intersectionBounds;
201 intersectionBounds.setRectRadii(bounds, radii);
202 return {intersectionBounds, clip};
203 }
204 }
205
206 // we didn't hit any of our fast paths so set the clip to the cropRect
207 clip.setRectXY(crop, cornerRadius.x, cornerRadius.y);
208 }
209
210 // if we hit this point then we either don't have rounded corners or we are going to rely
211 // on the clip to round the corners for us
212 return {SkRRect::MakeRect(bounds), clip};
213}
214
215static inline bool layerHasBlur(const android::renderengine::LayerSettings& layer,
216 bool colorTransformModifiesAlpha) {
217 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
218 // return false if the content is opaque and would therefore occlude the blur
219 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
220 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
221 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
222 }
223 return false;
224}
225
226static inline SkColor getSkColor(const android::vec4& color) {
227 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
228}
229
230static inline SkM44 getSkM44(const android::mat4& matrix) {
231 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
232 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
233 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
234 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
235}
236
237static inline SkPoint3 getSkPoint3(const android::vec3& vector) {
238 return SkPoint3::Make(vector.x, vector.y, vector.z);
239}
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700240} // namespace
rnleec6a73642021-06-04 14:16:42 -0700241
John Reck67b1e2b2020-08-26 13:17:24 -0700242namespace android {
243namespace renderengine {
rnleec6a73642021-06-04 14:16:42 -0700244namespace skia {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700245
246using base::StringAppendF;
247
Russell Myers3348c742024-04-29 20:22:42 +0000248std::future<void> SkiaRenderEngine::primeCache(PrimeCacheConfig config) {
249 Cache::primeShaderCache(this, config);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700250 return {};
251}
252
253sk_sp<SkData> SkiaRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
254 // This "cache" does not actually cache anything. It just allows us to
255 // monitor Skia's internal cache. So this method always returns null.
256 return nullptr;
257}
258
259void SkiaRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
260 const SkString& description) {
261 mShadersCachedSinceLastCall++;
262 mTotalShadersCompiled++;
Vishnu Nair40d80012024-07-13 23:25:06 +0000263 SFTRACE_FORMAT("SF cache: %i shaders", mTotalShadersCompiled);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700264}
265
266int SkiaRenderEngine::reportShadersCompiled() {
267 return mSkSLCacheMonitor.totalShadersCompiled();
268}
Leon Scroggins IIIa37ca992022-02-02 18:08:20 -0500269
270void SkiaRenderEngine::setEnableTracing(bool tracingEnabled) {
271 SkAndroidFrameworkTraceUtil::setEnableTracing(tracingEnabled);
rnleec6a73642021-06-04 14:16:42 -0700272}
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700273
Leon Scroggins III696bf932024-01-24 15:21:05 -0500274SkiaRenderEngine::SkiaRenderEngine(Threaded threaded, PixelFormat pixelFormat,
Robin Lee7338bd92024-04-04 14:05:07 +0000275 BlurAlgorithm blurAlgorithm)
Leon Scroggins III696bf932024-01-24 15:21:05 -0500276 : RenderEngine(threaded), mDefaultPixelFormat(pixelFormat) {
Robin Lee7338bd92024-04-04 14:05:07 +0000277 switch (blurAlgorithm) {
278 case BlurAlgorithm::GAUSSIAN: {
279 ALOGD("Background Blurs Enabled (Gaussian algorithm)");
280 mBlurFilter = new GaussianBlurFilter();
281 break;
282 }
283 case BlurAlgorithm::KAWASE: {
284 ALOGD("Background Blurs Enabled (Kawase algorithm)");
285 mBlurFilter = new KawaseBlurFilter();
286 break;
287 }
288 default: {
289 mBlurFilter = nullptr;
290 break;
291 }
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700292 }
Robin Lee7338bd92024-04-04 14:05:07 +0000293
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700294 mCapture = std::make_unique<SkiaCapture>();
295}
296
297SkiaRenderEngine::~SkiaRenderEngine() { }
298
Nolan Scobie2526b2f2024-04-16 15:12:22 -0400299// To be called from backend dtors. Used to clean up Skia objects before GPU API contexts are
300// destroyed by subclasses.
301void SkiaRenderEngine::finishRenderingAndAbandonContexts() {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700302 std::lock_guard<std::mutex> lock(mRenderingMutex);
303
304 if (mBlurFilter) {
305 delete mBlurFilter;
306 }
307
Nolan Scobie2526b2f2024-04-16 15:12:22 -0400308 // Leftover textures may hold refs to backend-specific Skia contexts, which must be released
309 // before ~SkiaGpuContext is called.
310 mTextureCleanupMgr.setDeferredStatus(false);
311 mTextureCleanupMgr.cleanup();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700312
Nolan Scobie2526b2f2024-04-16 15:12:22 -0400313 // ~SkiaGpuContext must be called before GPU API contexts are torn down.
314 mContext.reset();
315 mProtectedContext.reset();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700316}
317
318void SkiaRenderEngine::useProtectedContext(bool useProtectedContext) {
319 if (useProtectedContext == mInProtectedContext ||
320 (useProtectedContext && !supportsProtectedContent())) {
321 return;
322 }
323
324 // release any scratch resources before switching into a new mode
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400325 if (getActiveContext()) {
326 getActiveContext()->purgeUnlockedScratchResources();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700327 }
328
329 // Backend-specific way to switch to protected context
330 if (useProtectedContextImpl(
331 useProtectedContext ? GrProtected::kYes : GrProtected::kNo)) {
332 mInProtectedContext = useProtectedContext;
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400333 // given that we are sharing the same thread between two contexts we need to
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700334 // make sure that the thread state is reset when switching between the two.
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400335 if (getActiveContext()) {
336 getActiveContext()->resetContextIfApplicable();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700337 }
338 }
339}
340
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400341SkiaGpuContext* SkiaRenderEngine::getActiveContext() {
342 return mInProtectedContext ? mProtectedContext.get() : mContext.get();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700343}
344
345static float toDegrees(uint32_t transform) {
346 switch (transform) {
347 case ui::Transform::ROT_90:
348 return 90.0;
349 case ui::Transform::ROT_180:
350 return 180.0;
351 case ui::Transform::ROT_270:
352 return 270.0;
353 default:
354 return 0.0;
355 }
356}
357
358static SkColorMatrix toSkColorMatrix(const android::mat4& matrix) {
359 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
360 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
361 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
362 matrix[3][3], 0);
363}
364
365static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
366 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
367 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
368
369 // Treat unsupported dataspaces as srgb
370 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
371 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
372 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
373 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
374 }
375
376 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
377 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
378 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
379 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
380 }
381
382 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
383 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
384 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
385 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
386
387 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
388 sourceTransfer != destTransfer;
389}
390
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400391void SkiaRenderEngine::ensureContextsCreated() {
392 if (mContext) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700393 return;
394 }
395
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400396 std::tie(mContext, mProtectedContext) = createContexts();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700397}
398
399void SkiaRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
400 bool isRenderable) {
Ian Elliott1f0911e2022-09-09 16:31:47 -0600401 // Only run this if RE is running on its own thread. This
Leon Scroggins III696bf932024-01-24 15:21:05 -0500402 // way the access to GL/VK operations is guaranteed to be happening on the
Ian Elliott1f0911e2022-09-09 16:31:47 -0600403 // same thread.
Leon Scroggins III696bf932024-01-24 15:21:05 -0500404 if (!isThreaded()) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700405 return;
406 }
Ian Elliott8506e362023-03-08 12:12:09 -0700407 // We don't attempt to map a buffer if the buffer contains protected content. In GL this is
408 // important because GPU resources for protected buffers are much more limited. (In Vk we
Robert Phillips59f71732023-08-23 15:18:27 -0400409 // simply match the existing behavior for protected buffers.) We also never cache any
410 // buffers while in a protected context.
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700411 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Alec Mouri07196db2023-09-12 23:33:49 +0000412 // Don't attempt to map buffers if we're not gpu sampleable. Callers shouldn't send a buffer
413 // over to RenderEngine.
414 const bool isGpuSampleable = buffer->getUsage() & GRALLOC_USAGE_HW_TEXTURE;
415 if (isProtectedBuffer || isProtected() || !isGpuSampleable) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700416 return;
417 }
Vishnu Nair40d80012024-07-13 23:25:06 +0000418 SFTRACE_CALL();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700419
420 // If we were to support caching protected buffers then we will need to switch the
421 // currently bound context if we are not already using the protected context (and subsequently
Leon Scroggins IIIea458282023-09-05 16:17:04 -0400422 // switch back after the buffer is cached).
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400423 auto context = getActiveContext();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700424 auto& cache = mTextureCache;
425
426 std::lock_guard<std::mutex> lock(mRenderingMutex);
427 mGraphicBufferExternalRefs[buffer->getId()]++;
428
429 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Leon Scroggins IIIdf8166e2024-01-25 15:50:56 -0500430 if (FlagManager::getInstance().renderable_buffer_usage()) {
431 isRenderable = buffer->getUsage() & GRALLOC_USAGE_HW_RENDER;
432 }
Nolan Scobieca050282024-03-15 13:27:06 -0400433 std::unique_ptr<SkiaBackendTexture> backendTexture =
434 context->makeBackendTexture(buffer->toAHardwareBuffer(), isRenderable);
435 auto imageTextureRef =
436 std::make_shared<AutoBackendTexture::LocalRef>(std::move(backendTexture),
437 mTextureCleanupMgr);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700438 cache.insert({buffer->getId(), imageTextureRef});
439 }
440}
441
Alec Mouri92f89fa2023-02-24 00:05:06 +0000442void SkiaRenderEngine::unmapExternalTextureBuffer(sp<GraphicBuffer>&& buffer) {
Vishnu Nair40d80012024-07-13 23:25:06 +0000443 SFTRACE_CALL();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700444 std::lock_guard<std::mutex> lock(mRenderingMutex);
445 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
446 iter != mGraphicBufferExternalRefs.end()) {
447 if (iter->second == 0) {
448 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
449 "> from RenderEngine texture, but the "
450 "ref count was already zero!",
451 buffer->getId());
452 mGraphicBufferExternalRefs.erase(buffer->getId());
453 return;
454 }
455
456 iter->second--;
457
458 // Swap contexts if needed prior to deleting this buffer
459 // See Issue 1 of
460 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
461 // when a protected context and an unprotected context are part of the same share group,
462 // protected surfaces may not be accessed by an unprotected context, implying that protected
463 // surfaces may only be freed when a protected context is active.
464 const bool inProtected = mInProtectedContext;
465 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
466
467 if (iter->second == 0) {
468 mTextureCache.erase(buffer->getId());
469 mGraphicBufferExternalRefs.erase(buffer->getId());
470 }
471
472 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
473 // are up-to-date.
474 if (inProtected != mInProtectedContext) {
475 useProtectedContext(inProtected);
476 }
477 }
478}
479
Ian Elliott8506e362023-03-08 12:12:09 -0700480std::shared_ptr<AutoBackendTexture::LocalRef> SkiaRenderEngine::getOrCreateBackendTexture(
481 const sp<GraphicBuffer>& buffer, bool isOutputBuffer) {
Robert Phillips59f71732023-08-23 15:18:27 -0400482 // Do not lookup the buffer in the cache for protected contexts
483 if (!isProtected()) {
Ian Elliott8506e362023-03-08 12:12:09 -0700484 if (const auto& it = mTextureCache.find(buffer->getId()); it != mTextureCache.end()) {
485 return it->second;
486 }
487 }
Nolan Scobieca050282024-03-15 13:27:06 -0400488 std::unique_ptr<SkiaBackendTexture> backendTexture =
489 getActiveContext()->makeBackendTexture(buffer->toAHardwareBuffer(), isOutputBuffer);
490 return std::make_shared<AutoBackendTexture::LocalRef>(std::move(backendTexture),
491 mTextureCleanupMgr);
Ian Elliott8506e362023-03-08 12:12:09 -0700492}
493
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700494bool SkiaRenderEngine::canSkipPostRenderCleanup() const {
495 std::lock_guard<std::mutex> lock(mRenderingMutex);
496 return mTextureCleanupMgr.isEmpty();
497}
498
499void SkiaRenderEngine::cleanupPostRender() {
Vishnu Nair40d80012024-07-13 23:25:06 +0000500 SFTRACE_CALL();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700501 std::lock_guard<std::mutex> lock(mRenderingMutex);
502 mTextureCleanupMgr.cleanup();
503}
504
505sk_sp<SkShader> SkiaRenderEngine::createRuntimeEffectShader(
506 const RuntimeEffectShaderParameters& parameters) {
507 // The given surface will be stretched by HWUI via matrix transformation
508 // which gets similar results for most surfaces
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000509 // Determine later on if we need to leverage the stretch shader within
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700510 // surface flinger
511 const auto& stretchEffect = parameters.layer.stretchEffect;
Alec Mourif2ea10c2024-05-24 19:13:21 +0000512 const auto& targetBuffer = parameters.layer.source.buffer.buffer;
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000513 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
514
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700515 auto shader = parameters.shader;
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000516 if (graphicBuffer && parameters.shader) {
517 if (stretchEffect.hasEffect()) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700518 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
519 }
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000520 // The given surface requires to be filled outside of its buffer bounds if the edge
521 // extension is required
522 const auto& edgeExtensionEffect = parameters.layer.edgeExtensionEffect;
523 if (edgeExtensionEffect.hasEffect()) {
524 shader = mEdgeExtensionShaderFactory.createSkShader(shader, parameters.layer,
525 parameters.imageBounds);
526 }
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700527 }
528
529 if (parameters.requiresLinearEffect) {
Alec Mourif2ea10c2024-05-24 19:13:21 +0000530 const auto format = targetBuffer != nullptr
531 ? std::optional<ui::PixelFormat>(
532 static_cast<ui::PixelFormat>(targetBuffer->getPixelFormat()))
533 : std::nullopt;
534
Alec Mouria32eade2024-06-25 23:20:51 +0000535 const auto hdrType = getHdrRenderType(parameters.layer.sourceDataspace, format,
536 parameters.layerDimmingRatio);
Alec Mouri77c511c2024-06-24 21:55:46 +0000537
538 const auto usingLocalTonemap =
539 parameters.display.tonemapStrategy == DisplaySettings::TonemapStrategy::Local &&
540 hdrType != HdrRenderType::SDR &&
541 shader->isAImage((SkMatrix*)nullptr, (SkTileMode*)nullptr);
542
543 if (usingLocalTonemap) {
544 static MouriMap kMapper;
545 const float ratio =
546 hdrType == HdrRenderType::GENERIC_HDR ? 1.0f : parameters.layerDimmingRatio;
547 shader = kMapper.mouriMap(getActiveContext(), shader, ratio);
Alec Mouria7e752e2024-05-24 18:21:21 +0000548 }
549
Alec Mouri77c511c2024-06-24 21:55:46 +0000550 // disable tonemapping if we already locally tonemapped
551 auto inputDataspace =
552 usingLocalTonemap ? parameters.outputDataSpace : parameters.layer.sourceDataspace;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700553 auto effect =
Alec Mouri77c511c2024-06-24 21:55:46 +0000554 shaders::LinearEffect{.inputDataspace = inputDataspace,
Sally Qi628ef6e2023-03-30 14:49:03 -0700555 .outputDataspace = parameters.outputDataSpace,
Alec Mourie0bb6f42023-08-02 22:41:52 +0000556 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha,
557 .fakeOutputDataspace = parameters.fakeOutputDataspace};
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700558
559 auto effectIter = mRuntimeEffects.find(effect);
560 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
561 if (effectIter == mRuntimeEffects.end()) {
562 runtimeEffect = buildRuntimeEffect(effect);
563 mRuntimeEffects.insert({effect, runtimeEffect});
564 } else {
565 runtimeEffect = effectIter->second;
566 }
Alec Mouri3e5965f2023-04-07 18:00:58 +0000567
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700568 mat4 colorTransform = parameters.layer.colorTransform;
569
Alec Mouri77c511c2024-06-24 21:55:46 +0000570 if (!usingLocalTonemap) {
571 colorTransform *=
572 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
573 parameters.layerDimmingRatio, 1.f));
574 }
Alec Mouri3e5965f2023-04-07 18:00:58 +0000575
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700576 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouri77c511c2024-06-24 21:55:46 +0000577 return createLinearEffectShader(shader, effect, runtimeEffect, std::move(colorTransform),
578 parameters.display.maxLuminance,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700579 parameters.display.currentLuminanceNits,
580 parameters.layer.source.buffer.maxLuminanceNits,
581 hardwareBuffer, parameters.display.renderIntent);
582 }
Alec Mouri77c511c2024-06-24 21:55:46 +0000583 return shader;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700584}
585
586void SkiaRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
587 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
588 // Record display settings when capture is running.
589 std::stringstream displaySettings;
590 PrintTo(display, &displaySettings);
591 // Store the DisplaySettings in additional information.
592 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
593 SkData::MakeWithCString(displaySettings.str().c_str()));
594 }
595
596 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
597 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
598 // displays might have different scaling when compared to the physical screen.
599
600 canvas->clipRect(getSkRect(display.physicalDisplay));
601 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
602
603 const auto clipWidth = display.clip.width();
604 const auto clipHeight = display.clip.height();
605 auto rotatedClipWidth = clipWidth;
606 auto rotatedClipHeight = clipHeight;
607 // Scale is contingent on the rotation result.
608 if (display.orientation & ui::Transform::ROT_90) {
609 std::swap(rotatedClipWidth, rotatedClipHeight);
610 }
611 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
612 static_cast<SkScalar>(rotatedClipWidth);
613 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
614 static_cast<SkScalar>(rotatedClipHeight);
615 canvas->scale(scaleX, scaleY);
616
617 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
618 // back so that the top left corner of the clip is at (0, 0).
619 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
620 canvas->rotate(toDegrees(display.orientation));
621 canvas->translate(-clipWidth / 2, -clipHeight / 2);
622 canvas->translate(-display.clip.left, -display.clip.top);
623}
624
625class AutoSaveRestore {
626public:
627 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
628 ~AutoSaveRestore() { restore(); }
629 void replace(SkCanvas* canvas) {
630 mCanvas = canvas;
631 mSaveCount = canvas->save();
632 }
633 void restore() {
634 if (mCanvas) {
635 mCanvas->restoreToCount(mSaveCount);
636 mCanvas = nullptr;
637 }
638 }
639
640private:
641 SkCanvas* mCanvas;
642 int mSaveCount;
643};
644
645static SkRRect getBlurRRect(const BlurRegion& region) {
646 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
647 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
648 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
649 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
650 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
651 SkRRect roundedRect;
652 roundedRect.setRectRadii(rect, radii);
653 return roundedRect;
654}
655
656// Arbitrary default margin which should be close enough to zero.
657constexpr float kDefaultMargin = 0.0001f;
658static bool equalsWithinMargin(float expected, float value, float margin = kDefaultMargin) {
659 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
660 return std::abs(expected - value) < margin;
661}
662
663namespace {
664template <typename T>
665void logSettings(const T& t) {
666 std::stringstream stream;
667 PrintTo(t, &stream);
668 auto string = stream.str();
669 size_t pos = 0;
670 // Perfetto ignores \n, so split up manually into separate ALOGD statements.
671 const size_t size = string.size();
672 while (pos < size) {
673 const size_t end = std::min(string.find("\n", pos), size);
674 ALOGD("%s", string.substr(pos, end - pos).c_str());
675 pos = end + 1;
676 }
677}
678} // namespace
679
680// Helper class intended to be used on the stack to ensure that texture cleanup
681// is deferred until after this class goes out of scope.
682class DeferTextureCleanup final {
683public:
684 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
685 mMgr.setDeferredStatus(true);
686 }
687 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
688
689private:
690 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
691 AutoBackendTexture::CleanupManager& mMgr;
692};
693
694void SkiaRenderEngine::drawLayersInternal(
Patrick Williams2e9748f2022-08-09 22:48:18 +0000695 const std::shared_ptr<std::promise<FenceResult>>&& resultPromise,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700696 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
Alec Mourif29700f2023-08-17 21:53:31 +0000697 const std::shared_ptr<ExternalTexture>& buffer, base::unique_fd&& bufferFence) {
Vishnu Nair40d80012024-07-13 23:25:06 +0000698 SFTRACE_FORMAT("%s for %s", __func__, display.namePlusId.c_str());
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700699
700 std::lock_guard<std::mutex> lock(mRenderingMutex);
701
702 if (buffer == nullptr) {
703 ALOGE("No output buffer provided. Aborting GPU composition.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000704 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700705 return;
706 }
707
708 validateOutputBufferUsage(buffer->getBuffer());
709
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400710 auto context = getActiveContext();
Nolan Scobie17ffe902024-03-25 11:07:30 -0400711 LOG_ALWAYS_FATAL_IF(context->isAbandonedOrDeviceLost(),
712 "Context is abandoned/device lost at start of %s", __func__);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700713
714 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
715 DeferTextureCleanup dtc(mTextureCleanupMgr);
716
Ian Elliott8506e362023-03-08 12:12:09 -0700717 auto surfaceTextureRef = getOrCreateBackendTexture(buffer->getBuffer(), true);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700718
719 // wait on the buffer to be ready to use prior to using it
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400720 waitFence(context, bufferFence);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700721
Nolan Scobie17e25512024-03-13 18:02:48 -0400722 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(display.outputDataspace);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700723
724 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
725 if (dstCanvas == nullptr) {
726 ALOGE("Cannot acquire canvas from Skia.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000727 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700728 return;
729 }
730
731 // setup color filter if necessary
732 sk_sp<SkColorFilter> displayColorTransform;
733 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
734 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
735 }
736 const bool ctModifiesAlpha =
737 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
738
739 // Find the max layer white point to determine the max luminance of the scene...
740 const float maxLayerWhitePoint = std::transform_reduce(
741 layers.cbegin(), layers.cend(), 0.f,
742 [](float left, float right) { return std::max(left, right); },
743 [&](const auto& l) { return l.whitePointNits; });
744
745 // ...and compute the dimming ratio if dimming is requested
Alec Mouri5697ad62024-05-24 20:00:52 +0000746 const float displayDimmingRatio = display.targetLuminanceNits > 0.f && maxLayerWhitePoint > 0.f
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700747 ? maxLayerWhitePoint / display.targetLuminanceNits
748 : 1.f;
749
750 // Find if any layers have requested blur, we'll use that info to decide when to render to an
751 // offscreen buffer and when to render to the native buffer.
752 sk_sp<SkSurface> activeSurface(dstSurface);
753 SkCanvas* canvas = dstCanvas;
754 SkiaCapture::OffscreenState offscreenCaptureState;
755 const LayerSettings* blurCompositionLayer = nullptr;
Leon Scroggins IIIf31b4bc2023-08-25 10:40:27 -0400756 if (mBlurFilter) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700757 bool requiresCompositionLayer = false;
758 for (const auto& layer : layers) {
759 // if the layer doesn't have blur or it is not visible then continue
760 if (!layerHasBlur(layer, ctModifiesAlpha)) {
761 continue;
762 }
763 if (layer.backgroundBlurRadius > 0 &&
764 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
765 requiresCompositionLayer = true;
766 }
767 for (auto region : layer.blurRegions) {
768 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
769 requiresCompositionLayer = true;
770 }
771 }
772 if (requiresCompositionLayer) {
773 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
774 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
775 blurCompositionLayer = &layer;
776 break;
777 }
778 }
779 }
780
781 AutoSaveRestore surfaceAutoSaveRestore(canvas);
782 // Clear the entire canvas with a transparent black to prevent ghost images.
783 canvas->clear(SK_ColorTRANSPARENT);
784 initCanvas(canvas, display);
785
786 if (kPrintLayerSettings) {
787 logSettings(display);
788 }
789 for (const auto& layer : layers) {
Vishnu Nair40d80012024-07-13 23:25:06 +0000790 SFTRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700791
792 if (kPrintLayerSettings) {
793 logSettings(layer);
794 }
795
796 sk_sp<SkImage> blurInput;
797 if (blurCompositionLayer == &layer) {
798 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
799 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
800
801 // save a snapshot of the activeSurface to use as input to the blur shaders
802 blurInput = activeSurface->makeImageSnapshot();
803
Leon Scroggins III48a60cc2024-01-31 12:41:33 -0500804 // blit the offscreen framebuffer into the destination AHB. This ensures that
805 // even if the blurred image does not cover the screen (for example, during
806 // a rotation animation, or if blur regions are used), the entire screen is
807 // initialized.
808 if (layer.blurRegions.size() || FlagManager::getInstance().restore_blur_step()) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700809 SkPaint paint;
810 paint.setBlendMode(SkBlendMode::kSrc);
811 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
812 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
813 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
814 String8::format("SurfaceID|%" PRId64, id).c_str(),
815 nullptr);
816 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
817 } else {
818 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
819 }
820 }
821
822 // assign dstCanvas to canvas and ensure that the canvas state is up to date
823 canvas = dstCanvas;
824 surfaceAutoSaveRestore.replace(canvas);
825 initCanvas(canvas, display);
826
827 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
828 dstSurface->getCanvas()->getSaveCount());
829 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
830 dstSurface->getCanvas()->getTotalMatrix());
831
832 // assign dstSurface to activeSurface
833 activeSurface = dstSurface;
834 }
835
836 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
837 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
838 // Record the name of the layer if the capture is running.
839 std::stringstream layerSettings;
840 PrintTo(layer, &layerSettings);
841 // Store the LayerSettings in additional information.
842 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
843 SkData::MakeWithCString(layerSettings.str().c_str()));
844 }
845 // Layers have a local transform that should be applied to them
846 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
847
848 const auto [bounds, roundRectClip] =
849 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
850 layer.geometry.roundedCornersRadius);
Leon Scroggins IIIf31b4bc2023-08-25 10:40:27 -0400851 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700852 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
853
854 // if multiple layers have blur, then we need to take a snapshot now because
855 // only the lowest layer will have blurImage populated earlier
856 if (!blurInput) {
857 blurInput = activeSurface->makeImageSnapshot();
858 }
Leon Scroggins IIIa09cddc2023-07-25 09:34:11 -0400859
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700860 // rect to be blurred in the coordinate space of blurInput
Leon Scroggins IIIa09cddc2023-07-25 09:34:11 -0400861 SkRect blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
862
863 // Some layers may be much bigger than the screen. If we used
864 // `blurRect` directly, this would allocate a large buffer with no
865 // benefit. Apply the clip, which already takes the display size
866 // into account. The clipped size will then be used to calculate the
867 // size of the buffer we will create for blurring.
868 if (!blurRect.intersect(SkRect::Make(canvas->getDeviceClipBounds()))) {
869 // This should not happen, but if it did, we would use the full
870 // sized layer, which should still be fine.
871 ALOGW("blur bounds does not intersect display clip!");
872 }
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700873
874 // if the clip needs to be applied then apply it now and make sure
875 // it is restored before we attempt to draw any shadows.
876 SkAutoCanvasRestore acr(canvas, true);
877 if (!roundRectClip.isEmpty()) {
878 canvas->clipRRect(roundRectClip, true);
879 }
880
881 // TODO(b/182216890): Filter out empty layers earlier
882 if (blurRect.width() > 0 && blurRect.height() > 0) {
883 if (layer.backgroundBlurRadius > 0) {
Vishnu Nair40d80012024-07-13 23:25:06 +0000884 SFTRACE_NAME("BackgroundBlur");
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400885 auto blurredImage = mBlurFilter->generate(context, layer.backgroundBlurRadius,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700886 blurInput, blurRect);
887
888 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
889
890 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
891 blurRect, blurredImage, blurInput);
892 }
893
894 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
895 for (auto region : layer.blurRegions) {
896 if (cachedBlurs[region.blurRadius] == nullptr) {
Vishnu Nair40d80012024-07-13 23:25:06 +0000897 SFTRACE_NAME("BlurRegion");
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700898 cachedBlurs[region.blurRadius] =
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400899 mBlurFilter->generate(context, region.blurRadius, blurInput,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700900 blurRect);
901 }
902
903 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
904 region.alpha, blurRect,
905 cachedBlurs[region.blurRadius], blurInput);
906 }
907 }
908 }
909
910 if (layer.shadow.length > 0) {
911 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
912 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
913
914 SkRRect shadowBounds, shadowClip;
915 if (layer.geometry.boundaries == layer.shadow.boundaries) {
916 shadowBounds = bounds;
917 shadowClip = roundRectClip;
918 } else {
919 std::tie(shadowBounds, shadowClip) =
920 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
921 layer.geometry.roundedCornersRadius);
922 }
923
924 // Technically, if bounds is a rect and roundRectClip is not empty,
925 // it means that the bounds and roundedCornersCrop were different
926 // enough that we should intersect them to find the proper shadow.
927 // In practice, this often happens when the two rectangles appear to
928 // not match due to rounding errors. Draw the rounded version, which
929 // looks more like the intent.
930 const auto& rrect =
931 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
932 drawShadow(canvas, rrect, layer.shadow);
933 }
934
935 const float layerDimmingRatio = layer.whitePointNits <= 0.f
936 ? displayDimmingRatio
937 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
938
939 const bool dimInLinearSpace = display.dimmingStage !=
940 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
941
Sally Qi628ef6e2023-03-30 14:49:03 -0700942 const bool isExtendedHdr = (layer.sourceDataspace & ui::Dataspace::RANGE_MASK) ==
943 static_cast<int32_t>(ui::Dataspace::RANGE_EXTENDED) &&
944 (display.outputDataspace & ui::Dataspace::TRANSFER_MASK) ==
945 static_cast<int32_t>(ui::Dataspace::TRANSFER_SRGB);
946
Alec Mourie0bb6f42023-08-02 22:41:52 +0000947 const bool useFakeOutputDataspaceForRuntimeEffect = !dimInLinearSpace && isExtendedHdr;
948
949 const ui::Dataspace fakeDataspace = useFakeOutputDataspaceForRuntimeEffect
Sally Qi628ef6e2023-03-30 14:49:03 -0700950 ? static_cast<ui::Dataspace>(
951 (display.outputDataspace & ui::Dataspace::STANDARD_MASK) |
952 ui::Dataspace::TRANSFER_GAMMA2_2 |
953 (display.outputDataspace & ui::Dataspace::RANGE_MASK))
Alec Mourie0bb6f42023-08-02 22:41:52 +0000954 : ui::Dataspace::UNKNOWN;
Sally Qi628ef6e2023-03-30 14:49:03 -0700955
956 // If the input dataspace is range extended, the output dataspace transfer is sRGB
957 // and dimmingStage is GAMMA_OETF, dim in linear space instead, and
958 // set the output dataspace's transfer to be GAMMA2_2.
959 // This allows DPU side to use oetf_gamma_2p2 for extended HDR layer
960 // to avoid tone shift.
961 // The reason of tone shift here is because HDR layers manage white point
962 // luminance in linear space, which color pipelines request GAMMA_OETF break
963 // without a gamma 2.2 fixup.
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700964 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
Alec Mouri47bcb072023-08-15 02:02:49 +0000965 (needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
Sally Qi628ef6e2023-03-30 14:49:03 -0700966 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio)) ||
967 (!dimInLinearSpace && isExtendedHdr);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700968
969 // quick abort from drawing the remaining portion of the layer
970 if (layer.skipContentDraw ||
971 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
972 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
973 continue;
974 }
975
Alec Mouri47bcb072023-08-15 02:02:49 +0000976 const ui::Dataspace layerDataspace = layer.sourceDataspace;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700977
978 SkPaint paint;
979 if (layer.source.buffer.buffer) {
Vishnu Nair40d80012024-07-13 23:25:06 +0000980 SFTRACE_NAME("DrawImage");
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700981 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
982 const auto& item = layer.source.buffer;
Ian Elliott8506e362023-03-08 12:12:09 -0700983 auto imageTextureRef = getOrCreateBackendTexture(item.buffer->getBuffer(), false);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700984
985 // if the layer's buffer has a fence, then we must must respect the fence prior to using
986 // the buffer.
987 if (layer.source.buffer.fence != nullptr) {
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400988 waitFence(context, layer.source.buffer.fence->get());
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700989 }
990
991 // isOpaque means we need to ignore the alpha in the image,
992 // replacing it with the alpha specified by the LayerSettings. See
993 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
994 // The proper way to do this is to use an SkColorType that ignores
995 // alpha, like kRGB_888x_SkColorType, and that is used if the
996 // incoming image is kRGBA_8888_SkColorType. However, the incoming
997 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
998 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
999 // kRGB_101010x_SkColorType, but it is not yet supported as a source
1000 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
1001 // meantime, we'll use a workaround that works unless we need to do
1002 // any color conversion. The workaround requires that we pretend the
1003 // image is already premultiplied, so that we do not premultiply it
1004 // before applying SkBlendMode::kPlus.
1005 const bool useIsOpaqueWorkaround = item.isOpaque &&
1006 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
1007 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
1008 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
1009 : item.isOpaque ? kOpaque_SkAlphaType
1010 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
1011 : kUnpremul_SkAlphaType;
Nolan Scobie17e25512024-03-13 18:02:48 -04001012 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001013
1014 auto texMatrix = getSkM44(item.textureTransform).asM33();
1015 // textureTansform was intended to be passed directly into a shader, so when
1016 // building the total matrix with the textureTransform we need to first
1017 // normalize it, then apply the textureTransform, then scale back up.
1018 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
1019 texMatrix.postScale(image->width(), image->height());
1020
1021 SkMatrix matrix;
1022 if (!texMatrix.invert(&matrix)) {
1023 matrix = texMatrix;
1024 }
1025 // The shader does not respect the translation, so we add it to the texture
1026 // transform for the SkImage. This will make sure that the correct layer contents
1027 // are drawn in the correct part of the screen.
1028 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
1029
1030 sk_sp<SkShader> shader;
1031
1032 if (layer.source.buffer.useTextureFiltering) {
1033 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1034 SkSamplingOptions(
1035 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1036 &matrix);
1037 } else {
1038 shader = image->makeShader(SkSamplingOptions(), matrix);
1039 }
1040
1041 if (useIsOpaqueWorkaround) {
1042 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1043 SkShaders::Color(SkColors::kBlack,
1044 toSkColorSpace(layerDataspace)));
1045 }
1046
Marzia Favarodcc9d9b2024-01-10 10:17:00 +00001047 SkRect imageBounds;
1048 matrix.mapRect(&imageBounds, SkRect::Make(image->bounds()));
1049
1050 paint.setShader(createRuntimeEffectShader(RuntimeEffectShaderParameters{
1051 .shader = shader,
1052 .layer = layer,
1053 .display = display,
1054 .undoPremultipliedAlpha = !item.isOpaque && item.usePremultipliedAlpha,
1055 .requiresLinearEffect = requiresLinearEffect,
1056 .layerDimmingRatio = dimInLinearSpace ? layerDimmingRatio : 1.f,
1057 .outputDataSpace = display.outputDataspace,
1058 .fakeOutputDataspace = fakeDataspace,
1059 .imageBounds = imageBounds,
1060 }));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001061
1062 // Turn on dithering when dimming beyond this (arbitrary) threshold...
linkai296566e2024-01-22 20:58:15 +08001063 static constexpr float kDimmingThreshold = 0.9f;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001064 // ...or we're rendering an HDR layer down to an 8-bit target
1065 // Most HDR standards require at least 10-bits of color depth for source content, so we
1066 // can just extract the transfer function rather than dig into precise gralloc layout.
1067 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
Sally Qif6918d42023-08-07 15:28:30 -07001068 const bool requiresDownsample =
1069 getHdrRenderType(layer.sourceDataspace,
1070 std::optional<ui::PixelFormat>(static_cast<ui::PixelFormat>(
1071 buffer->getPixelFormat()))) != HdrRenderType::SDR &&
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001072 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
1073 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
1074 paint.setDither(true);
1075 }
1076 paint.setAlphaf(layer.alpha);
1077
1078 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1079 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
1080
1081 // SysUI creates the alpha layer as a coverage layer, which is
1082 // appropriate for the DPU. Use a color matrix to convert it to
1083 // a mask.
1084 // TODO (b/219525258): Handle input as a mask.
1085 //
1086 // The color matrix will convert A8 pixels with no alpha to
1087 // black, as described by this vector. If the display handles
1088 // the color transform, we need to invert it to find the color
1089 // that will result in black after the DPU applies the transform.
1090 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1091 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1092 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1093 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1094 black = colorSpaceMatrix * black;
1095 } else {
1096 // We'll just have to use 0,0,0 as black, which should
1097 // be close to correct.
1098 ALOGI("Could not invert colorTransform!");
1099 }
1100 }
1101 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1102 0, 0, 0, 0, black[1],
1103 0, 0, 0, 0, black[2],
1104 0, 0, 0, -1, 1);
1105 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1106 // On the other hand, if the device doesn't handle it, we
1107 // have to apply it ourselves.
1108 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1109 }
1110 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
1111 }
1112 } else {
Vishnu Nair40d80012024-07-13 23:25:06 +00001113 SFTRACE_NAME("DrawColor");
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001114 const auto color = layer.source.solidColor;
1115 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1116 .fG = color.g,
1117 .fB = color.b,
1118 .fA = layer.alpha},
1119 toSkColorSpace(layerDataspace));
1120 paint.setShader(createRuntimeEffectShader(
1121 RuntimeEffectShaderParameters{.shader = shader,
1122 .layer = layer,
1123 .display = display,
1124 .undoPremultipliedAlpha = false,
1125 .requiresLinearEffect = requiresLinearEffect,
Sally Qi628ef6e2023-03-30 14:49:03 -07001126 .layerDimmingRatio = layerDimmingRatio,
Alec Mourie0bb6f42023-08-02 22:41:52 +00001127 .outputDataSpace = display.outputDataspace,
Marzia Favarodcc9d9b2024-01-10 10:17:00 +00001128 .fakeOutputDataspace = fakeDataspace,
1129 .imageBounds = SkRect::MakeEmpty()}));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001130 }
1131
1132 if (layer.disableBlending) {
1133 paint.setBlendMode(SkBlendMode::kSrc);
1134 }
1135
1136 // An A8 buffer will already have the proper color filter attached to
1137 // its paint, including the displayColorTransform as needed.
1138 if (!paint.getColorFilter()) {
1139 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1140 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1141 // can assume a gamma 2.2 transfer function.
1142 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1143 const auto gammaCorrectedDimmingRatio =
1144 std::pow(layerDimmingRatio, kInverseGamma22);
1145 auto dimmingMatrix =
1146 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1147 gammaCorrectedDimmingRatio, 1.f));
1148
1149 const auto colorFilter =
1150 SkColorFilters::Matrix(toSkColorMatrix(std::move(dimmingMatrix)));
1151 paint.setColorFilter(displayColorTransform
1152 ? displayColorTransform->makeComposed(colorFilter)
1153 : colorFilter);
1154 } else {
1155 paint.setColorFilter(displayColorTransform);
1156 }
1157 }
1158
1159 if (!roundRectClip.isEmpty()) {
1160 canvas->clipRRect(roundRectClip, true);
1161 }
1162
1163 if (!bounds.isRect()) {
1164 paint.setAntiAlias(true);
1165 canvas->drawRRect(bounds, paint);
1166 } else {
1167 canvas->drawRect(bounds.rect(), paint);
1168 }
Nolan Scobie1e06f2d2024-03-21 14:56:38 -04001169 if (kGaneshFlushAfterEveryLayer) {
Vishnu Nair40d80012024-07-13 23:25:06 +00001170 SFTRACE_NAME("flush surface");
Nolan Scobie1e06f2d2024-03-21 14:56:38 -04001171 // No-op in Graphite. If "flushing" Skia's drawing commands after each layer is desired
1172 // in Graphite, then a graphite::Recording would need to be snapped and tracked for each
1173 // layer, which is likely possible but adds non-trivial complexity (in both bookkeeping
1174 // and refactoring).
Kevin Lubick208e11a2023-05-31 19:34:46 +00001175 skgpu::ganesh::Flush(activeSurface);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001176 }
1177 }
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001178
1179 surfaceAutoSaveRestore.restore();
1180 mCapture->endCapture();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001181
Nolan Scobie1e06f2d2024-03-21 14:56:38 -04001182 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1183 auto drawFence = sp<Fence>::make(flushAndSubmit(context, dstSurface));
Alec Mouri0e7d8fd2023-05-03 23:58:43 +00001184
Vishnu Nair40d80012024-07-13 23:25:06 +00001185 if (SFTRACE_ENABLED()) {
Alec Mouri0e7d8fd2023-05-03 23:58:43 +00001186 static gui::FenceMonitor sMonitor("RE Completion");
1187 sMonitor.queueFence(drawFence);
1188 }
1189 resultPromise->set_value(std::move(drawFence));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001190}
1191
1192size_t SkiaRenderEngine::getMaxTextureSize() const {
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001193 return mContext->getMaxTextureSize();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001194}
1195
1196size_t SkiaRenderEngine::getMaxViewportDims() const {
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001197 return mContext->getMaxRenderTargetSize();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001198}
1199
1200void SkiaRenderEngine::drawShadow(SkCanvas* canvas,
1201 const SkRRect& casterRRect,
1202 const ShadowSettings& settings) {
Vishnu Nair40d80012024-07-13 23:25:06 +00001203 SFTRACE_CALL();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001204 const float casterZ = settings.length / 2.0f;
1205 const auto flags =
1206 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1207
1208 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
1209 getSkPoint3(settings.lightPos), settings.lightRadius,
1210 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1211 flags);
1212}
1213
1214void SkiaRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
1215 // This cache multiplier was selected based on review of cache sizes relative
1216 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1217 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1218 // conservative default based on that analysis.
1219 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1220 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1221
1222 // start by resizing the current context
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001223 getActiveContext()->setResourceCacheLimit(maxResourceBytes);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001224
1225 // if it is possible to switch contexts then we will resize the other context
1226 const bool originalProtectedState = mInProtectedContext;
1227 useProtectedContext(!mInProtectedContext);
1228 if (mInProtectedContext != originalProtectedState) {
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001229 getActiveContext()->setResourceCacheLimit(maxResourceBytes);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001230 // reset back to the initial context that was active when this method was called
1231 useProtectedContext(originalProtectedState);
1232 }
1233}
1234
1235void SkiaRenderEngine::dump(std::string& result) {
1236 // Dump for the specific backend (GLES or Vk)
1237 appendBackendSpecificInfoToDump(result);
1238
1239 // Info about protected content
1240 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1241 supportsProtectedContent());
1242 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1243 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1244 mSkSLCacheMonitor.shadersCachedSinceLastCall());
1245
1246 std::vector<ResourcePair> cpuResourceMap = {
1247 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1248 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1249 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1250 {"skia/sk_resource_cache/tessellated", "Shadows"},
1251 {"skia", "Other"},
1252 };
1253 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1254 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1255 StringAppendF(&result, "Skia CPU Caches: ");
1256 cpuReporter.logTotals(result);
1257 cpuReporter.logOutput(result);
1258
1259 {
1260 std::lock_guard<std::mutex> lock(mRenderingMutex);
1261
1262 std::vector<ResourcePair> gpuResourceMap = {
1263 {"texture_renderbuffer", "Texture/RenderBuffer"},
1264 {"texture", "Texture"},
1265 {"gr_text_blob_cache", "Text"},
1266 {"skia", "Other"},
1267 };
1268 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001269 mContext->dumpMemoryStatistics(&gpuReporter);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001270 StringAppendF(&result, "Skia's GPU Caches: ");
1271 gpuReporter.logTotals(result);
1272 gpuReporter.logOutput(result);
1273 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1274 gpuReporter.logOutput(result, true);
1275
1276 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1277 mGraphicBufferExternalRefs.size());
1278 StringAppendF(&result, "Dumping buffer ids...\n");
1279 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1280 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1281 }
1282 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1283 mTextureCache.size());
1284 StringAppendF(&result, "Dumping buffer ids...\n");
1285 // TODO(178539829): It would be nice to know which layer these are coming from and what
1286 // the texture sizes are.
1287 for (const auto& [id, unused] : mTextureCache) {
1288 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1289 }
1290 StringAppendF(&result, "\n");
1291
1292 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001293 if (mProtectedContext) {
1294 mProtectedContext->dumpMemoryStatistics(&gpuProtectedReporter);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001295 }
1296 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1297 gpuProtectedReporter.logTotals(result);
1298 gpuProtectedReporter.logOutput(result);
1299 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1300 gpuProtectedReporter.logOutput(result, true);
1301
1302 StringAppendF(&result, "\n");
1303 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1304 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1305 StringAppendF(&result, "- inputDataspace: %s\n",
1306 dataspaceDetails(
1307 static_cast<android_dataspace>(linearEffect.inputDataspace))
1308 .c_str());
1309 StringAppendF(&result, "- outputDataspace: %s\n",
1310 dataspaceDetails(
1311 static_cast<android_dataspace>(linearEffect.outputDataspace))
1312 .c_str());
1313 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1314 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1315 }
1316 }
1317 StringAppendF(&result, "\n");
1318}
1319
rnleec6a73642021-06-04 14:16:42 -07001320} // namespace skia
John Reck67b1e2b2020-08-26 13:17:24 -07001321} // namespace renderengine
rnleec6a73642021-06-04 14:16:42 -07001322} // namespace android