blob: 27daeba0920b5bba7be06607d95e35525b827e45 [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>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000057#include <gui/FenceMonitor.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070058#include <gui/TraceUtils.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#include <utils/Trace.h>
68
69#include <cmath>
70#include <cstdint>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000071#include <deque>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070072#include <memory>
73#include <numeric>
74
75#include "Cache.h"
76#include "ColorSpaces.h"
Nolan Scobiefc125ec2024-03-11 20:08:27 -040077#include "compat/SkiaGpuContext.h"
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070078#include "filters/BlurFilter.h"
79#include "filters/GaussianBlurFilter.h"
80#include "filters/KawaseBlurFilter.h"
81#include "filters/LinearEffect.h"
82#include "log/log_main.h"
83#include "skia/debug/SkiaCapture.h"
84#include "skia/debug/SkiaMemoryReporter.h"
85#include "skia/filters/StretchShaderFactory.h"
86#include "system/graphics-base-v1.0.h"
87
88namespace {
89
90// Debugging settings
91static const bool kPrintLayerSettings = false;
92static const bool kFlushAfterEveryLayer = kPrintLayerSettings;
John Reck5b02fc42023-06-14 14:41:10 -040093static constexpr bool kEnableLayerBrightening = true;
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
Bruno BELANYIb9b5b702023-10-13 13:25:11 +0000248std::future<void> SkiaRenderEngine::primeCache(bool shouldPrimeUltraHDR) {
249 Cache::primeShaderCache(this, shouldPrimeUltraHDR);
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++;
263 ATRACE_FORMAT("SF cache: %i shaders", mTotalShadersCompiled);
264}
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,
Alec Mouri47bcb072023-08-15 02:02:49 +0000275 bool supportsBackgroundBlur)
Leon Scroggins III696bf932024-01-24 15:21:05 -0500276 : RenderEngine(threaded), mDefaultPixelFormat(pixelFormat) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700277 if (supportsBackgroundBlur) {
278 ALOGD("Background Blurs Enabled");
279 mBlurFilter = new KawaseBlurFilter();
280 }
281 mCapture = std::make_unique<SkiaCapture>();
282}
283
284SkiaRenderEngine::~SkiaRenderEngine() { }
285
286// To be called from backend dtors.
287void SkiaRenderEngine::finishRenderingAndAbandonContext() {
288 std::lock_guard<std::mutex> lock(mRenderingMutex);
289
290 if (mBlurFilter) {
291 delete mBlurFilter;
292 }
293
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400294 if (mContext) {
295 mContext->finishRenderingAndAbandonContext();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700296 }
297
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400298 if (mProtectedContext) {
299 mProtectedContext->finishRenderingAndAbandonContext();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700300 }
301}
302
303void SkiaRenderEngine::useProtectedContext(bool useProtectedContext) {
304 if (useProtectedContext == mInProtectedContext ||
305 (useProtectedContext && !supportsProtectedContent())) {
306 return;
307 }
308
309 // release any scratch resources before switching into a new mode
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400310 if (getActiveContext()) {
311 getActiveContext()->purgeUnlockedScratchResources();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700312 }
313
314 // Backend-specific way to switch to protected context
315 if (useProtectedContextImpl(
316 useProtectedContext ? GrProtected::kYes : GrProtected::kNo)) {
317 mInProtectedContext = useProtectedContext;
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400318 // given that we are sharing the same thread between two contexts we need to
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700319 // make sure that the thread state is reset when switching between the two.
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400320 if (getActiveContext()) {
321 getActiveContext()->resetContextIfApplicable();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700322 }
323 }
324}
325
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400326SkiaGpuContext* SkiaRenderEngine::getActiveContext() {
327 return mInProtectedContext ? mProtectedContext.get() : mContext.get();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700328}
329
330static float toDegrees(uint32_t transform) {
331 switch (transform) {
332 case ui::Transform::ROT_90:
333 return 90.0;
334 case ui::Transform::ROT_180:
335 return 180.0;
336 case ui::Transform::ROT_270:
337 return 270.0;
338 default:
339 return 0.0;
340 }
341}
342
343static SkColorMatrix toSkColorMatrix(const android::mat4& matrix) {
344 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
345 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
346 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
347 matrix[3][3], 0);
348}
349
350static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
351 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
352 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
353
354 // Treat unsupported dataspaces as srgb
355 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
356 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
357 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
358 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
359 }
360
361 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
362 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
363 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
364 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
365 }
366
367 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
368 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
369 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
370 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
371
372 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
373 sourceTransfer != destTransfer;
374}
375
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400376void SkiaRenderEngine::ensureContextsCreated() {
377 if (mContext) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700378 return;
379 }
380
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400381 std::tie(mContext, mProtectedContext) = createContexts();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700382}
383
384void SkiaRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
385 bool isRenderable) {
Ian Elliott1f0911e2022-09-09 16:31:47 -0600386 // Only run this if RE is running on its own thread. This
Leon Scroggins III696bf932024-01-24 15:21:05 -0500387 // way the access to GL/VK operations is guaranteed to be happening on the
Ian Elliott1f0911e2022-09-09 16:31:47 -0600388 // same thread.
Leon Scroggins III696bf932024-01-24 15:21:05 -0500389 if (!isThreaded()) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700390 return;
391 }
Ian Elliott8506e362023-03-08 12:12:09 -0700392 // We don't attempt to map a buffer if the buffer contains protected content. In GL this is
393 // important because GPU resources for protected buffers are much more limited. (In Vk we
Robert Phillips59f71732023-08-23 15:18:27 -0400394 // simply match the existing behavior for protected buffers.) We also never cache any
395 // buffers while in a protected context.
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700396 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Alec Mouri07196db2023-09-12 23:33:49 +0000397 // Don't attempt to map buffers if we're not gpu sampleable. Callers shouldn't send a buffer
398 // over to RenderEngine.
399 const bool isGpuSampleable = buffer->getUsage() & GRALLOC_USAGE_HW_TEXTURE;
400 if (isProtectedBuffer || isProtected() || !isGpuSampleable) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700401 return;
402 }
403 ATRACE_CALL();
404
405 // If we were to support caching protected buffers then we will need to switch the
406 // currently bound context if we are not already using the protected context (and subsequently
407 // switch back after the buffer is cached). However, for non-protected content we can bind
408 // the texture in either GL context because they are initialized with the same share_context
409 // which allows the texture state to be shared between them.
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400410 auto context = getActiveContext();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700411 auto& cache = mTextureCache;
412
413 std::lock_guard<std::mutex> lock(mRenderingMutex);
414 mGraphicBufferExternalRefs[buffer->getId()]++;
415
416 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Leon Scroggins IIIdf8166e2024-01-25 15:50:56 -0500417 if (FlagManager::getInstance().renderable_buffer_usage()) {
418 isRenderable = buffer->getUsage() & GRALLOC_USAGE_HW_RENDER;
419 }
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700420 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400421 std::make_shared<AutoBackendTexture::LocalRef>(context, buffer->toAHardwareBuffer(),
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700422 isRenderable, mTextureCleanupMgr);
423 cache.insert({buffer->getId(), imageTextureRef});
424 }
425}
426
Alec Mouri92f89fa2023-02-24 00:05:06 +0000427void SkiaRenderEngine::unmapExternalTextureBuffer(sp<GraphicBuffer>&& buffer) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700428 ATRACE_CALL();
429 std::lock_guard<std::mutex> lock(mRenderingMutex);
430 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
431 iter != mGraphicBufferExternalRefs.end()) {
432 if (iter->second == 0) {
433 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
434 "> from RenderEngine texture, but the "
435 "ref count was already zero!",
436 buffer->getId());
437 mGraphicBufferExternalRefs.erase(buffer->getId());
438 return;
439 }
440
441 iter->second--;
442
443 // Swap contexts if needed prior to deleting this buffer
444 // See Issue 1 of
445 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
446 // when a protected context and an unprotected context are part of the same share group,
447 // protected surfaces may not be accessed by an unprotected context, implying that protected
448 // surfaces may only be freed when a protected context is active.
449 const bool inProtected = mInProtectedContext;
450 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
451
452 if (iter->second == 0) {
453 mTextureCache.erase(buffer->getId());
454 mGraphicBufferExternalRefs.erase(buffer->getId());
455 }
456
457 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
458 // are up-to-date.
459 if (inProtected != mInProtectedContext) {
460 useProtectedContext(inProtected);
461 }
462 }
463}
464
Ian Elliott8506e362023-03-08 12:12:09 -0700465std::shared_ptr<AutoBackendTexture::LocalRef> SkiaRenderEngine::getOrCreateBackendTexture(
466 const sp<GraphicBuffer>& buffer, bool isOutputBuffer) {
Robert Phillips59f71732023-08-23 15:18:27 -0400467 // Do not lookup the buffer in the cache for protected contexts
468 if (!isProtected()) {
Ian Elliott8506e362023-03-08 12:12:09 -0700469 if (const auto& it = mTextureCache.find(buffer->getId()); it != mTextureCache.end()) {
470 return it->second;
471 }
472 }
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400473 return std::make_shared<AutoBackendTexture::LocalRef>(getActiveContext(),
Ian Elliott8506e362023-03-08 12:12:09 -0700474 buffer->toAHardwareBuffer(),
475 isOutputBuffer, mTextureCleanupMgr);
476}
477
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700478bool SkiaRenderEngine::canSkipPostRenderCleanup() const {
479 std::lock_guard<std::mutex> lock(mRenderingMutex);
480 return mTextureCleanupMgr.isEmpty();
481}
482
483void SkiaRenderEngine::cleanupPostRender() {
484 ATRACE_CALL();
485 std::lock_guard<std::mutex> lock(mRenderingMutex);
486 mTextureCleanupMgr.cleanup();
487}
488
489sk_sp<SkShader> SkiaRenderEngine::createRuntimeEffectShader(
490 const RuntimeEffectShaderParameters& parameters) {
491 // The given surface will be stretched by HWUI via matrix transformation
492 // which gets similar results for most surfaces
493 // Determine later on if we need to leverage the stertch shader within
494 // surface flinger
495 const auto& stretchEffect = parameters.layer.stretchEffect;
496 auto shader = parameters.shader;
497 if (stretchEffect.hasEffect()) {
498 const auto targetBuffer = parameters.layer.source.buffer.buffer;
499 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
500 if (graphicBuffer && parameters.shader) {
501 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
502 }
503 }
504
505 if (parameters.requiresLinearEffect) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700506 auto effect =
Sally Qi628ef6e2023-03-30 14:49:03 -0700507 shaders::LinearEffect{.inputDataspace = parameters.layer.sourceDataspace,
508 .outputDataspace = parameters.outputDataSpace,
Alec Mourie0bb6f42023-08-02 22:41:52 +0000509 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha,
510 .fakeOutputDataspace = parameters.fakeOutputDataspace};
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700511
512 auto effectIter = mRuntimeEffects.find(effect);
513 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
514 if (effectIter == mRuntimeEffects.end()) {
515 runtimeEffect = buildRuntimeEffect(effect);
516 mRuntimeEffects.insert({effect, runtimeEffect});
517 } else {
518 runtimeEffect = effectIter->second;
519 }
Alec Mouri3e5965f2023-04-07 18:00:58 +0000520
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700521 mat4 colorTransform = parameters.layer.colorTransform;
522
523 colorTransform *=
524 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
525 parameters.layerDimmingRatio, 1.f));
Alec Mouri3e5965f2023-04-07 18:00:58 +0000526
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700527 const auto targetBuffer = parameters.layer.source.buffer.buffer;
528 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
529 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouri3e5965f2023-04-07 18:00:58 +0000530 return createLinearEffectShader(parameters.shader, effect, runtimeEffect,
531 std::move(colorTransform), parameters.display.maxLuminance,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700532 parameters.display.currentLuminanceNits,
533 parameters.layer.source.buffer.maxLuminanceNits,
534 hardwareBuffer, parameters.display.renderIntent);
535 }
536 return parameters.shader;
537}
538
539void SkiaRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
540 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
541 // Record display settings when capture is running.
542 std::stringstream displaySettings;
543 PrintTo(display, &displaySettings);
544 // Store the DisplaySettings in additional information.
545 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
546 SkData::MakeWithCString(displaySettings.str().c_str()));
547 }
548
549 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
550 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
551 // displays might have different scaling when compared to the physical screen.
552
553 canvas->clipRect(getSkRect(display.physicalDisplay));
554 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
555
556 const auto clipWidth = display.clip.width();
557 const auto clipHeight = display.clip.height();
558 auto rotatedClipWidth = clipWidth;
559 auto rotatedClipHeight = clipHeight;
560 // Scale is contingent on the rotation result.
561 if (display.orientation & ui::Transform::ROT_90) {
562 std::swap(rotatedClipWidth, rotatedClipHeight);
563 }
564 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
565 static_cast<SkScalar>(rotatedClipWidth);
566 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
567 static_cast<SkScalar>(rotatedClipHeight);
568 canvas->scale(scaleX, scaleY);
569
570 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
571 // back so that the top left corner of the clip is at (0, 0).
572 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
573 canvas->rotate(toDegrees(display.orientation));
574 canvas->translate(-clipWidth / 2, -clipHeight / 2);
575 canvas->translate(-display.clip.left, -display.clip.top);
576}
577
578class AutoSaveRestore {
579public:
580 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
581 ~AutoSaveRestore() { restore(); }
582 void replace(SkCanvas* canvas) {
583 mCanvas = canvas;
584 mSaveCount = canvas->save();
585 }
586 void restore() {
587 if (mCanvas) {
588 mCanvas->restoreToCount(mSaveCount);
589 mCanvas = nullptr;
590 }
591 }
592
593private:
594 SkCanvas* mCanvas;
595 int mSaveCount;
596};
597
598static SkRRect getBlurRRect(const BlurRegion& region) {
599 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
600 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
601 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
602 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
603 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
604 SkRRect roundedRect;
605 roundedRect.setRectRadii(rect, radii);
606 return roundedRect;
607}
608
609// Arbitrary default margin which should be close enough to zero.
610constexpr float kDefaultMargin = 0.0001f;
611static bool equalsWithinMargin(float expected, float value, float margin = kDefaultMargin) {
612 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
613 return std::abs(expected - value) < margin;
614}
615
616namespace {
617template <typename T>
618void logSettings(const T& t) {
619 std::stringstream stream;
620 PrintTo(t, &stream);
621 auto string = stream.str();
622 size_t pos = 0;
623 // Perfetto ignores \n, so split up manually into separate ALOGD statements.
624 const size_t size = string.size();
625 while (pos < size) {
626 const size_t end = std::min(string.find("\n", pos), size);
627 ALOGD("%s", string.substr(pos, end - pos).c_str());
628 pos = end + 1;
629 }
630}
631} // namespace
632
633// Helper class intended to be used on the stack to ensure that texture cleanup
634// is deferred until after this class goes out of scope.
635class DeferTextureCleanup final {
636public:
637 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
638 mMgr.setDeferredStatus(true);
639 }
640 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
641
642private:
643 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
644 AutoBackendTexture::CleanupManager& mMgr;
645};
646
647void SkiaRenderEngine::drawLayersInternal(
Patrick Williams2e9748f2022-08-09 22:48:18 +0000648 const std::shared_ptr<std::promise<FenceResult>>&& resultPromise,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700649 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
Alec Mourif29700f2023-08-17 21:53:31 +0000650 const std::shared_ptr<ExternalTexture>& buffer, base::unique_fd&& bufferFence) {
Leon Scroggins III5a655b82022-09-07 13:17:09 -0400651 ATRACE_FORMAT("%s for %s", __func__, display.namePlusId.c_str());
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700652
653 std::lock_guard<std::mutex> lock(mRenderingMutex);
654
655 if (buffer == nullptr) {
656 ALOGE("No output buffer provided. Aborting GPU composition.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000657 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700658 return;
659 }
660
661 validateOutputBufferUsage(buffer->getBuffer());
662
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400663 auto context = getActiveContext();
664 LOG_ALWAYS_FATAL_IF(context->isAbandoned(), "Context is abandoned/device lost at start of %s",
Leon Scroggins III41c00c52023-06-21 15:55:55 -0400665 __func__);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700666
667 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
668 DeferTextureCleanup dtc(mTextureCleanupMgr);
669
Ian Elliott8506e362023-03-08 12:12:09 -0700670 auto surfaceTextureRef = getOrCreateBackendTexture(buffer->getBuffer(), true);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700671
672 // wait on the buffer to be ready to use prior to using it
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400673 waitFence(context, bufferFence);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700674
Nolan Scobie17e25512024-03-13 18:02:48 -0400675 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(display.outputDataspace);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700676
677 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
678 if (dstCanvas == nullptr) {
679 ALOGE("Cannot acquire canvas from Skia.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000680 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700681 return;
682 }
683
684 // setup color filter if necessary
685 sk_sp<SkColorFilter> displayColorTransform;
686 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
687 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
688 }
689 const bool ctModifiesAlpha =
690 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
691
692 // Find the max layer white point to determine the max luminance of the scene...
693 const float maxLayerWhitePoint = std::transform_reduce(
694 layers.cbegin(), layers.cend(), 0.f,
695 [](float left, float right) { return std::max(left, right); },
696 [&](const auto& l) { return l.whitePointNits; });
697
698 // ...and compute the dimming ratio if dimming is requested
699 const float displayDimmingRatio = display.targetLuminanceNits > 0.f &&
John Reck5b02fc42023-06-14 14:41:10 -0400700 maxLayerWhitePoint > 0.f &&
701 (kEnableLayerBrightening || display.targetLuminanceNits > maxLayerWhitePoint)
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700702 ? maxLayerWhitePoint / display.targetLuminanceNits
703 : 1.f;
704
705 // Find if any layers have requested blur, we'll use that info to decide when to render to an
706 // offscreen buffer and when to render to the native buffer.
707 sk_sp<SkSurface> activeSurface(dstSurface);
708 SkCanvas* canvas = dstCanvas;
709 SkiaCapture::OffscreenState offscreenCaptureState;
710 const LayerSettings* blurCompositionLayer = nullptr;
Leon Scroggins IIIf31b4bc2023-08-25 10:40:27 -0400711 if (mBlurFilter) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700712 bool requiresCompositionLayer = false;
713 for (const auto& layer : layers) {
714 // if the layer doesn't have blur or it is not visible then continue
715 if (!layerHasBlur(layer, ctModifiesAlpha)) {
716 continue;
717 }
718 if (layer.backgroundBlurRadius > 0 &&
719 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
720 requiresCompositionLayer = true;
721 }
722 for (auto region : layer.blurRegions) {
723 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
724 requiresCompositionLayer = true;
725 }
726 }
727 if (requiresCompositionLayer) {
728 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
729 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
730 blurCompositionLayer = &layer;
731 break;
732 }
733 }
734 }
735
736 AutoSaveRestore surfaceAutoSaveRestore(canvas);
737 // Clear the entire canvas with a transparent black to prevent ghost images.
738 canvas->clear(SK_ColorTRANSPARENT);
739 initCanvas(canvas, display);
740
741 if (kPrintLayerSettings) {
742 logSettings(display);
743 }
744 for (const auto& layer : layers) {
745 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
746
747 if (kPrintLayerSettings) {
748 logSettings(layer);
749 }
750
751 sk_sp<SkImage> blurInput;
752 if (blurCompositionLayer == &layer) {
753 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
754 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
755
756 // save a snapshot of the activeSurface to use as input to the blur shaders
757 blurInput = activeSurface->makeImageSnapshot();
758
Leon Scroggins III48a60cc2024-01-31 12:41:33 -0500759 // blit the offscreen framebuffer into the destination AHB. This ensures that
760 // even if the blurred image does not cover the screen (for example, during
761 // a rotation animation, or if blur regions are used), the entire screen is
762 // initialized.
763 if (layer.blurRegions.size() || FlagManager::getInstance().restore_blur_step()) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700764 SkPaint paint;
765 paint.setBlendMode(SkBlendMode::kSrc);
766 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
767 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
768 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
769 String8::format("SurfaceID|%" PRId64, id).c_str(),
770 nullptr);
771 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
772 } else {
773 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
774 }
775 }
776
777 // assign dstCanvas to canvas and ensure that the canvas state is up to date
778 canvas = dstCanvas;
779 surfaceAutoSaveRestore.replace(canvas);
780 initCanvas(canvas, display);
781
782 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
783 dstSurface->getCanvas()->getSaveCount());
784 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
785 dstSurface->getCanvas()->getTotalMatrix());
786
787 // assign dstSurface to activeSurface
788 activeSurface = dstSurface;
789 }
790
791 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
792 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
793 // Record the name of the layer if the capture is running.
794 std::stringstream layerSettings;
795 PrintTo(layer, &layerSettings);
796 // Store the LayerSettings in additional information.
797 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
798 SkData::MakeWithCString(layerSettings.str().c_str()));
799 }
800 // Layers have a local transform that should be applied to them
801 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
802
803 const auto [bounds, roundRectClip] =
804 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
805 layer.geometry.roundedCornersRadius);
Leon Scroggins IIIf31b4bc2023-08-25 10:40:27 -0400806 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700807 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
808
809 // if multiple layers have blur, then we need to take a snapshot now because
810 // only the lowest layer will have blurImage populated earlier
811 if (!blurInput) {
812 blurInput = activeSurface->makeImageSnapshot();
813 }
Leon Scroggins IIIa09cddc2023-07-25 09:34:11 -0400814
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700815 // rect to be blurred in the coordinate space of blurInput
Leon Scroggins IIIa09cddc2023-07-25 09:34:11 -0400816 SkRect blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
817
818 // Some layers may be much bigger than the screen. If we used
819 // `blurRect` directly, this would allocate a large buffer with no
820 // benefit. Apply the clip, which already takes the display size
821 // into account. The clipped size will then be used to calculate the
822 // size of the buffer we will create for blurring.
823 if (!blurRect.intersect(SkRect::Make(canvas->getDeviceClipBounds()))) {
824 // This should not happen, but if it did, we would use the full
825 // sized layer, which should still be fine.
826 ALOGW("blur bounds does not intersect display clip!");
827 }
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700828
829 // if the clip needs to be applied then apply it now and make sure
830 // it is restored before we attempt to draw any shadows.
831 SkAutoCanvasRestore acr(canvas, true);
832 if (!roundRectClip.isEmpty()) {
833 canvas->clipRRect(roundRectClip, true);
834 }
835
836 // TODO(b/182216890): Filter out empty layers earlier
837 if (blurRect.width() > 0 && blurRect.height() > 0) {
838 if (layer.backgroundBlurRadius > 0) {
839 ATRACE_NAME("BackgroundBlur");
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400840 auto blurredImage = mBlurFilter->generate(context, layer.backgroundBlurRadius,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700841 blurInput, blurRect);
842
843 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
844
845 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
846 blurRect, blurredImage, blurInput);
847 }
848
849 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
850 for (auto region : layer.blurRegions) {
851 if (cachedBlurs[region.blurRadius] == nullptr) {
852 ATRACE_NAME("BlurRegion");
853 cachedBlurs[region.blurRadius] =
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400854 mBlurFilter->generate(context, region.blurRadius, blurInput,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700855 blurRect);
856 }
857
858 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
859 region.alpha, blurRect,
860 cachedBlurs[region.blurRadius], blurInput);
861 }
862 }
863 }
864
865 if (layer.shadow.length > 0) {
866 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
867 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
868
869 SkRRect shadowBounds, shadowClip;
870 if (layer.geometry.boundaries == layer.shadow.boundaries) {
871 shadowBounds = bounds;
872 shadowClip = roundRectClip;
873 } else {
874 std::tie(shadowBounds, shadowClip) =
875 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
876 layer.geometry.roundedCornersRadius);
877 }
878
879 // Technically, if bounds is a rect and roundRectClip is not empty,
880 // it means that the bounds and roundedCornersCrop were different
881 // enough that we should intersect them to find the proper shadow.
882 // In practice, this often happens when the two rectangles appear to
883 // not match due to rounding errors. Draw the rounded version, which
884 // looks more like the intent.
885 const auto& rrect =
886 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
887 drawShadow(canvas, rrect, layer.shadow);
888 }
889
890 const float layerDimmingRatio = layer.whitePointNits <= 0.f
891 ? displayDimmingRatio
892 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
893
894 const bool dimInLinearSpace = display.dimmingStage !=
895 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
896
Sally Qi628ef6e2023-03-30 14:49:03 -0700897 const bool isExtendedHdr = (layer.sourceDataspace & ui::Dataspace::RANGE_MASK) ==
898 static_cast<int32_t>(ui::Dataspace::RANGE_EXTENDED) &&
899 (display.outputDataspace & ui::Dataspace::TRANSFER_MASK) ==
900 static_cast<int32_t>(ui::Dataspace::TRANSFER_SRGB);
901
Alec Mourie0bb6f42023-08-02 22:41:52 +0000902 const bool useFakeOutputDataspaceForRuntimeEffect = !dimInLinearSpace && isExtendedHdr;
903
904 const ui::Dataspace fakeDataspace = useFakeOutputDataspaceForRuntimeEffect
Sally Qi628ef6e2023-03-30 14:49:03 -0700905 ? static_cast<ui::Dataspace>(
906 (display.outputDataspace & ui::Dataspace::STANDARD_MASK) |
907 ui::Dataspace::TRANSFER_GAMMA2_2 |
908 (display.outputDataspace & ui::Dataspace::RANGE_MASK))
Alec Mourie0bb6f42023-08-02 22:41:52 +0000909 : ui::Dataspace::UNKNOWN;
Sally Qi628ef6e2023-03-30 14:49:03 -0700910
911 // If the input dataspace is range extended, the output dataspace transfer is sRGB
912 // and dimmingStage is GAMMA_OETF, dim in linear space instead, and
913 // set the output dataspace's transfer to be GAMMA2_2.
914 // This allows DPU side to use oetf_gamma_2p2 for extended HDR layer
915 // to avoid tone shift.
916 // The reason of tone shift here is because HDR layers manage white point
917 // luminance in linear space, which color pipelines request GAMMA_OETF break
918 // without a gamma 2.2 fixup.
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700919 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
Alec Mouri47bcb072023-08-15 02:02:49 +0000920 (needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
Sally Qi628ef6e2023-03-30 14:49:03 -0700921 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio)) ||
922 (!dimInLinearSpace && isExtendedHdr);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700923
924 // quick abort from drawing the remaining portion of the layer
925 if (layer.skipContentDraw ||
926 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
927 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
928 continue;
929 }
930
Alec Mouri47bcb072023-08-15 02:02:49 +0000931 const ui::Dataspace layerDataspace = layer.sourceDataspace;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700932
933 SkPaint paint;
934 if (layer.source.buffer.buffer) {
935 ATRACE_NAME("DrawImage");
936 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
937 const auto& item = layer.source.buffer;
Ian Elliott8506e362023-03-08 12:12:09 -0700938 auto imageTextureRef = getOrCreateBackendTexture(item.buffer->getBuffer(), false);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700939
940 // if the layer's buffer has a fence, then we must must respect the fence prior to using
941 // the buffer.
942 if (layer.source.buffer.fence != nullptr) {
Nolan Scobiefc125ec2024-03-11 20:08:27 -0400943 waitFence(context, layer.source.buffer.fence->get());
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700944 }
945
946 // isOpaque means we need to ignore the alpha in the image,
947 // replacing it with the alpha specified by the LayerSettings. See
948 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
949 // The proper way to do this is to use an SkColorType that ignores
950 // alpha, like kRGB_888x_SkColorType, and that is used if the
951 // incoming image is kRGBA_8888_SkColorType. However, the incoming
952 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
953 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
954 // kRGB_101010x_SkColorType, but it is not yet supported as a source
955 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
956 // meantime, we'll use a workaround that works unless we need to do
957 // any color conversion. The workaround requires that we pretend the
958 // image is already premultiplied, so that we do not premultiply it
959 // before applying SkBlendMode::kPlus.
960 const bool useIsOpaqueWorkaround = item.isOpaque &&
961 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
962 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
963 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
964 : item.isOpaque ? kOpaque_SkAlphaType
965 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
966 : kUnpremul_SkAlphaType;
Nolan Scobie17e25512024-03-13 18:02:48 -0400967 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700968
969 auto texMatrix = getSkM44(item.textureTransform).asM33();
970 // textureTansform was intended to be passed directly into a shader, so when
971 // building the total matrix with the textureTransform we need to first
972 // normalize it, then apply the textureTransform, then scale back up.
973 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
974 texMatrix.postScale(image->width(), image->height());
975
976 SkMatrix matrix;
977 if (!texMatrix.invert(&matrix)) {
978 matrix = texMatrix;
979 }
980 // The shader does not respect the translation, so we add it to the texture
981 // transform for the SkImage. This will make sure that the correct layer contents
982 // are drawn in the correct part of the screen.
983 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
984
985 sk_sp<SkShader> shader;
986
987 if (layer.source.buffer.useTextureFiltering) {
988 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
989 SkSamplingOptions(
990 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
991 &matrix);
992 } else {
993 shader = image->makeShader(SkSamplingOptions(), matrix);
994 }
995
996 if (useIsOpaqueWorkaround) {
997 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
998 SkShaders::Color(SkColors::kBlack,
999 toSkColorSpace(layerDataspace)));
1000 }
1001
1002 paint.setShader(createRuntimeEffectShader(
1003 RuntimeEffectShaderParameters{.shader = shader,
1004 .layer = layer,
1005 .display = display,
1006 .undoPremultipliedAlpha = !item.isOpaque &&
1007 item.usePremultipliedAlpha,
1008 .requiresLinearEffect = requiresLinearEffect,
1009 .layerDimmingRatio = dimInLinearSpace
1010 ? layerDimmingRatio
Sally Qi628ef6e2023-03-30 14:49:03 -07001011 : 1.f,
Alec Mourie0bb6f42023-08-02 22:41:52 +00001012 .outputDataSpace = display.outputDataspace,
1013 .fakeOutputDataspace = fakeDataspace}));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001014
1015 // Turn on dithering when dimming beyond this (arbitrary) threshold...
linkai296566e2024-01-22 20:58:15 +08001016 static constexpr float kDimmingThreshold = 0.9f;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001017 // ...or we're rendering an HDR layer down to an 8-bit target
1018 // Most HDR standards require at least 10-bits of color depth for source content, so we
1019 // can just extract the transfer function rather than dig into precise gralloc layout.
1020 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
Sally Qif6918d42023-08-07 15:28:30 -07001021 const bool requiresDownsample =
1022 getHdrRenderType(layer.sourceDataspace,
1023 std::optional<ui::PixelFormat>(static_cast<ui::PixelFormat>(
1024 buffer->getPixelFormat()))) != HdrRenderType::SDR &&
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001025 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
1026 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
1027 paint.setDither(true);
1028 }
1029 paint.setAlphaf(layer.alpha);
1030
1031 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1032 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
1033
1034 // SysUI creates the alpha layer as a coverage layer, which is
1035 // appropriate for the DPU. Use a color matrix to convert it to
1036 // a mask.
1037 // TODO (b/219525258): Handle input as a mask.
1038 //
1039 // The color matrix will convert A8 pixels with no alpha to
1040 // black, as described by this vector. If the display handles
1041 // the color transform, we need to invert it to find the color
1042 // that will result in black after the DPU applies the transform.
1043 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1044 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1045 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1046 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1047 black = colorSpaceMatrix * black;
1048 } else {
1049 // We'll just have to use 0,0,0 as black, which should
1050 // be close to correct.
1051 ALOGI("Could not invert colorTransform!");
1052 }
1053 }
1054 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1055 0, 0, 0, 0, black[1],
1056 0, 0, 0, 0, black[2],
1057 0, 0, 0, -1, 1);
1058 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1059 // On the other hand, if the device doesn't handle it, we
1060 // have to apply it ourselves.
1061 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1062 }
1063 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
1064 }
1065 } else {
1066 ATRACE_NAME("DrawColor");
1067 const auto color = layer.source.solidColor;
1068 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1069 .fG = color.g,
1070 .fB = color.b,
1071 .fA = layer.alpha},
1072 toSkColorSpace(layerDataspace));
1073 paint.setShader(createRuntimeEffectShader(
1074 RuntimeEffectShaderParameters{.shader = shader,
1075 .layer = layer,
1076 .display = display,
1077 .undoPremultipliedAlpha = false,
1078 .requiresLinearEffect = requiresLinearEffect,
Sally Qi628ef6e2023-03-30 14:49:03 -07001079 .layerDimmingRatio = layerDimmingRatio,
Alec Mourie0bb6f42023-08-02 22:41:52 +00001080 .outputDataSpace = display.outputDataspace,
1081 .fakeOutputDataspace = fakeDataspace}));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001082 }
1083
1084 if (layer.disableBlending) {
1085 paint.setBlendMode(SkBlendMode::kSrc);
1086 }
1087
1088 // An A8 buffer will already have the proper color filter attached to
1089 // its paint, including the displayColorTransform as needed.
1090 if (!paint.getColorFilter()) {
1091 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1092 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1093 // can assume a gamma 2.2 transfer function.
1094 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1095 const auto gammaCorrectedDimmingRatio =
1096 std::pow(layerDimmingRatio, kInverseGamma22);
1097 auto dimmingMatrix =
1098 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1099 gammaCorrectedDimmingRatio, 1.f));
1100
1101 const auto colorFilter =
1102 SkColorFilters::Matrix(toSkColorMatrix(std::move(dimmingMatrix)));
1103 paint.setColorFilter(displayColorTransform
1104 ? displayColorTransform->makeComposed(colorFilter)
1105 : colorFilter);
1106 } else {
1107 paint.setColorFilter(displayColorTransform);
1108 }
1109 }
1110
1111 if (!roundRectClip.isEmpty()) {
1112 canvas->clipRRect(roundRectClip, true);
1113 }
1114
1115 if (!bounds.isRect()) {
1116 paint.setAntiAlias(true);
1117 canvas->drawRRect(bounds, paint);
1118 } else {
1119 canvas->drawRect(bounds.rect(), paint);
1120 }
1121 if (kFlushAfterEveryLayer) {
1122 ATRACE_NAME("flush surface");
Kevin Lubick208e11a2023-05-31 19:34:46 +00001123 skgpu::ganesh::Flush(activeSurface);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001124 }
1125 }
1126 for (const auto& borderRenderInfo : display.borderInfoList) {
1127 SkPaint p;
1128 p.setColor(SkColor4f{borderRenderInfo.color.r, borderRenderInfo.color.g,
1129 borderRenderInfo.color.b, borderRenderInfo.color.a});
1130 p.setAntiAlias(true);
1131 p.setStyle(SkPaint::kStroke_Style);
1132 p.setStrokeWidth(borderRenderInfo.width);
1133 SkRegion sk_region;
1134 SkPath path;
1135
1136 // Construct a final SkRegion using Regions
1137 for (const auto& r : borderRenderInfo.combinedRegion) {
1138 sk_region.op({r.left, r.top, r.right, r.bottom}, SkRegion::kUnion_Op);
1139 }
1140
1141 sk_region.getBoundaryPath(&path);
1142 canvas->drawPath(path, p);
1143 path.close();
1144 }
1145
1146 surfaceAutoSaveRestore.restore();
1147 mCapture->endCapture();
1148 {
1149 ATRACE_NAME("flush surface");
1150 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
Kevin Lubick208e11a2023-05-31 19:34:46 +00001151 skgpu::ganesh::Flush(activeSurface);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001152 }
1153
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001154 auto drawFence = sp<Fence>::make(flushAndSubmit(context));
Alec Mouri0e7d8fd2023-05-03 23:58:43 +00001155
1156 if (ATRACE_ENABLED()) {
1157 static gui::FenceMonitor sMonitor("RE Completion");
1158 sMonitor.queueFence(drawFence);
1159 }
1160 resultPromise->set_value(std::move(drawFence));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001161}
1162
1163size_t SkiaRenderEngine::getMaxTextureSize() const {
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001164 return mContext->getMaxTextureSize();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001165}
1166
1167size_t SkiaRenderEngine::getMaxViewportDims() const {
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001168 return mContext->getMaxRenderTargetSize();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001169}
1170
1171void SkiaRenderEngine::drawShadow(SkCanvas* canvas,
1172 const SkRRect& casterRRect,
1173 const ShadowSettings& settings) {
1174 ATRACE_CALL();
1175 const float casterZ = settings.length / 2.0f;
1176 const auto flags =
1177 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1178
1179 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
1180 getSkPoint3(settings.lightPos), settings.lightRadius,
1181 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1182 flags);
1183}
1184
1185void SkiaRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
1186 // This cache multiplier was selected based on review of cache sizes relative
1187 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1188 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1189 // conservative default based on that analysis.
1190 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1191 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1192
1193 // start by resizing the current context
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001194 getActiveContext()->setResourceCacheLimit(maxResourceBytes);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001195
1196 // if it is possible to switch contexts then we will resize the other context
1197 const bool originalProtectedState = mInProtectedContext;
1198 useProtectedContext(!mInProtectedContext);
1199 if (mInProtectedContext != originalProtectedState) {
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001200 getActiveContext()->setResourceCacheLimit(maxResourceBytes);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001201 // reset back to the initial context that was active when this method was called
1202 useProtectedContext(originalProtectedState);
1203 }
1204}
1205
1206void SkiaRenderEngine::dump(std::string& result) {
1207 // Dump for the specific backend (GLES or Vk)
1208 appendBackendSpecificInfoToDump(result);
1209
1210 // Info about protected content
1211 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1212 supportsProtectedContent());
1213 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1214 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1215 mSkSLCacheMonitor.shadersCachedSinceLastCall());
1216
1217 std::vector<ResourcePair> cpuResourceMap = {
1218 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1219 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1220 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1221 {"skia/sk_resource_cache/tessellated", "Shadows"},
1222 {"skia", "Other"},
1223 };
1224 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1225 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1226 StringAppendF(&result, "Skia CPU Caches: ");
1227 cpuReporter.logTotals(result);
1228 cpuReporter.logOutput(result);
1229
1230 {
1231 std::lock_guard<std::mutex> lock(mRenderingMutex);
1232
1233 std::vector<ResourcePair> gpuResourceMap = {
1234 {"texture_renderbuffer", "Texture/RenderBuffer"},
1235 {"texture", "Texture"},
1236 {"gr_text_blob_cache", "Text"},
1237 {"skia", "Other"},
1238 };
1239 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001240 mContext->dumpMemoryStatistics(&gpuReporter);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001241 StringAppendF(&result, "Skia's GPU Caches: ");
1242 gpuReporter.logTotals(result);
1243 gpuReporter.logOutput(result);
1244 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1245 gpuReporter.logOutput(result, true);
1246
1247 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1248 mGraphicBufferExternalRefs.size());
1249 StringAppendF(&result, "Dumping buffer ids...\n");
1250 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1251 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1252 }
1253 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1254 mTextureCache.size());
1255 StringAppendF(&result, "Dumping buffer ids...\n");
1256 // TODO(178539829): It would be nice to know which layer these are coming from and what
1257 // the texture sizes are.
1258 for (const auto& [id, unused] : mTextureCache) {
1259 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1260 }
1261 StringAppendF(&result, "\n");
1262
1263 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Nolan Scobiefc125ec2024-03-11 20:08:27 -04001264 if (mProtectedContext) {
1265 mProtectedContext->dumpMemoryStatistics(&gpuProtectedReporter);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001266 }
1267 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1268 gpuProtectedReporter.logTotals(result);
1269 gpuProtectedReporter.logOutput(result);
1270 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1271 gpuProtectedReporter.logOutput(result, true);
1272
1273 StringAppendF(&result, "\n");
1274 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1275 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1276 StringAppendF(&result, "- inputDataspace: %s\n",
1277 dataspaceDetails(
1278 static_cast<android_dataspace>(linearEffect.inputDataspace))
1279 .c_str());
1280 StringAppendF(&result, "- outputDataspace: %s\n",
1281 dataspaceDetails(
1282 static_cast<android_dataspace>(linearEffect.outputDataspace))
1283 .c_str());
1284 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1285 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1286 }
1287 }
1288 StringAppendF(&result, "\n");
1289}
1290
rnleec6a73642021-06-04 14:16:42 -07001291} // namespace skia
John Reck67b1e2b2020-08-26 13:17:24 -07001292} // namespace renderengine
rnleec6a73642021-06-04 14:16:42 -07001293} // namespace android