blob: 8f232492e9026089a78aef22006d1be17e3296f1 [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 <SkBlendMode.h>
24#include <SkCanvas.h>
25#include <SkColor.h>
26#include <SkColorFilter.h>
27#include <SkColorMatrix.h>
28#include <SkColorSpace.h>
29#include <SkData.h>
30#include <SkGraphics.h>
31#include <SkImage.h>
32#include <SkImageFilters.h>
33#include <SkImageInfo.h>
34#include <SkM44.h>
35#include <SkMatrix.h>
36#include <SkPaint.h>
37#include <SkPath.h>
38#include <SkPoint.h>
39#include <SkPoint3.h>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000040#include <SkRRect.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070041#include <SkRect.h>
42#include <SkRefCnt.h>
43#include <SkRegion.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070044#include <SkRuntimeEffect.h>
45#include <SkSamplingOptions.h>
46#include <SkScalar.h>
47#include <SkShader.h>
48#include <SkShadowUtils.h>
49#include <SkString.h>
50#include <SkSurface.h>
51#include <SkTileMode.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070052#include <android-base/stringprintf.h>
Leon Scroggins IIIdf8166e2024-01-25 15:50:56 -050053#include <common/FlagManager.h>
Vishnu Nair40d80012024-07-13 23:25:06 +000054#include <common/trace.h>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000055#include <gui/FenceMonitor.h>
Nolan Scobiebc3f3602024-08-30 13:51:37 -040056#include <include/gpu/ganesh/GrBackendSemaphore.h>
57#include <include/gpu/ganesh/GrContextOptions.h>
58#include <include/gpu/ganesh/GrTypes.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"
Alec Mouri1b1853f2024-07-15 22:46:58 +000078#include "filters/GainmapFactory.h"
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070079#include "filters/GaussianBlurFilter.h"
Robin Lee26315202021-08-10 22:54:51 +020080#include "filters/KawaseBlurDualFilter.h"
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070081#include "filters/KawaseBlurFilter.h"
82#include "filters/LinearEffect.h"
Alec Mourif2ea10c2024-05-24 19:13:21 +000083#include "filters/MouriMap.h"
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070084#include "log/log_main.h"
Nolan Scobieca050282024-03-15 13:27:06 -040085#include "skia/compat/SkiaBackendTexture.h"
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070086#include "skia/debug/SkiaCapture.h"
87#include "skia/debug/SkiaMemoryReporter.h"
88#include "skia/filters/StretchShaderFactory.h"
89#include "system/graphics-base-v1.0.h"
90
91namespace {
92
93// Debugging settings
94static const bool kPrintLayerSettings = false;
Nolan Scobie1e06f2d2024-03-21 14:56:38 -040095static const bool kGaneshFlushAfterEveryLayer = kPrintLayerSettings;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070096
97} // namespace
98
99// Utility functions related to SkRect
100
101namespace {
102
103static inline SkRect getSkRect(const android::FloatRect& rect) {
104 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
105}
106
107static inline SkRect getSkRect(const android::Rect& rect) {
108 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
109}
110
111/**
112 * Verifies that common, simple bounds + clip combinations can be converted into
113 * a single RRect draw call returning true if possible. If true the radii parameter
114 * will be filled with the correct radii values that combined with bounds param will
115 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
116 */
117static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
118 const SkRect& insetCrop, const android::vec2& cornerRadius,
119 SkVector radii[4]) {
120 const bool leftEqual = bounds.fLeft == crop.fLeft;
121 const bool topEqual = bounds.fTop == crop.fTop;
122 const bool rightEqual = bounds.fRight == crop.fRight;
123 const bool bottomEqual = bounds.fBottom == crop.fBottom;
124
125 // In the event that the corners of the bounds only partially align with the crop we
126 // need to ensure that the resulting shape can still be represented as a round rect.
127 // In particular the round rect implementation will scale the value of all corner radii
128 // if the sum of the radius along any edge is greater than the length of that edge.
129 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
130 const bool requiredWidth = bounds.width() > (cornerRadius.x * 2);
131 const bool requiredHeight = bounds.height() > (cornerRadius.y * 2);
132 if (!requiredWidth || !requiredHeight) {
133 return false;
134 }
135
136 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
137 // contained within the cropped shape and does not need rounded.
138 // compute the UpperLeft corner radius
139 if (leftEqual && topEqual) {
140 radii[0].set(cornerRadius.x, cornerRadius.y);
141 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
142 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
143 radii[0].set(0, 0);
144 } else {
145 return false;
146 }
147 // compute the UpperRight corner radius
148 if (rightEqual && topEqual) {
149 radii[1].set(cornerRadius.x, cornerRadius.y);
150 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
151 (topEqual && bounds.fRight <= insetCrop.fRight)) {
152 radii[1].set(0, 0);
153 } else {
154 return false;
155 }
156 // compute the BottomRight corner radius
157 if (rightEqual && bottomEqual) {
158 radii[2].set(cornerRadius.x, cornerRadius.y);
159 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
160 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
161 radii[2].set(0, 0);
162 } else {
163 return false;
164 }
165 // compute the BottomLeft corner radius
166 if (leftEqual && bottomEqual) {
167 radii[3].set(cornerRadius.x, cornerRadius.y);
168 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
169 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
170 radii[3].set(0, 0);
171 } else {
172 return false;
173 }
174
175 return true;
176}
177
178static inline std::pair<SkRRect, SkRRect> getBoundsAndClip(const android::FloatRect& boundsRect,
179 const android::FloatRect& cropRect,
180 const android::vec2& cornerRadius) {
181 const SkRect bounds = getSkRect(boundsRect);
182 const SkRect crop = getSkRect(cropRect);
183
184 SkRRect clip;
185 if (cornerRadius.x > 0 && cornerRadius.y > 0) {
186 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
187 if (bounds == crop || crop.isEmpty()) {
188 return {SkRRect::MakeRectXY(bounds, cornerRadius.x, cornerRadius.y), clip};
189 }
190
191 // This makes an effort to speed up common, simple bounds + clip combinations by
192 // converting them to a single RRect draw. It is possible there are other cases
193 // that can be converted.
194 if (crop.contains(bounds)) {
195 const auto insetCrop = crop.makeInset(cornerRadius.x, cornerRadius.y);
196 if (insetCrop.contains(bounds)) {
197 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
198 }
199
200 SkVector radii[4];
201 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
202 SkRRect intersectionBounds;
203 intersectionBounds.setRectRadii(bounds, radii);
204 return {intersectionBounds, clip};
205 }
206 }
207
208 // we didn't hit any of our fast paths so set the clip to the cropRect
209 clip.setRectXY(crop, cornerRadius.x, cornerRadius.y);
210 }
211
212 // if we hit this point then we either don't have rounded corners or we are going to rely
213 // on the clip to round the corners for us
214 return {SkRRect::MakeRect(bounds), clip};
215}
216
217static inline bool layerHasBlur(const android::renderengine::LayerSettings& layer,
218 bool colorTransformModifiesAlpha) {
219 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
220 // return false if the content is opaque and would therefore occlude the blur
221 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
222 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
223 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
224 }
225 return false;
226}
227
228static inline SkColor getSkColor(const android::vec4& color) {
229 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
230}
231
232static inline SkM44 getSkM44(const android::mat4& matrix) {
233 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
234 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
235 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
236 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
237}
238
239static inline SkPoint3 getSkPoint3(const android::vec3& vector) {
240 return SkPoint3::Make(vector.x, vector.y, vector.z);
241}
Alec Mouri1b1853f2024-07-15 22:46:58 +0000242
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700243} // namespace
rnleec6a73642021-06-04 14:16:42 -0700244
John Reck67b1e2b2020-08-26 13:17:24 -0700245namespace android {
246namespace renderengine {
rnleec6a73642021-06-04 14:16:42 -0700247namespace skia {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700248
Alec Mouri1b1853f2024-07-15 22:46:58 +0000249namespace {
250void trace(sp<Fence> fence) {
251 if (SFTRACE_ENABLED()) {
252 static gui::FenceMonitor sMonitor("RE Completion");
253 sMonitor.queueFence(std::move(fence));
254 }
255}
256} // namespace
257
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700258using base::StringAppendF;
259
Russell Myers3348c742024-04-29 20:22:42 +0000260std::future<void> SkiaRenderEngine::primeCache(PrimeCacheConfig config) {
261 Cache::primeShaderCache(this, config);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700262 return {};
263}
264
265sk_sp<SkData> SkiaRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
266 // This "cache" does not actually cache anything. It just allows us to
267 // monitor Skia's internal cache. So this method always returns null.
268 return nullptr;
269}
270
271void SkiaRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
272 const SkString& description) {
273 mShadersCachedSinceLastCall++;
274 mTotalShadersCompiled++;
Vishnu Nair40d80012024-07-13 23:25:06 +0000275 SFTRACE_FORMAT("SF cache: %i shaders", mTotalShadersCompiled);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700276}
277
278int SkiaRenderEngine::reportShadersCompiled() {
279 return mSkSLCacheMonitor.totalShadersCompiled();
280}
Leon Scroggins IIIa37ca992022-02-02 18:08:20 -0500281
282void SkiaRenderEngine::setEnableTracing(bool tracingEnabled) {
283 SkAndroidFrameworkTraceUtil::setEnableTracing(tracingEnabled);
rnleec6a73642021-06-04 14:16:42 -0700284}
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700285
Leon Scroggins III696bf932024-01-24 15:21:05 -0500286SkiaRenderEngine::SkiaRenderEngine(Threaded threaded, PixelFormat pixelFormat,
Robin Lee7338bd92024-04-04 14:05:07 +0000287 BlurAlgorithm blurAlgorithm)
Leon Scroggins III696bf932024-01-24 15:21:05 -0500288 : RenderEngine(threaded), mDefaultPixelFormat(pixelFormat) {
Robin Lee7338bd92024-04-04 14:05:07 +0000289 switch (blurAlgorithm) {
290 case BlurAlgorithm::GAUSSIAN: {
291 ALOGD("Background Blurs Enabled (Gaussian algorithm)");
292 mBlurFilter = new GaussianBlurFilter();
293 break;
294 }
295 case BlurAlgorithm::KAWASE: {
296 ALOGD("Background Blurs Enabled (Kawase algorithm)");
297 mBlurFilter = new KawaseBlurFilter();
298 break;
299 }
Robin Lee26315202021-08-10 22:54:51 +0200300 case BlurAlgorithm::KAWASE_DUAL_FILTER: {
301 ALOGD("Background Blurs Enabled (Kawase dual-filtering algorithm)");
302 mBlurFilter = new KawaseBlurDualFilter();
303 break;
304 }
Robin Lee7338bd92024-04-04 14:05:07 +0000305 default: {
306 mBlurFilter = nullptr;
307 break;
308 }
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700309 }
Robin Lee7338bd92024-04-04 14:05:07 +0000310
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700311 mCapture = std::make_unique<SkiaCapture>();
312}
313
314SkiaRenderEngine::~SkiaRenderEngine() { }
315
Nolan Scobie2526b2f2024-04-16 15:12:22 -0400316// To be called from backend dtors. Used to clean up Skia objects before GPU API contexts are
317// destroyed by subclasses.
318void SkiaRenderEngine::finishRenderingAndAbandonContexts() {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700319 std::lock_guard<std::mutex> lock(mRenderingMutex);
320
321 if (mBlurFilter) {
322 delete mBlurFilter;
323 }
324
Nolan Scobie2526b2f2024-04-16 15:12:22 -0400325 // Leftover textures may hold refs to backend-specific Skia contexts, which must be released
326 // before ~SkiaGpuContext is called.
327 mTextureCleanupMgr.setDeferredStatus(false);
328 mTextureCleanupMgr.cleanup();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700329
Nolan Scobie2526b2f2024-04-16 15:12:22 -0400330 // ~SkiaGpuContext must be called before GPU API contexts are torn down.
331 mContext.reset();
332 mProtectedContext.reset();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700333}
334
335void SkiaRenderEngine::useProtectedContext(bool useProtectedContext) {
336 if (useProtectedContext == mInProtectedContext ||
337 (useProtectedContext && !supportsProtectedContent())) {
338 return;
339 }
340
341 // release any scratch resources before switching into a new mode
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400342 if (getActiveContext()) {
343 getActiveContext()->purgeUnlockedScratchResources();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700344 }
345
346 // Backend-specific way to switch to protected context
347 if (useProtectedContextImpl(
348 useProtectedContext ? GrProtected::kYes : GrProtected::kNo)) {
349 mInProtectedContext = useProtectedContext;
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400350 // given that we are sharing the same thread between two contexts we need to
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700351 // make sure that the thread state is reset when switching between the two.
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400352 if (getActiveContext()) {
353 getActiveContext()->resetContextIfApplicable();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700354 }
355 }
356}
357
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400358SkiaGpuContext* SkiaRenderEngine::getActiveContext() {
359 return mInProtectedContext ? mProtectedContext.get() : mContext.get();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700360}
361
362static float toDegrees(uint32_t transform) {
363 switch (transform) {
364 case ui::Transform::ROT_90:
365 return 90.0;
366 case ui::Transform::ROT_180:
367 return 180.0;
368 case ui::Transform::ROT_270:
369 return 270.0;
370 default:
371 return 0.0;
372 }
373}
374
375static SkColorMatrix toSkColorMatrix(const android::mat4& matrix) {
376 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
377 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
378 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
379 matrix[3][3], 0);
380}
381
382static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
383 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
384 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
385
386 // Treat unsupported dataspaces as srgb
387 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
388 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
389 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
390 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
391 }
392
393 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
394 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
395 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
396 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
397 }
398
399 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
400 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
401 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
402 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
403
404 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
405 sourceTransfer != destTransfer;
406}
407
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400408void SkiaRenderEngine::ensureContextsCreated() {
409 if (mContext) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700410 return;
411 }
412
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400413 std::tie(mContext, mProtectedContext) = createContexts();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700414}
415
416void SkiaRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
417 bool isRenderable) {
Ian Elliott1f0911e2022-09-09 16:31:47 -0600418 // Only run this if RE is running on its own thread. This
Leon Scroggins III696bf932024-01-24 15:21:05 -0500419 // way the access to GL/VK operations is guaranteed to be happening on the
Ian Elliott1f0911e2022-09-09 16:31:47 -0600420 // same thread.
Leon Scroggins III696bf932024-01-24 15:21:05 -0500421 if (!isThreaded()) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700422 return;
423 }
Ian Elliott8506e362023-03-08 12:12:09 -0700424 // We don't attempt to map a buffer if the buffer contains protected content. In GL this is
425 // important because GPU resources for protected buffers are much more limited. (In Vk we
Robert Phillips59f71732023-08-23 15:18:27 -0400426 // simply match the existing behavior for protected buffers.) We also never cache any
427 // buffers while in a protected context.
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700428 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Alec Mouri07196db2023-09-12 23:33:49 +0000429 // Don't attempt to map buffers if we're not gpu sampleable. Callers shouldn't send a buffer
430 // over to RenderEngine.
431 const bool isGpuSampleable = buffer->getUsage() & GRALLOC_USAGE_HW_TEXTURE;
432 if (isProtectedBuffer || isProtected() || !isGpuSampleable) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700433 return;
434 }
Vishnu Nair40d80012024-07-13 23:25:06 +0000435 SFTRACE_CALL();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700436
437 // If we were to support caching protected buffers then we will need to switch the
438 // currently bound context if we are not already using the protected context (and subsequently
Leon Scroggins IIIea458282023-09-05 16:17:04 -0400439 // switch back after the buffer is cached).
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400440 auto context = getActiveContext();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700441 auto& cache = mTextureCache;
442
443 std::lock_guard<std::mutex> lock(mRenderingMutex);
444 mGraphicBufferExternalRefs[buffer->getId()]++;
445
446 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Leon Scroggins IIIdf8166e2024-01-25 15:50:56 -0500447 if (FlagManager::getInstance().renderable_buffer_usage()) {
448 isRenderable = buffer->getUsage() & GRALLOC_USAGE_HW_RENDER;
449 }
Nolan Scobieca050282024-03-15 13:27:06 -0400450 std::unique_ptr<SkiaBackendTexture> backendTexture =
451 context->makeBackendTexture(buffer->toAHardwareBuffer(), isRenderable);
452 auto imageTextureRef =
453 std::make_shared<AutoBackendTexture::LocalRef>(std::move(backendTexture),
454 mTextureCleanupMgr);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700455 cache.insert({buffer->getId(), imageTextureRef});
456 }
457}
458
Alec Mouri92f89fa2023-02-24 00:05:06 +0000459void SkiaRenderEngine::unmapExternalTextureBuffer(sp<GraphicBuffer>&& buffer) {
Vishnu Nair40d80012024-07-13 23:25:06 +0000460 SFTRACE_CALL();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700461 std::lock_guard<std::mutex> lock(mRenderingMutex);
462 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
463 iter != mGraphicBufferExternalRefs.end()) {
464 if (iter->second == 0) {
465 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
466 "> from RenderEngine texture, but the "
467 "ref count was already zero!",
468 buffer->getId());
469 mGraphicBufferExternalRefs.erase(buffer->getId());
470 return;
471 }
472
473 iter->second--;
474
475 // Swap contexts if needed prior to deleting this buffer
476 // See Issue 1 of
477 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
478 // when a protected context and an unprotected context are part of the same share group,
479 // protected surfaces may not be accessed by an unprotected context, implying that protected
480 // surfaces may only be freed when a protected context is active.
481 const bool inProtected = mInProtectedContext;
482 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
483
484 if (iter->second == 0) {
485 mTextureCache.erase(buffer->getId());
486 mGraphicBufferExternalRefs.erase(buffer->getId());
487 }
488
489 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
490 // are up-to-date.
491 if (inProtected != mInProtectedContext) {
492 useProtectedContext(inProtected);
493 }
494 }
495}
496
Ian Elliott8506e362023-03-08 12:12:09 -0700497std::shared_ptr<AutoBackendTexture::LocalRef> SkiaRenderEngine::getOrCreateBackendTexture(
498 const sp<GraphicBuffer>& buffer, bool isOutputBuffer) {
Robert Phillips59f71732023-08-23 15:18:27 -0400499 // Do not lookup the buffer in the cache for protected contexts
500 if (!isProtected()) {
Ian Elliott8506e362023-03-08 12:12:09 -0700501 if (const auto& it = mTextureCache.find(buffer->getId()); it != mTextureCache.end()) {
502 return it->second;
503 }
504 }
Nolan Scobieca050282024-03-15 13:27:06 -0400505 std::unique_ptr<SkiaBackendTexture> backendTexture =
506 getActiveContext()->makeBackendTexture(buffer->toAHardwareBuffer(), isOutputBuffer);
507 return std::make_shared<AutoBackendTexture::LocalRef>(std::move(backendTexture),
508 mTextureCleanupMgr);
Ian Elliott8506e362023-03-08 12:12:09 -0700509}
510
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700511bool SkiaRenderEngine::canSkipPostRenderCleanup() const {
512 std::lock_guard<std::mutex> lock(mRenderingMutex);
513 return mTextureCleanupMgr.isEmpty();
514}
515
516void SkiaRenderEngine::cleanupPostRender() {
Vishnu Nair40d80012024-07-13 23:25:06 +0000517 SFTRACE_CALL();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700518 std::lock_guard<std::mutex> lock(mRenderingMutex);
519 mTextureCleanupMgr.cleanup();
520}
521
522sk_sp<SkShader> SkiaRenderEngine::createRuntimeEffectShader(
523 const RuntimeEffectShaderParameters& parameters) {
524 // The given surface will be stretched by HWUI via matrix transformation
525 // which gets similar results for most surfaces
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000526 // Determine later on if we need to leverage the stretch shader within
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700527 // surface flinger
528 const auto& stretchEffect = parameters.layer.stretchEffect;
Alec Mourif2ea10c2024-05-24 19:13:21 +0000529 const auto& targetBuffer = parameters.layer.source.buffer.buffer;
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000530 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
531
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700532 auto shader = parameters.shader;
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000533 if (graphicBuffer && parameters.shader) {
534 if (stretchEffect.hasEffect()) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700535 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
536 }
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000537 // The given surface requires to be filled outside of its buffer bounds if the edge
538 // extension is required
539 const auto& edgeExtensionEffect = parameters.layer.edgeExtensionEffect;
540 if (edgeExtensionEffect.hasEffect()) {
541 shader = mEdgeExtensionShaderFactory.createSkShader(shader, parameters.layer,
542 parameters.imageBounds);
543 }
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700544 }
545
Sally Qief006582024-10-11 13:23:09 -0700546 if (graphicBuffer && parameters.layer.luts) {
Sally Qib658b152024-11-11 19:43:42 -0800547 shader = mLutShader.lutShader(shader, parameters.layer.luts,
548 toSkColorSpace(parameters.outputDataSpace));
Sally Qief006582024-10-11 13:23:09 -0700549 }
550
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700551 if (parameters.requiresLinearEffect) {
Alec Mourif2ea10c2024-05-24 19:13:21 +0000552 const auto format = targetBuffer != nullptr
553 ? std::optional<ui::PixelFormat>(
554 static_cast<ui::PixelFormat>(targetBuffer->getPixelFormat()))
555 : std::nullopt;
556
Alec Mouria32eade2024-06-25 23:20:51 +0000557 const auto hdrType = getHdrRenderType(parameters.layer.sourceDataspace, format,
558 parameters.layerDimmingRatio);
Alec Mouri77c511c2024-06-24 21:55:46 +0000559
560 const auto usingLocalTonemap =
561 parameters.display.tonemapStrategy == DisplaySettings::TonemapStrategy::Local &&
562 hdrType != HdrRenderType::SDR &&
Alec Mouri1b1853f2024-07-15 22:46:58 +0000563 shader->isAImage((SkMatrix*)nullptr, (SkTileMode*)nullptr) &&
564 (hdrType != HdrRenderType::DISPLAY_HDR ||
565 parameters.display.targetHdrSdrRatio < parameters.layerDimmingRatio);
Alec Mouri77c511c2024-06-24 21:55:46 +0000566 if (usingLocalTonemap) {
Alec Mouri1b1853f2024-07-15 22:46:58 +0000567 const float inputRatio =
Alec Mouri77c511c2024-06-24 21:55:46 +0000568 hdrType == HdrRenderType::GENERIC_HDR ? 1.0f : parameters.layerDimmingRatio;
Alec Mouri1b1853f2024-07-15 22:46:58 +0000569 static MouriMap kMapper;
570 shader = kMapper.mouriMap(getActiveContext(), shader, inputRatio,
571 parameters.display.targetHdrSdrRatio);
Alec Mouria7e752e2024-05-24 18:21:21 +0000572 }
573
Alec Mouri77c511c2024-06-24 21:55:46 +0000574 // disable tonemapping if we already locally tonemapped
Sally Qi9cea07c2024-11-18 15:40:03 -0800575 // skip tonemapping if the luts is in use
576 auto inputDataspace = usingLocalTonemap || (graphicBuffer && parameters.layer.luts)
577 ? parameters.outputDataSpace
578 : parameters.layer.sourceDataspace;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700579 auto effect =
Alec Mouri77c511c2024-06-24 21:55:46 +0000580 shaders::LinearEffect{.inputDataspace = inputDataspace,
Sally Qi628ef6e2023-03-30 14:49:03 -0700581 .outputDataspace = parameters.outputDataSpace,
Alec Mourie0bb6f42023-08-02 22:41:52 +0000582 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha,
583 .fakeOutputDataspace = parameters.fakeOutputDataspace};
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700584
585 auto effectIter = mRuntimeEffects.find(effect);
586 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
587 if (effectIter == mRuntimeEffects.end()) {
588 runtimeEffect = buildRuntimeEffect(effect);
589 mRuntimeEffects.insert({effect, runtimeEffect});
590 } else {
591 runtimeEffect = effectIter->second;
592 }
Alec Mouri3e5965f2023-04-07 18:00:58 +0000593
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700594 mat4 colorTransform = parameters.layer.colorTransform;
595
Alec Mouri77c511c2024-06-24 21:55:46 +0000596 if (!usingLocalTonemap) {
597 colorTransform *=
598 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
599 parameters.layerDimmingRatio, 1.f));
600 }
Alec Mouri3e5965f2023-04-07 18:00:58 +0000601
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700602 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouri77c511c2024-06-24 21:55:46 +0000603 return createLinearEffectShader(shader, effect, runtimeEffect, std::move(colorTransform),
604 parameters.display.maxLuminance,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700605 parameters.display.currentLuminanceNits,
606 parameters.layer.source.buffer.maxLuminanceNits,
607 hardwareBuffer, parameters.display.renderIntent);
608 }
Alec Mouri77c511c2024-06-24 21:55:46 +0000609 return shader;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700610}
611
612void SkiaRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
613 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
614 // Record display settings when capture is running.
615 std::stringstream displaySettings;
616 PrintTo(display, &displaySettings);
617 // Store the DisplaySettings in additional information.
618 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
619 SkData::MakeWithCString(displaySettings.str().c_str()));
620 }
621
622 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
623 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
624 // displays might have different scaling when compared to the physical screen.
625
626 canvas->clipRect(getSkRect(display.physicalDisplay));
627 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
628
629 const auto clipWidth = display.clip.width();
630 const auto clipHeight = display.clip.height();
631 auto rotatedClipWidth = clipWidth;
632 auto rotatedClipHeight = clipHeight;
633 // Scale is contingent on the rotation result.
634 if (display.orientation & ui::Transform::ROT_90) {
635 std::swap(rotatedClipWidth, rotatedClipHeight);
636 }
637 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
638 static_cast<SkScalar>(rotatedClipWidth);
639 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
640 static_cast<SkScalar>(rotatedClipHeight);
641 canvas->scale(scaleX, scaleY);
642
643 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
644 // back so that the top left corner of the clip is at (0, 0).
645 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
646 canvas->rotate(toDegrees(display.orientation));
647 canvas->translate(-clipWidth / 2, -clipHeight / 2);
648 canvas->translate(-display.clip.left, -display.clip.top);
649}
650
651class AutoSaveRestore {
652public:
653 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
654 ~AutoSaveRestore() { restore(); }
655 void replace(SkCanvas* canvas) {
656 mCanvas = canvas;
657 mSaveCount = canvas->save();
658 }
659 void restore() {
660 if (mCanvas) {
661 mCanvas->restoreToCount(mSaveCount);
662 mCanvas = nullptr;
663 }
664 }
665
666private:
667 SkCanvas* mCanvas;
668 int mSaveCount;
669};
670
671static SkRRect getBlurRRect(const BlurRegion& region) {
672 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
673 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
674 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
675 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
676 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
677 SkRRect roundedRect;
678 roundedRect.setRectRadii(rect, radii);
679 return roundedRect;
680}
681
682// Arbitrary default margin which should be close enough to zero.
683constexpr float kDefaultMargin = 0.0001f;
684static bool equalsWithinMargin(float expected, float value, float margin = kDefaultMargin) {
685 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
686 return std::abs(expected - value) < margin;
687}
688
689namespace {
690template <typename T>
691void logSettings(const T& t) {
692 std::stringstream stream;
693 PrintTo(t, &stream);
694 auto string = stream.str();
695 size_t pos = 0;
696 // Perfetto ignores \n, so split up manually into separate ALOGD statements.
697 const size_t size = string.size();
698 while (pos < size) {
699 const size_t end = std::min(string.find("\n", pos), size);
700 ALOGD("%s", string.substr(pos, end - pos).c_str());
701 pos = end + 1;
702 }
703}
704} // namespace
705
706// Helper class intended to be used on the stack to ensure that texture cleanup
707// is deferred until after this class goes out of scope.
708class DeferTextureCleanup final {
709public:
710 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
711 mMgr.setDeferredStatus(true);
712 }
713 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
714
715private:
716 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
717 AutoBackendTexture::CleanupManager& mMgr;
718};
719
720void SkiaRenderEngine::drawLayersInternal(
Patrick Williams2e9748f2022-08-09 22:48:18 +0000721 const std::shared_ptr<std::promise<FenceResult>>&& resultPromise,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700722 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
Alec Mourif29700f2023-08-17 21:53:31 +0000723 const std::shared_ptr<ExternalTexture>& buffer, base::unique_fd&& bufferFence) {
Vishnu Nair40d80012024-07-13 23:25:06 +0000724 SFTRACE_FORMAT("%s for %s", __func__, display.namePlusId.c_str());
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700725
726 std::lock_guard<std::mutex> lock(mRenderingMutex);
727
728 if (buffer == nullptr) {
729 ALOGE("No output buffer provided. Aborting GPU composition.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000730 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700731 return;
732 }
733
734 validateOutputBufferUsage(buffer->getBuffer());
735
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400736 auto context = getActiveContext();
Nolan Scobie17ffe902024-03-25 11:07:30 -0400737 LOG_ALWAYS_FATAL_IF(context->isAbandonedOrDeviceLost(),
738 "Context is abandoned/device lost at start of %s", __func__);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700739
740 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
741 DeferTextureCleanup dtc(mTextureCleanupMgr);
742
Ian Elliott8506e362023-03-08 12:12:09 -0700743 auto surfaceTextureRef = getOrCreateBackendTexture(buffer->getBuffer(), true);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700744
745 // wait on the buffer to be ready to use prior to using it
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400746 waitFence(context, bufferFence);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700747
Nolan Scobie17e25512024-03-13 18:02:48 -0400748 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(display.outputDataspace);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700749
750 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
751 if (dstCanvas == nullptr) {
752 ALOGE("Cannot acquire canvas from Skia.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000753 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700754 return;
755 }
756
757 // setup color filter if necessary
758 sk_sp<SkColorFilter> displayColorTransform;
759 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
760 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
761 }
762 const bool ctModifiesAlpha =
763 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
764
765 // Find the max layer white point to determine the max luminance of the scene...
766 const float maxLayerWhitePoint = std::transform_reduce(
767 layers.cbegin(), layers.cend(), 0.f,
768 [](float left, float right) { return std::max(left, right); },
769 [&](const auto& l) { return l.whitePointNits; });
770
771 // ...and compute the dimming ratio if dimming is requested
Alec Mouri5697ad62024-05-24 20:00:52 +0000772 const float displayDimmingRatio = display.targetLuminanceNits > 0.f && maxLayerWhitePoint > 0.f
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700773 ? maxLayerWhitePoint / display.targetLuminanceNits
774 : 1.f;
775
776 // Find if any layers have requested blur, we'll use that info to decide when to render to an
777 // offscreen buffer and when to render to the native buffer.
778 sk_sp<SkSurface> activeSurface(dstSurface);
779 SkCanvas* canvas = dstCanvas;
780 SkiaCapture::OffscreenState offscreenCaptureState;
781 const LayerSettings* blurCompositionLayer = nullptr;
Leon Scroggins IIIf31b4bc2023-08-25 10:40:27 -0400782 if (mBlurFilter) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700783 bool requiresCompositionLayer = false;
784 for (const auto& layer : layers) {
785 // if the layer doesn't have blur or it is not visible then continue
786 if (!layerHasBlur(layer, ctModifiesAlpha)) {
787 continue;
788 }
789 if (layer.backgroundBlurRadius > 0 &&
790 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
791 requiresCompositionLayer = true;
792 }
793 for (auto region : layer.blurRegions) {
794 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
795 requiresCompositionLayer = true;
796 }
797 }
798 if (requiresCompositionLayer) {
799 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
800 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
801 blurCompositionLayer = &layer;
802 break;
803 }
804 }
805 }
806
807 AutoSaveRestore surfaceAutoSaveRestore(canvas);
808 // Clear the entire canvas with a transparent black to prevent ghost images.
809 canvas->clear(SK_ColorTRANSPARENT);
810 initCanvas(canvas, display);
811
812 if (kPrintLayerSettings) {
813 logSettings(display);
814 }
815 for (const auto& layer : layers) {
Vishnu Nair40d80012024-07-13 23:25:06 +0000816 SFTRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700817
818 if (kPrintLayerSettings) {
819 logSettings(layer);
820 }
821
822 sk_sp<SkImage> blurInput;
823 if (blurCompositionLayer == &layer) {
824 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
825 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
826
827 // save a snapshot of the activeSurface to use as input to the blur shaders
828 blurInput = activeSurface->makeImageSnapshot();
829
Leon Scroggins III48a60cc2024-01-31 12:41:33 -0500830 // blit the offscreen framebuffer into the destination AHB. This ensures that
831 // even if the blurred image does not cover the screen (for example, during
832 // a rotation animation, or if blur regions are used), the entire screen is
833 // initialized.
834 if (layer.blurRegions.size() || FlagManager::getInstance().restore_blur_step()) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700835 SkPaint paint;
836 paint.setBlendMode(SkBlendMode::kSrc);
837 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
838 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
839 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
840 String8::format("SurfaceID|%" PRId64, id).c_str(),
841 nullptr);
842 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
843 } else {
844 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
845 }
846 }
847
848 // assign dstCanvas to canvas and ensure that the canvas state is up to date
849 canvas = dstCanvas;
850 surfaceAutoSaveRestore.replace(canvas);
851 initCanvas(canvas, display);
852
853 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
854 dstSurface->getCanvas()->getSaveCount());
855 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
856 dstSurface->getCanvas()->getTotalMatrix());
857
858 // assign dstSurface to activeSurface
859 activeSurface = dstSurface;
860 }
861
862 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
863 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
864 // Record the name of the layer if the capture is running.
865 std::stringstream layerSettings;
866 PrintTo(layer, &layerSettings);
867 // Store the LayerSettings in additional information.
868 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
869 SkData::MakeWithCString(layerSettings.str().c_str()));
870 }
871 // Layers have a local transform that should be applied to them
872 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
873
874 const auto [bounds, roundRectClip] =
875 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
876 layer.geometry.roundedCornersRadius);
Leon Scroggins IIIf31b4bc2023-08-25 10:40:27 -0400877 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700878 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
879
880 // if multiple layers have blur, then we need to take a snapshot now because
881 // only the lowest layer will have blurImage populated earlier
882 if (!blurInput) {
883 blurInput = activeSurface->makeImageSnapshot();
884 }
Leon Scroggins IIIa09cddc2023-07-25 09:34:11 -0400885
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700886 // rect to be blurred in the coordinate space of blurInput
Leon Scroggins IIIa09cddc2023-07-25 09:34:11 -0400887 SkRect blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
888
889 // Some layers may be much bigger than the screen. If we used
890 // `blurRect` directly, this would allocate a large buffer with no
891 // benefit. Apply the clip, which already takes the display size
892 // into account. The clipped size will then be used to calculate the
893 // size of the buffer we will create for blurring.
894 if (!blurRect.intersect(SkRect::Make(canvas->getDeviceClipBounds()))) {
895 // This should not happen, but if it did, we would use the full
896 // sized layer, which should still be fine.
897 ALOGW("blur bounds does not intersect display clip!");
898 }
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700899
900 // if the clip needs to be applied then apply it now and make sure
901 // it is restored before we attempt to draw any shadows.
902 SkAutoCanvasRestore acr(canvas, true);
903 if (!roundRectClip.isEmpty()) {
904 canvas->clipRRect(roundRectClip, true);
905 }
906
907 // TODO(b/182216890): Filter out empty layers earlier
908 if (blurRect.width() > 0 && blurRect.height() > 0) {
909 if (layer.backgroundBlurRadius > 0) {
Vishnu Nair40d80012024-07-13 23:25:06 +0000910 SFTRACE_NAME("BackgroundBlur");
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400911 auto blurredImage = mBlurFilter->generate(context, layer.backgroundBlurRadius,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700912 blurInput, blurRect);
913
914 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
915
916 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
917 blurRect, blurredImage, blurInput);
918 }
919
920 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
921 for (auto region : layer.blurRegions) {
922 if (cachedBlurs[region.blurRadius] == nullptr) {
Vishnu Nair40d80012024-07-13 23:25:06 +0000923 SFTRACE_NAME("BlurRegion");
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700924 cachedBlurs[region.blurRadius] =
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400925 mBlurFilter->generate(context, region.blurRadius, blurInput,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700926 blurRect);
927 }
928
929 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
930 region.alpha, blurRect,
931 cachedBlurs[region.blurRadius], blurInput);
932 }
933 }
934 }
935
936 if (layer.shadow.length > 0) {
937 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
938 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
939
940 SkRRect shadowBounds, shadowClip;
941 if (layer.geometry.boundaries == layer.shadow.boundaries) {
942 shadowBounds = bounds;
943 shadowClip = roundRectClip;
944 } else {
945 std::tie(shadowBounds, shadowClip) =
946 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
947 layer.geometry.roundedCornersRadius);
948 }
949
950 // Technically, if bounds is a rect and roundRectClip is not empty,
951 // it means that the bounds and roundedCornersCrop were different
952 // enough that we should intersect them to find the proper shadow.
953 // In practice, this often happens when the two rectangles appear to
954 // not match due to rounding errors. Draw the rounded version, which
955 // looks more like the intent.
956 const auto& rrect =
957 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
958 drawShadow(canvas, rrect, layer.shadow);
959 }
960
961 const float layerDimmingRatio = layer.whitePointNits <= 0.f
962 ? displayDimmingRatio
963 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
964
965 const bool dimInLinearSpace = display.dimmingStage !=
966 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
967
Sally Qi628ef6e2023-03-30 14:49:03 -0700968 const bool isExtendedHdr = (layer.sourceDataspace & ui::Dataspace::RANGE_MASK) ==
969 static_cast<int32_t>(ui::Dataspace::RANGE_EXTENDED) &&
970 (display.outputDataspace & ui::Dataspace::TRANSFER_MASK) ==
971 static_cast<int32_t>(ui::Dataspace::TRANSFER_SRGB);
972
Alec Mourie0bb6f42023-08-02 22:41:52 +0000973 const bool useFakeOutputDataspaceForRuntimeEffect = !dimInLinearSpace && isExtendedHdr;
974
975 const ui::Dataspace fakeDataspace = useFakeOutputDataspaceForRuntimeEffect
Sally Qi628ef6e2023-03-30 14:49:03 -0700976 ? static_cast<ui::Dataspace>(
977 (display.outputDataspace & ui::Dataspace::STANDARD_MASK) |
978 ui::Dataspace::TRANSFER_GAMMA2_2 |
979 (display.outputDataspace & ui::Dataspace::RANGE_MASK))
Alec Mourie0bb6f42023-08-02 22:41:52 +0000980 : ui::Dataspace::UNKNOWN;
Sally Qi628ef6e2023-03-30 14:49:03 -0700981
982 // If the input dataspace is range extended, the output dataspace transfer is sRGB
983 // and dimmingStage is GAMMA_OETF, dim in linear space instead, and
984 // set the output dataspace's transfer to be GAMMA2_2.
985 // This allows DPU side to use oetf_gamma_2p2 for extended HDR layer
986 // to avoid tone shift.
987 // The reason of tone shift here is because HDR layers manage white point
988 // luminance in linear space, which color pipelines request GAMMA_OETF break
989 // without a gamma 2.2 fixup.
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700990 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
Alec Mouri47bcb072023-08-15 02:02:49 +0000991 (needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
Sally Qi628ef6e2023-03-30 14:49:03 -0700992 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio)) ||
993 (!dimInLinearSpace && isExtendedHdr);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700994
995 // quick abort from drawing the remaining portion of the layer
996 if (layer.skipContentDraw ||
997 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
998 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
999 continue;
1000 }
1001
Alec Mouri47bcb072023-08-15 02:02:49 +00001002 const ui::Dataspace layerDataspace = layer.sourceDataspace;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001003
1004 SkPaint paint;
1005 if (layer.source.buffer.buffer) {
Vishnu Nair40d80012024-07-13 23:25:06 +00001006 SFTRACE_NAME("DrawImage");
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001007 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
1008 const auto& item = layer.source.buffer;
Ian Elliott8506e362023-03-08 12:12:09 -07001009 auto imageTextureRef = getOrCreateBackendTexture(item.buffer->getBuffer(), false);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001010
1011 // if the layer's buffer has a fence, then we must must respect the fence prior to using
1012 // the buffer.
1013 if (layer.source.buffer.fence != nullptr) {
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001014 waitFence(context, layer.source.buffer.fence->get());
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001015 }
1016
1017 // isOpaque means we need to ignore the alpha in the image,
1018 // replacing it with the alpha specified by the LayerSettings. See
1019 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
1020 // The proper way to do this is to use an SkColorType that ignores
1021 // alpha, like kRGB_888x_SkColorType, and that is used if the
1022 // incoming image is kRGBA_8888_SkColorType. However, the incoming
1023 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
1024 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
1025 // kRGB_101010x_SkColorType, but it is not yet supported as a source
1026 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
1027 // meantime, we'll use a workaround that works unless we need to do
1028 // any color conversion. The workaround requires that we pretend the
1029 // image is already premultiplied, so that we do not premultiply it
1030 // before applying SkBlendMode::kPlus.
1031 const bool useIsOpaqueWorkaround = item.isOpaque &&
1032 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
1033 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
1034 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
1035 : item.isOpaque ? kOpaque_SkAlphaType
1036 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
1037 : kUnpremul_SkAlphaType;
Nolan Scobie17e25512024-03-13 18:02:48 -04001038 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001039
1040 auto texMatrix = getSkM44(item.textureTransform).asM33();
1041 // textureTansform was intended to be passed directly into a shader, so when
1042 // building the total matrix with the textureTransform we need to first
1043 // normalize it, then apply the textureTransform, then scale back up.
1044 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
1045 texMatrix.postScale(image->width(), image->height());
1046
1047 SkMatrix matrix;
1048 if (!texMatrix.invert(&matrix)) {
1049 matrix = texMatrix;
1050 }
1051 // The shader does not respect the translation, so we add it to the texture
1052 // transform for the SkImage. This will make sure that the correct layer contents
1053 // are drawn in the correct part of the screen.
1054 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
1055
1056 sk_sp<SkShader> shader;
1057
1058 if (layer.source.buffer.useTextureFiltering) {
1059 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1060 SkSamplingOptions(
1061 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1062 &matrix);
1063 } else {
1064 shader = image->makeShader(SkSamplingOptions(), matrix);
1065 }
1066
1067 if (useIsOpaqueWorkaround) {
1068 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1069 SkShaders::Color(SkColors::kBlack,
1070 toSkColorSpace(layerDataspace)));
1071 }
1072
Marzia Favarodcc9d9b2024-01-10 10:17:00 +00001073 SkRect imageBounds;
1074 matrix.mapRect(&imageBounds, SkRect::Make(image->bounds()));
1075
1076 paint.setShader(createRuntimeEffectShader(RuntimeEffectShaderParameters{
1077 .shader = shader,
1078 .layer = layer,
1079 .display = display,
1080 .undoPremultipliedAlpha = !item.isOpaque && item.usePremultipliedAlpha,
1081 .requiresLinearEffect = requiresLinearEffect,
1082 .layerDimmingRatio = dimInLinearSpace ? layerDimmingRatio : 1.f,
1083 .outputDataSpace = display.outputDataspace,
1084 .fakeOutputDataspace = fakeDataspace,
1085 .imageBounds = imageBounds,
1086 }));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001087
1088 // Turn on dithering when dimming beyond this (arbitrary) threshold...
linkai296566e2024-01-22 20:58:15 +08001089 static constexpr float kDimmingThreshold = 0.9f;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001090 // ...or we're rendering an HDR layer down to an 8-bit target
1091 // Most HDR standards require at least 10-bits of color depth for source content, so we
1092 // can just extract the transfer function rather than dig into precise gralloc layout.
1093 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
Sally Qif6918d42023-08-07 15:28:30 -07001094 const bool requiresDownsample =
1095 getHdrRenderType(layer.sourceDataspace,
1096 std::optional<ui::PixelFormat>(static_cast<ui::PixelFormat>(
1097 buffer->getPixelFormat()))) != HdrRenderType::SDR &&
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001098 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
1099 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
1100 paint.setDither(true);
1101 }
1102 paint.setAlphaf(layer.alpha);
1103
1104 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1105 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
1106
1107 // SysUI creates the alpha layer as a coverage layer, which is
1108 // appropriate for the DPU. Use a color matrix to convert it to
1109 // a mask.
1110 // TODO (b/219525258): Handle input as a mask.
1111 //
1112 // The color matrix will convert A8 pixels with no alpha to
1113 // black, as described by this vector. If the display handles
1114 // the color transform, we need to invert it to find the color
1115 // that will result in black after the DPU applies the transform.
1116 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1117 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1118 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1119 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1120 black = colorSpaceMatrix * black;
1121 } else {
1122 // We'll just have to use 0,0,0 as black, which should
1123 // be close to correct.
1124 ALOGI("Could not invert colorTransform!");
1125 }
1126 }
1127 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1128 0, 0, 0, 0, black[1],
1129 0, 0, 0, 0, black[2],
1130 0, 0, 0, -1, 1);
1131 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1132 // On the other hand, if the device doesn't handle it, we
1133 // have to apply it ourselves.
1134 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1135 }
1136 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
1137 }
1138 } else {
Vishnu Nair40d80012024-07-13 23:25:06 +00001139 SFTRACE_NAME("DrawColor");
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001140 const auto color = layer.source.solidColor;
1141 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1142 .fG = color.g,
1143 .fB = color.b,
1144 .fA = layer.alpha},
1145 toSkColorSpace(layerDataspace));
1146 paint.setShader(createRuntimeEffectShader(
1147 RuntimeEffectShaderParameters{.shader = shader,
1148 .layer = layer,
1149 .display = display,
1150 .undoPremultipliedAlpha = false,
1151 .requiresLinearEffect = requiresLinearEffect,
Sally Qi628ef6e2023-03-30 14:49:03 -07001152 .layerDimmingRatio = layerDimmingRatio,
Alec Mourie0bb6f42023-08-02 22:41:52 +00001153 .outputDataSpace = display.outputDataspace,
Marzia Favarodcc9d9b2024-01-10 10:17:00 +00001154 .fakeOutputDataspace = fakeDataspace,
1155 .imageBounds = SkRect::MakeEmpty()}));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001156 }
1157
1158 if (layer.disableBlending) {
1159 paint.setBlendMode(SkBlendMode::kSrc);
1160 }
1161
1162 // An A8 buffer will already have the proper color filter attached to
1163 // its paint, including the displayColorTransform as needed.
1164 if (!paint.getColorFilter()) {
1165 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1166 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1167 // can assume a gamma 2.2 transfer function.
1168 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1169 const auto gammaCorrectedDimmingRatio =
1170 std::pow(layerDimmingRatio, kInverseGamma22);
1171 auto dimmingMatrix =
1172 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1173 gammaCorrectedDimmingRatio, 1.f));
1174
1175 const auto colorFilter =
1176 SkColorFilters::Matrix(toSkColorMatrix(std::move(dimmingMatrix)));
1177 paint.setColorFilter(displayColorTransform
1178 ? displayColorTransform->makeComposed(colorFilter)
1179 : colorFilter);
1180 } else {
1181 paint.setColorFilter(displayColorTransform);
1182 }
1183 }
1184
1185 if (!roundRectClip.isEmpty()) {
1186 canvas->clipRRect(roundRectClip, true);
1187 }
1188
1189 if (!bounds.isRect()) {
1190 paint.setAntiAlias(true);
1191 canvas->drawRRect(bounds, paint);
1192 } else {
1193 canvas->drawRect(bounds.rect(), paint);
1194 }
Nolan Scobie1e06f2d2024-03-21 14:56:38 -04001195 if (kGaneshFlushAfterEveryLayer) {
Vishnu Nair40d80012024-07-13 23:25:06 +00001196 SFTRACE_NAME("flush surface");
Nolan Scobie1e06f2d2024-03-21 14:56:38 -04001197 // No-op in Graphite. If "flushing" Skia's drawing commands after each layer is desired
1198 // in Graphite, then a graphite::Recording would need to be snapped and tracked for each
1199 // layer, which is likely possible but adds non-trivial complexity (in both bookkeeping
1200 // and refactoring).
Kevin Lubick208e11a2023-05-31 19:34:46 +00001201 skgpu::ganesh::Flush(activeSurface);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001202 }
1203 }
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001204
1205 surfaceAutoSaveRestore.restore();
1206 mCapture->endCapture();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001207
Nolan Scobie1e06f2d2024-03-21 14:56:38 -04001208 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1209 auto drawFence = sp<Fence>::make(flushAndSubmit(context, dstSurface));
Alec Mouri1b1853f2024-07-15 22:46:58 +00001210 trace(drawFence);
1211 resultPromise->set_value(std::move(drawFence));
1212}
Alec Mouri0e7d8fd2023-05-03 23:58:43 +00001213
Alec Mouri1b1853f2024-07-15 22:46:58 +00001214void SkiaRenderEngine::drawGainmapInternal(
1215 const std::shared_ptr<std::promise<FenceResult>>&& resultPromise,
1216 const std::shared_ptr<ExternalTexture>& sdr, base::borrowed_fd&& sdrFence,
1217 const std::shared_ptr<ExternalTexture>& hdr, base::borrowed_fd&& hdrFence,
1218 float hdrSdrRatio, ui::Dataspace dataspace,
1219 const std::shared_ptr<ExternalTexture>& gainmap) {
1220 std::lock_guard<std::mutex> lock(mRenderingMutex);
1221 auto context = getActiveContext();
1222 auto surfaceTextureRef = getOrCreateBackendTexture(gainmap->getBuffer(), true);
1223 sk_sp<SkSurface> dstSurface =
1224 surfaceTextureRef->getOrCreateSurface(ui::Dataspace::V0_SRGB_LINEAR);
1225
1226 waitFence(context, sdrFence);
1227 const auto sdrTextureRef = getOrCreateBackendTexture(sdr->getBuffer(), false);
1228 const auto sdrImage = sdrTextureRef->makeImage(dataspace, kPremul_SkAlphaType);
1229 const auto sdrShader =
1230 sdrImage->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1231 SkSamplingOptions({SkFilterMode::kLinear, SkMipmapMode::kNone}),
1232 nullptr);
1233 waitFence(context, hdrFence);
1234 const auto hdrTextureRef = getOrCreateBackendTexture(hdr->getBuffer(), false);
1235 const auto hdrImage = hdrTextureRef->makeImage(dataspace, kPremul_SkAlphaType);
1236 const auto hdrShader =
1237 hdrImage->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1238 SkSamplingOptions({SkFilterMode::kLinear, SkMipmapMode::kNone}),
1239 nullptr);
1240
1241 static GainmapFactory kGainmapFactory;
1242 const auto gainmapShader = kGainmapFactory.createSkShader(sdrShader, hdrShader, hdrSdrRatio);
1243
1244 const auto canvas = dstSurface->getCanvas();
1245 SkPaint paint;
1246 paint.setShader(gainmapShader);
1247 paint.setBlendMode(SkBlendMode::kSrc);
1248 canvas->drawPaint(paint);
1249
1250 auto drawFence = sp<Fence>::make(flushAndSubmit(context, dstSurface));
1251 trace(drawFence);
Alec Mouri0e7d8fd2023-05-03 23:58:43 +00001252 resultPromise->set_value(std::move(drawFence));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001253}
1254
1255size_t SkiaRenderEngine::getMaxTextureSize() const {
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001256 return mContext->getMaxTextureSize();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001257}
1258
1259size_t SkiaRenderEngine::getMaxViewportDims() const {
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001260 return mContext->getMaxRenderTargetSize();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001261}
1262
1263void SkiaRenderEngine::drawShadow(SkCanvas* canvas,
1264 const SkRRect& casterRRect,
1265 const ShadowSettings& settings) {
Vishnu Nair40d80012024-07-13 23:25:06 +00001266 SFTRACE_CALL();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001267 const float casterZ = settings.length / 2.0f;
1268 const auto flags =
1269 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1270
1271 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
1272 getSkPoint3(settings.lightPos), settings.lightRadius,
1273 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1274 flags);
1275}
1276
1277void SkiaRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
1278 // This cache multiplier was selected based on review of cache sizes relative
1279 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1280 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1281 // conservative default based on that analysis.
1282 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1283 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1284
1285 // start by resizing the current context
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001286 getActiveContext()->setResourceCacheLimit(maxResourceBytes);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001287
1288 // if it is possible to switch contexts then we will resize the other context
1289 const bool originalProtectedState = mInProtectedContext;
1290 useProtectedContext(!mInProtectedContext);
1291 if (mInProtectedContext != originalProtectedState) {
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001292 getActiveContext()->setResourceCacheLimit(maxResourceBytes);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001293 // reset back to the initial context that was active when this method was called
1294 useProtectedContext(originalProtectedState);
1295 }
1296}
1297
1298void SkiaRenderEngine::dump(std::string& result) {
1299 // Dump for the specific backend (GLES or Vk)
1300 appendBackendSpecificInfoToDump(result);
1301
1302 // Info about protected content
1303 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1304 supportsProtectedContent());
1305 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1306 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1307 mSkSLCacheMonitor.shadersCachedSinceLastCall());
1308
1309 std::vector<ResourcePair> cpuResourceMap = {
1310 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1311 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1312 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1313 {"skia/sk_resource_cache/tessellated", "Shadows"},
1314 {"skia", "Other"},
1315 };
1316 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1317 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1318 StringAppendF(&result, "Skia CPU Caches: ");
1319 cpuReporter.logTotals(result);
1320 cpuReporter.logOutput(result);
1321
1322 {
1323 std::lock_guard<std::mutex> lock(mRenderingMutex);
1324
1325 std::vector<ResourcePair> gpuResourceMap = {
1326 {"texture_renderbuffer", "Texture/RenderBuffer"},
1327 {"texture", "Texture"},
1328 {"gr_text_blob_cache", "Text"},
1329 {"skia", "Other"},
1330 };
1331 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001332 mContext->dumpMemoryStatistics(&gpuReporter);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001333 StringAppendF(&result, "Skia's GPU Caches: ");
1334 gpuReporter.logTotals(result);
1335 gpuReporter.logOutput(result);
1336 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1337 gpuReporter.logOutput(result, true);
1338
1339 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1340 mGraphicBufferExternalRefs.size());
1341 StringAppendF(&result, "Dumping buffer ids...\n");
1342 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1343 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1344 }
1345 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1346 mTextureCache.size());
1347 StringAppendF(&result, "Dumping buffer ids...\n");
1348 // TODO(178539829): It would be nice to know which layer these are coming from and what
1349 // the texture sizes are.
1350 for (const auto& [id, unused] : mTextureCache) {
1351 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1352 }
1353 StringAppendF(&result, "\n");
1354
1355 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001356 if (mProtectedContext) {
1357 mProtectedContext->dumpMemoryStatistics(&gpuProtectedReporter);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001358 }
1359 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1360 gpuProtectedReporter.logTotals(result);
1361 gpuProtectedReporter.logOutput(result);
1362 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1363 gpuProtectedReporter.logOutput(result, true);
1364
1365 StringAppendF(&result, "\n");
1366 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1367 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1368 StringAppendF(&result, "- inputDataspace: %s\n",
1369 dataspaceDetails(
1370 static_cast<android_dataspace>(linearEffect.inputDataspace))
1371 .c_str());
1372 StringAppendF(&result, "- outputDataspace: %s\n",
1373 dataspaceDetails(
1374 static_cast<android_dataspace>(linearEffect.outputDataspace))
1375 .c_str());
1376 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1377 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1378 }
1379 }
1380 StringAppendF(&result, "\n");
1381}
1382
rnleec6a73642021-06-04 14:16:42 -07001383} // namespace skia
John Reck67b1e2b2020-08-26 13:17:24 -07001384} // namespace renderengine
rnleec6a73642021-06-04 14:16:42 -07001385} // namespace android