blob: fda6ea189ec7b72072490853225e543c8a2a22b5 [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>
25#include <SkBlendMode.h>
26#include <SkCanvas.h>
27#include <SkColor.h>
28#include <SkColorFilter.h>
29#include <SkColorMatrix.h>
30#include <SkColorSpace.h>
31#include <SkData.h>
32#include <SkGraphics.h>
33#include <SkImage.h>
34#include <SkImageFilters.h>
35#include <SkImageInfo.h>
36#include <SkM44.h>
37#include <SkMatrix.h>
38#include <SkPaint.h>
39#include <SkPath.h>
40#include <SkPoint.h>
41#include <SkPoint3.h>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000042#include <SkRRect.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070043#include <SkRect.h>
44#include <SkRefCnt.h>
45#include <SkRegion.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070046#include <SkRuntimeEffect.h>
47#include <SkSamplingOptions.h>
48#include <SkScalar.h>
49#include <SkShader.h>
50#include <SkShadowUtils.h>
51#include <SkString.h>
52#include <SkSurface.h>
53#include <SkTileMode.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070054#include <android-base/stringprintf.h>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000055#include <gui/FenceMonitor.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070056#include <gui/TraceUtils.h>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000057#include <pthread.h>
58#include <src/core/SkTraceEventCommon.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070059#include <sync/sync.h>
60#include <ui/BlurRegion.h>
61#include <ui/DataspaceUtils.h>
62#include <ui/DebugUtils.h>
63#include <ui/GraphicBuffer.h>
64#include <utils/Trace.h>
65
66#include <cmath>
67#include <cstdint>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000068#include <deque>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070069#include <memory>
70#include <numeric>
71
72#include "Cache.h"
73#include "ColorSpaces.h"
74#include "filters/BlurFilter.h"
75#include "filters/GaussianBlurFilter.h"
76#include "filters/KawaseBlurFilter.h"
77#include "filters/LinearEffect.h"
78#include "log/log_main.h"
79#include "skia/debug/SkiaCapture.h"
80#include "skia/debug/SkiaMemoryReporter.h"
81#include "skia/filters/StretchShaderFactory.h"
82#include "system/graphics-base-v1.0.h"
83
84namespace {
85
86// Debugging settings
87static const bool kPrintLayerSettings = false;
88static const bool kFlushAfterEveryLayer = kPrintLayerSettings;
John Reck5b02fc42023-06-14 14:41:10 -040089static constexpr bool kEnableLayerBrightening = true;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070090
91} // namespace
92
93// Utility functions related to SkRect
94
95namespace {
96
97static inline SkRect getSkRect(const android::FloatRect& rect) {
98 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
99}
100
101static inline SkRect getSkRect(const android::Rect& rect) {
102 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
103}
104
105/**
106 * Verifies that common, simple bounds + clip combinations can be converted into
107 * a single RRect draw call returning true if possible. If true the radii parameter
108 * will be filled with the correct radii values that combined with bounds param will
109 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
110 */
111static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
112 const SkRect& insetCrop, const android::vec2& cornerRadius,
113 SkVector radii[4]) {
114 const bool leftEqual = bounds.fLeft == crop.fLeft;
115 const bool topEqual = bounds.fTop == crop.fTop;
116 const bool rightEqual = bounds.fRight == crop.fRight;
117 const bool bottomEqual = bounds.fBottom == crop.fBottom;
118
119 // In the event that the corners of the bounds only partially align with the crop we
120 // need to ensure that the resulting shape can still be represented as a round rect.
121 // In particular the round rect implementation will scale the value of all corner radii
122 // if the sum of the radius along any edge is greater than the length of that edge.
123 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
124 const bool requiredWidth = bounds.width() > (cornerRadius.x * 2);
125 const bool requiredHeight = bounds.height() > (cornerRadius.y * 2);
126 if (!requiredWidth || !requiredHeight) {
127 return false;
128 }
129
130 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
131 // contained within the cropped shape and does not need rounded.
132 // compute the UpperLeft corner radius
133 if (leftEqual && topEqual) {
134 radii[0].set(cornerRadius.x, cornerRadius.y);
135 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
136 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
137 radii[0].set(0, 0);
138 } else {
139 return false;
140 }
141 // compute the UpperRight corner radius
142 if (rightEqual && topEqual) {
143 radii[1].set(cornerRadius.x, cornerRadius.y);
144 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
145 (topEqual && bounds.fRight <= insetCrop.fRight)) {
146 radii[1].set(0, 0);
147 } else {
148 return false;
149 }
150 // compute the BottomRight corner radius
151 if (rightEqual && bottomEqual) {
152 radii[2].set(cornerRadius.x, cornerRadius.y);
153 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
154 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
155 radii[2].set(0, 0);
156 } else {
157 return false;
158 }
159 // compute the BottomLeft corner radius
160 if (leftEqual && bottomEqual) {
161 radii[3].set(cornerRadius.x, cornerRadius.y);
162 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
163 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
164 radii[3].set(0, 0);
165 } else {
166 return false;
167 }
168
169 return true;
170}
171
172static inline std::pair<SkRRect, SkRRect> getBoundsAndClip(const android::FloatRect& boundsRect,
173 const android::FloatRect& cropRect,
174 const android::vec2& cornerRadius) {
175 const SkRect bounds = getSkRect(boundsRect);
176 const SkRect crop = getSkRect(cropRect);
177
178 SkRRect clip;
179 if (cornerRadius.x > 0 && cornerRadius.y > 0) {
180 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
181 if (bounds == crop || crop.isEmpty()) {
182 return {SkRRect::MakeRectXY(bounds, cornerRadius.x, cornerRadius.y), clip};
183 }
184
185 // This makes an effort to speed up common, simple bounds + clip combinations by
186 // converting them to a single RRect draw. It is possible there are other cases
187 // that can be converted.
188 if (crop.contains(bounds)) {
189 const auto insetCrop = crop.makeInset(cornerRadius.x, cornerRadius.y);
190 if (insetCrop.contains(bounds)) {
191 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
192 }
193
194 SkVector radii[4];
195 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
196 SkRRect intersectionBounds;
197 intersectionBounds.setRectRadii(bounds, radii);
198 return {intersectionBounds, clip};
199 }
200 }
201
202 // we didn't hit any of our fast paths so set the clip to the cropRect
203 clip.setRectXY(crop, cornerRadius.x, cornerRadius.y);
204 }
205
206 // if we hit this point then we either don't have rounded corners or we are going to rely
207 // on the clip to round the corners for us
208 return {SkRRect::MakeRect(bounds), clip};
209}
210
211static inline bool layerHasBlur(const android::renderengine::LayerSettings& layer,
212 bool colorTransformModifiesAlpha) {
213 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
214 // return false if the content is opaque and would therefore occlude the blur
215 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
216 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
217 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
218 }
219 return false;
220}
221
222static inline SkColor getSkColor(const android::vec4& color) {
223 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
224}
225
226static inline SkM44 getSkM44(const android::mat4& matrix) {
227 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
228 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
229 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
230 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
231}
232
233static inline SkPoint3 getSkPoint3(const android::vec3& vector) {
234 return SkPoint3::Make(vector.x, vector.y, vector.z);
235}
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700236} // namespace
rnleec6a73642021-06-04 14:16:42 -0700237
John Reck67b1e2b2020-08-26 13:17:24 -0700238namespace android {
239namespace renderengine {
rnleec6a73642021-06-04 14:16:42 -0700240namespace skia {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700241
242using base::StringAppendF;
243
244std::future<void> SkiaRenderEngine::primeCache() {
245 Cache::primeShaderCache(this);
246 return {};
247}
248
249sk_sp<SkData> SkiaRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
250 // This "cache" does not actually cache anything. It just allows us to
251 // monitor Skia's internal cache. So this method always returns null.
252 return nullptr;
253}
254
255void SkiaRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
256 const SkString& description) {
257 mShadersCachedSinceLastCall++;
258 mTotalShadersCompiled++;
259 ATRACE_FORMAT("SF cache: %i shaders", mTotalShadersCompiled);
260}
261
262int SkiaRenderEngine::reportShadersCompiled() {
263 return mSkSLCacheMonitor.totalShadersCompiled();
264}
Leon Scroggins IIIa37ca992022-02-02 18:08:20 -0500265
266void SkiaRenderEngine::setEnableTracing(bool tracingEnabled) {
267 SkAndroidFrameworkTraceUtil::setEnableTracing(tracingEnabled);
rnleec6a73642021-06-04 14:16:42 -0700268}
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700269
Sally Qi628ef6e2023-03-30 14:49:03 -0700270SkiaRenderEngine::SkiaRenderEngine(RenderEngineType type, PixelFormat pixelFormat,
271 bool useColorManagement, bool supportsBackgroundBlur)
272 : RenderEngine(type),
273 mDefaultPixelFormat(pixelFormat),
274 mUseColorManagement(useColorManagement) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700275 if (supportsBackgroundBlur) {
276 ALOGD("Background Blurs Enabled");
277 mBlurFilter = new KawaseBlurFilter();
278 }
279 mCapture = std::make_unique<SkiaCapture>();
280}
281
282SkiaRenderEngine::~SkiaRenderEngine() { }
283
284// To be called from backend dtors.
285void SkiaRenderEngine::finishRenderingAndAbandonContext() {
286 std::lock_guard<std::mutex> lock(mRenderingMutex);
287
288 if (mBlurFilter) {
289 delete mBlurFilter;
290 }
291
292 if (mGrContext) {
293 mGrContext->flushAndSubmit(true);
294 mGrContext->abandonContext();
295 }
296
297 if (mProtectedGrContext) {
298 mProtectedGrContext->flushAndSubmit(true);
299 mProtectedGrContext->abandonContext();
300 }
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
310 if (getActiveGrContext()) {
311 getActiveGrContext()->purgeUnlockedResources(true);
312 }
313
314 // Backend-specific way to switch to protected context
315 if (useProtectedContextImpl(
316 useProtectedContext ? GrProtected::kYes : GrProtected::kNo)) {
317 mInProtectedContext = useProtectedContext;
318 // given that we are sharing the same thread between two GrContexts we need to
319 // make sure that the thread state is reset when switching between the two.
320 if (getActiveGrContext()) {
321 getActiveGrContext()->resetContext();
322 }
323 }
324}
325
326GrDirectContext* SkiaRenderEngine::getActiveGrContext() {
327 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
328}
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
376void SkiaRenderEngine::ensureGrContextsCreated() {
377 if (mGrContext) {
378 return;
379 }
380
381 GrContextOptions options;
382 options.fDisableDriverCorrectnessWorkarounds = true;
383 options.fDisableDistanceFieldPaths = true;
384 options.fReducedShaderVariations = true;
385 options.fPersistentCache = &mSkSLCacheMonitor;
386 std::tie(mGrContext, mProtectedGrContext) = createDirectContexts(options);
387}
388
389void SkiaRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
390 bool isRenderable) {
Ian Elliott1f0911e2022-09-09 16:31:47 -0600391 // Only run this if RE is running on its own thread. This
392 // way the access to GL operations is guaranteed to be happening on the
393 // same thread.
394 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED &&
395 mRenderEngineType != RenderEngineType::SKIA_VK_THREADED) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700396 return;
397 }
Ian Elliott8506e362023-03-08 12:12:09 -0700398 // We don't attempt to map a buffer if the buffer contains protected content. In GL this is
399 // important because GPU resources for protected buffers are much more limited. (In Vk we
400 // simply match the existing behavior for protected buffers.) In Vk, we never cache any
401 // buffers while in a protected context, since Vk cannot share across contexts, and protected
402 // is less common.
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700403 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Ian Elliott8506e362023-03-08 12:12:09 -0700404 if (isProtectedBuffer ||
405 (mRenderEngineType == RenderEngineType::SKIA_VK_THREADED && isProtected())) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700406 return;
407 }
408 ATRACE_CALL();
409
410 // If we were to support caching protected buffers then we will need to switch the
411 // currently bound context if we are not already using the protected context (and subsequently
412 // switch back after the buffer is cached). However, for non-protected content we can bind
413 // the texture in either GL context because they are initialized with the same share_context
414 // which allows the texture state to be shared between them.
415 auto grContext = getActiveGrContext();
416 auto& cache = mTextureCache;
417
418 std::lock_guard<std::mutex> lock(mRenderingMutex);
419 mGraphicBufferExternalRefs[buffer->getId()]++;
420
421 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
422 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
423 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
424 buffer->toAHardwareBuffer(),
425 isRenderable, mTextureCleanupMgr);
426 cache.insert({buffer->getId(), imageTextureRef});
427 }
428}
429
Alec Mouri92f89fa2023-02-24 00:05:06 +0000430void SkiaRenderEngine::unmapExternalTextureBuffer(sp<GraphicBuffer>&& buffer) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700431 ATRACE_CALL();
432 std::lock_guard<std::mutex> lock(mRenderingMutex);
433 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
434 iter != mGraphicBufferExternalRefs.end()) {
435 if (iter->second == 0) {
436 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
437 "> from RenderEngine texture, but the "
438 "ref count was already zero!",
439 buffer->getId());
440 mGraphicBufferExternalRefs.erase(buffer->getId());
441 return;
442 }
443
444 iter->second--;
445
446 // Swap contexts if needed prior to deleting this buffer
447 // See Issue 1 of
448 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
449 // when a protected context and an unprotected context are part of the same share group,
450 // protected surfaces may not be accessed by an unprotected context, implying that protected
451 // surfaces may only be freed when a protected context is active.
452 const bool inProtected = mInProtectedContext;
453 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
454
455 if (iter->second == 0) {
456 mTextureCache.erase(buffer->getId());
457 mGraphicBufferExternalRefs.erase(buffer->getId());
458 }
459
460 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
461 // are up-to-date.
462 if (inProtected != mInProtectedContext) {
463 useProtectedContext(inProtected);
464 }
465 }
466}
467
Ian Elliott8506e362023-03-08 12:12:09 -0700468std::shared_ptr<AutoBackendTexture::LocalRef> SkiaRenderEngine::getOrCreateBackendTexture(
469 const sp<GraphicBuffer>& buffer, bool isOutputBuffer) {
470 // Do not lookup the buffer in the cache for protected contexts with the SkiaVk back-end
471 if (mRenderEngineType == RenderEngineType::SKIA_GL_THREADED ||
472 (mRenderEngineType == RenderEngineType::SKIA_VK_THREADED && !isProtected())) {
473 if (const auto& it = mTextureCache.find(buffer->getId()); it != mTextureCache.end()) {
474 return it->second;
475 }
476 }
477 return std::make_shared<AutoBackendTexture::LocalRef>(getActiveGrContext(),
478 buffer->toAHardwareBuffer(),
479 isOutputBuffer, mTextureCleanupMgr);
480}
481
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700482bool SkiaRenderEngine::canSkipPostRenderCleanup() const {
483 std::lock_guard<std::mutex> lock(mRenderingMutex);
484 return mTextureCleanupMgr.isEmpty();
485}
486
487void SkiaRenderEngine::cleanupPostRender() {
488 ATRACE_CALL();
489 std::lock_guard<std::mutex> lock(mRenderingMutex);
490 mTextureCleanupMgr.cleanup();
491}
492
493sk_sp<SkShader> SkiaRenderEngine::createRuntimeEffectShader(
494 const RuntimeEffectShaderParameters& parameters) {
495 // The given surface will be stretched by HWUI via matrix transformation
496 // which gets similar results for most surfaces
497 // Determine later on if we need to leverage the stertch shader within
498 // surface flinger
499 const auto& stretchEffect = parameters.layer.stretchEffect;
500 auto shader = parameters.shader;
501 if (stretchEffect.hasEffect()) {
502 const auto targetBuffer = parameters.layer.source.buffer.buffer;
503 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
504 if (graphicBuffer && parameters.shader) {
505 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
506 }
507 }
508
509 if (parameters.requiresLinearEffect) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700510 auto effect =
Sally Qi628ef6e2023-03-30 14:49:03 -0700511 shaders::LinearEffect{.inputDataspace = parameters.layer.sourceDataspace,
512 .outputDataspace = parameters.outputDataSpace,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700513 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha};
514
515 auto effectIter = mRuntimeEffects.find(effect);
516 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
517 if (effectIter == mRuntimeEffects.end()) {
518 runtimeEffect = buildRuntimeEffect(effect);
519 mRuntimeEffects.insert({effect, runtimeEffect});
520 } else {
521 runtimeEffect = effectIter->second;
522 }
Alec Mouri3e5965f2023-04-07 18:00:58 +0000523
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700524 mat4 colorTransform = parameters.layer.colorTransform;
525
526 colorTransform *=
527 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
528 parameters.layerDimmingRatio, 1.f));
Alec Mouri3e5965f2023-04-07 18:00:58 +0000529
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700530 const auto targetBuffer = parameters.layer.source.buffer.buffer;
531 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
532 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouri3e5965f2023-04-07 18:00:58 +0000533 return createLinearEffectShader(parameters.shader, effect, runtimeEffect,
534 std::move(colorTransform), parameters.display.maxLuminance,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700535 parameters.display.currentLuminanceNits,
536 parameters.layer.source.buffer.maxLuminanceNits,
537 hardwareBuffer, parameters.display.renderIntent);
538 }
539 return parameters.shader;
540}
541
542void SkiaRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
543 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
544 // Record display settings when capture is running.
545 std::stringstream displaySettings;
546 PrintTo(display, &displaySettings);
547 // Store the DisplaySettings in additional information.
548 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
549 SkData::MakeWithCString(displaySettings.str().c_str()));
550 }
551
552 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
553 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
554 // displays might have different scaling when compared to the physical screen.
555
556 canvas->clipRect(getSkRect(display.physicalDisplay));
557 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
558
559 const auto clipWidth = display.clip.width();
560 const auto clipHeight = display.clip.height();
561 auto rotatedClipWidth = clipWidth;
562 auto rotatedClipHeight = clipHeight;
563 // Scale is contingent on the rotation result.
564 if (display.orientation & ui::Transform::ROT_90) {
565 std::swap(rotatedClipWidth, rotatedClipHeight);
566 }
567 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
568 static_cast<SkScalar>(rotatedClipWidth);
569 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
570 static_cast<SkScalar>(rotatedClipHeight);
571 canvas->scale(scaleX, scaleY);
572
573 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
574 // back so that the top left corner of the clip is at (0, 0).
575 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
576 canvas->rotate(toDegrees(display.orientation));
577 canvas->translate(-clipWidth / 2, -clipHeight / 2);
578 canvas->translate(-display.clip.left, -display.clip.top);
579}
580
581class AutoSaveRestore {
582public:
583 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
584 ~AutoSaveRestore() { restore(); }
585 void replace(SkCanvas* canvas) {
586 mCanvas = canvas;
587 mSaveCount = canvas->save();
588 }
589 void restore() {
590 if (mCanvas) {
591 mCanvas->restoreToCount(mSaveCount);
592 mCanvas = nullptr;
593 }
594 }
595
596private:
597 SkCanvas* mCanvas;
598 int mSaveCount;
599};
600
601static SkRRect getBlurRRect(const BlurRegion& region) {
602 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
603 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
604 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
605 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
606 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
607 SkRRect roundedRect;
608 roundedRect.setRectRadii(rect, radii);
609 return roundedRect;
610}
611
612// Arbitrary default margin which should be close enough to zero.
613constexpr float kDefaultMargin = 0.0001f;
614static bool equalsWithinMargin(float expected, float value, float margin = kDefaultMargin) {
615 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
616 return std::abs(expected - value) < margin;
617}
618
619namespace {
620template <typename T>
621void logSettings(const T& t) {
622 std::stringstream stream;
623 PrintTo(t, &stream);
624 auto string = stream.str();
625 size_t pos = 0;
626 // Perfetto ignores \n, so split up manually into separate ALOGD statements.
627 const size_t size = string.size();
628 while (pos < size) {
629 const size_t end = std::min(string.find("\n", pos), size);
630 ALOGD("%s", string.substr(pos, end - pos).c_str());
631 pos = end + 1;
632 }
633}
634} // namespace
635
636// Helper class intended to be used on the stack to ensure that texture cleanup
637// is deferred until after this class goes out of scope.
638class DeferTextureCleanup final {
639public:
640 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
641 mMgr.setDeferredStatus(true);
642 }
643 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
644
645private:
646 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
647 AutoBackendTexture::CleanupManager& mMgr;
648};
649
650void SkiaRenderEngine::drawLayersInternal(
Patrick Williams2e9748f2022-08-09 22:48:18 +0000651 const std::shared_ptr<std::promise<FenceResult>>&& resultPromise,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700652 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
653 const std::shared_ptr<ExternalTexture>& buffer, const bool /*useFramebufferCache*/,
654 base::unique_fd&& bufferFence) {
Leon Scroggins III5a655b82022-09-07 13:17:09 -0400655 ATRACE_FORMAT("%s for %s", __func__, display.namePlusId.c_str());
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700656
657 std::lock_guard<std::mutex> lock(mRenderingMutex);
658
659 if (buffer == nullptr) {
660 ALOGE("No output buffer provided. Aborting GPU composition.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000661 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700662 return;
663 }
664
665 validateOutputBufferUsage(buffer->getBuffer());
666
667 auto grContext = getActiveGrContext();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700668
669 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
670 DeferTextureCleanup dtc(mTextureCleanupMgr);
671
Ian Elliott8506e362023-03-08 12:12:09 -0700672 auto surfaceTextureRef = getOrCreateBackendTexture(buffer->getBuffer(), true);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700673
674 // wait on the buffer to be ready to use prior to using it
675 waitFence(grContext, bufferFence);
676
Sally Qi628ef6e2023-03-30 14:49:03 -0700677 sk_sp<SkSurface> dstSurface =
678 surfaceTextureRef->getOrCreateSurface(display.outputDataspace, grContext);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700679
680 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
681 if (dstCanvas == nullptr) {
682 ALOGE("Cannot acquire canvas from Skia.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000683 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700684 return;
685 }
686
687 // setup color filter if necessary
688 sk_sp<SkColorFilter> displayColorTransform;
689 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
690 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
691 }
692 const bool ctModifiesAlpha =
693 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
694
695 // Find the max layer white point to determine the max luminance of the scene...
696 const float maxLayerWhitePoint = std::transform_reduce(
697 layers.cbegin(), layers.cend(), 0.f,
698 [](float left, float right) { return std::max(left, right); },
699 [&](const auto& l) { return l.whitePointNits; });
700
701 // ...and compute the dimming ratio if dimming is requested
702 const float displayDimmingRatio = display.targetLuminanceNits > 0.f &&
John Reck5b02fc42023-06-14 14:41:10 -0400703 maxLayerWhitePoint > 0.f &&
704 (kEnableLayerBrightening || display.targetLuminanceNits > maxLayerWhitePoint)
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700705 ? maxLayerWhitePoint / display.targetLuminanceNits
706 : 1.f;
707
708 // Find if any layers have requested blur, we'll use that info to decide when to render to an
709 // offscreen buffer and when to render to the native buffer.
710 sk_sp<SkSurface> activeSurface(dstSurface);
711 SkCanvas* canvas = dstCanvas;
712 SkiaCapture::OffscreenState offscreenCaptureState;
713 const LayerSettings* blurCompositionLayer = nullptr;
714 if (mBlurFilter) {
715 bool requiresCompositionLayer = false;
716 for (const auto& layer : layers) {
717 // if the layer doesn't have blur or it is not visible then continue
718 if (!layerHasBlur(layer, ctModifiesAlpha)) {
719 continue;
720 }
721 if (layer.backgroundBlurRadius > 0 &&
722 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
723 requiresCompositionLayer = true;
724 }
725 for (auto region : layer.blurRegions) {
726 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
727 requiresCompositionLayer = true;
728 }
729 }
730 if (requiresCompositionLayer) {
731 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
732 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
733 blurCompositionLayer = &layer;
734 break;
735 }
736 }
737 }
738
739 AutoSaveRestore surfaceAutoSaveRestore(canvas);
740 // Clear the entire canvas with a transparent black to prevent ghost images.
741 canvas->clear(SK_ColorTRANSPARENT);
742 initCanvas(canvas, display);
743
744 if (kPrintLayerSettings) {
745 logSettings(display);
746 }
747 for (const auto& layer : layers) {
748 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
749
750 if (kPrintLayerSettings) {
751 logSettings(layer);
752 }
753
754 sk_sp<SkImage> blurInput;
755 if (blurCompositionLayer == &layer) {
756 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
757 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
758
759 // save a snapshot of the activeSurface to use as input to the blur shaders
760 blurInput = activeSurface->makeImageSnapshot();
761
762 // blit the offscreen framebuffer into the destination AHB, but only
763 // if there are blur regions. backgroundBlurRadius blurs the entire
764 // image below, so it can skip this step.
765 if (layer.blurRegions.size()) {
766 SkPaint paint;
767 paint.setBlendMode(SkBlendMode::kSrc);
768 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
769 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
770 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
771 String8::format("SurfaceID|%" PRId64, id).c_str(),
772 nullptr);
773 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
774 } else {
775 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
776 }
777 }
778
779 // assign dstCanvas to canvas and ensure that the canvas state is up to date
780 canvas = dstCanvas;
781 surfaceAutoSaveRestore.replace(canvas);
782 initCanvas(canvas, display);
783
784 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
785 dstSurface->getCanvas()->getSaveCount());
786 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
787 dstSurface->getCanvas()->getTotalMatrix());
788
789 // assign dstSurface to activeSurface
790 activeSurface = dstSurface;
791 }
792
793 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
794 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
795 // Record the name of the layer if the capture is running.
796 std::stringstream layerSettings;
797 PrintTo(layer, &layerSettings);
798 // Store the LayerSettings in additional information.
799 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
800 SkData::MakeWithCString(layerSettings.str().c_str()));
801 }
802 // Layers have a local transform that should be applied to them
803 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
804
805 const auto [bounds, roundRectClip] =
806 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
807 layer.geometry.roundedCornersRadius);
808 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
809 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
810
811 // if multiple layers have blur, then we need to take a snapshot now because
812 // only the lowest layer will have blurImage populated earlier
813 if (!blurInput) {
814 blurInput = activeSurface->makeImageSnapshot();
815 }
816 // rect to be blurred in the coordinate space of blurInput
817 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
818
819 // if the clip needs to be applied then apply it now and make sure
820 // it is restored before we attempt to draw any shadows.
821 SkAutoCanvasRestore acr(canvas, true);
822 if (!roundRectClip.isEmpty()) {
823 canvas->clipRRect(roundRectClip, true);
824 }
825
826 // TODO(b/182216890): Filter out empty layers earlier
827 if (blurRect.width() > 0 && blurRect.height() > 0) {
828 if (layer.backgroundBlurRadius > 0) {
829 ATRACE_NAME("BackgroundBlur");
830 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
831 blurInput, blurRect);
832
833 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
834
835 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
836 blurRect, blurredImage, blurInput);
837 }
838
839 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
840 for (auto region : layer.blurRegions) {
841 if (cachedBlurs[region.blurRadius] == nullptr) {
842 ATRACE_NAME("BlurRegion");
843 cachedBlurs[region.blurRadius] =
844 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
845 blurRect);
846 }
847
848 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
849 region.alpha, blurRect,
850 cachedBlurs[region.blurRadius], blurInput);
851 }
852 }
853 }
854
855 if (layer.shadow.length > 0) {
856 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
857 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
858
859 SkRRect shadowBounds, shadowClip;
860 if (layer.geometry.boundaries == layer.shadow.boundaries) {
861 shadowBounds = bounds;
862 shadowClip = roundRectClip;
863 } else {
864 std::tie(shadowBounds, shadowClip) =
865 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
866 layer.geometry.roundedCornersRadius);
867 }
868
869 // Technically, if bounds is a rect and roundRectClip is not empty,
870 // it means that the bounds and roundedCornersCrop were different
871 // enough that we should intersect them to find the proper shadow.
872 // In practice, this often happens when the two rectangles appear to
873 // not match due to rounding errors. Draw the rounded version, which
874 // looks more like the intent.
875 const auto& rrect =
876 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
877 drawShadow(canvas, rrect, layer.shadow);
878 }
879
880 const float layerDimmingRatio = layer.whitePointNits <= 0.f
881 ? displayDimmingRatio
882 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
883
884 const bool dimInLinearSpace = display.dimmingStage !=
885 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
886
Sally Qi628ef6e2023-03-30 14:49:03 -0700887 const bool isExtendedHdr = (layer.sourceDataspace & ui::Dataspace::RANGE_MASK) ==
888 static_cast<int32_t>(ui::Dataspace::RANGE_EXTENDED) &&
889 (display.outputDataspace & ui::Dataspace::TRANSFER_MASK) ==
890 static_cast<int32_t>(ui::Dataspace::TRANSFER_SRGB);
891
892 const ui::Dataspace runtimeEffectDataspace = !dimInLinearSpace && isExtendedHdr
893 ? static_cast<ui::Dataspace>(
894 (display.outputDataspace & ui::Dataspace::STANDARD_MASK) |
895 ui::Dataspace::TRANSFER_GAMMA2_2 |
896 (display.outputDataspace & ui::Dataspace::RANGE_MASK))
897 : display.outputDataspace;
898
899 // If the input dataspace is range extended, the output dataspace transfer is sRGB
900 // and dimmingStage is GAMMA_OETF, dim in linear space instead, and
901 // set the output dataspace's transfer to be GAMMA2_2.
902 // This allows DPU side to use oetf_gamma_2p2 for extended HDR layer
903 // to avoid tone shift.
904 // The reason of tone shift here is because HDR layers manage white point
905 // luminance in linear space, which color pipelines request GAMMA_OETF break
906 // without a gamma 2.2 fixup.
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700907 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
908 (mUseColorManagement &&
909 needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
Sally Qi628ef6e2023-03-30 14:49:03 -0700910 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio)) ||
911 (!dimInLinearSpace && isExtendedHdr);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700912
913 // quick abort from drawing the remaining portion of the layer
914 if (layer.skipContentDraw ||
915 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
916 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
917 continue;
918 }
919
Alec Mouri8a186102023-04-25 00:34:30 +0000920 // If color management is disabled, then mark the source image with the same colorspace as
921 // the destination surface so that Skia's color management is a no-op.
922 const ui::Dataspace layerDataspace =
923 !mUseColorManagement ? display.outputDataspace : layer.sourceDataspace;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700924
925 SkPaint paint;
926 if (layer.source.buffer.buffer) {
927 ATRACE_NAME("DrawImage");
928 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
929 const auto& item = layer.source.buffer;
Ian Elliott8506e362023-03-08 12:12:09 -0700930 auto imageTextureRef = getOrCreateBackendTexture(item.buffer->getBuffer(), false);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700931
932 // if the layer's buffer has a fence, then we must must respect the fence prior to using
933 // the buffer.
934 if (layer.source.buffer.fence != nullptr) {
935 waitFence(grContext, layer.source.buffer.fence->get());
936 }
937
938 // isOpaque means we need to ignore the alpha in the image,
939 // replacing it with the alpha specified by the LayerSettings. See
940 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
941 // The proper way to do this is to use an SkColorType that ignores
942 // alpha, like kRGB_888x_SkColorType, and that is used if the
943 // incoming image is kRGBA_8888_SkColorType. However, the incoming
944 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
945 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
946 // kRGB_101010x_SkColorType, but it is not yet supported as a source
947 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
948 // meantime, we'll use a workaround that works unless we need to do
949 // any color conversion. The workaround requires that we pretend the
950 // image is already premultiplied, so that we do not premultiply it
951 // before applying SkBlendMode::kPlus.
952 const bool useIsOpaqueWorkaround = item.isOpaque &&
953 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
954 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
955 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
956 : item.isOpaque ? kOpaque_SkAlphaType
957 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
958 : kUnpremul_SkAlphaType;
959 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
960
961 auto texMatrix = getSkM44(item.textureTransform).asM33();
962 // textureTansform was intended to be passed directly into a shader, so when
963 // building the total matrix with the textureTransform we need to first
964 // normalize it, then apply the textureTransform, then scale back up.
965 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
966 texMatrix.postScale(image->width(), image->height());
967
968 SkMatrix matrix;
969 if (!texMatrix.invert(&matrix)) {
970 matrix = texMatrix;
971 }
972 // The shader does not respect the translation, so we add it to the texture
973 // transform for the SkImage. This will make sure that the correct layer contents
974 // are drawn in the correct part of the screen.
975 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
976
977 sk_sp<SkShader> shader;
978
979 if (layer.source.buffer.useTextureFiltering) {
980 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
981 SkSamplingOptions(
982 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
983 &matrix);
984 } else {
985 shader = image->makeShader(SkSamplingOptions(), matrix);
986 }
987
988 if (useIsOpaqueWorkaround) {
989 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
990 SkShaders::Color(SkColors::kBlack,
991 toSkColorSpace(layerDataspace)));
992 }
993
994 paint.setShader(createRuntimeEffectShader(
995 RuntimeEffectShaderParameters{.shader = shader,
996 .layer = layer,
997 .display = display,
998 .undoPremultipliedAlpha = !item.isOpaque &&
999 item.usePremultipliedAlpha,
1000 .requiresLinearEffect = requiresLinearEffect,
1001 .layerDimmingRatio = dimInLinearSpace
1002 ? layerDimmingRatio
Sally Qi628ef6e2023-03-30 14:49:03 -07001003 : 1.f,
1004 .outputDataSpace = runtimeEffectDataspace}));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001005
1006 // Turn on dithering when dimming beyond this (arbitrary) threshold...
1007 static constexpr float kDimmingThreshold = 0.2f;
1008 // ...or we're rendering an HDR layer down to an 8-bit target
1009 // Most HDR standards require at least 10-bits of color depth for source content, so we
1010 // can just extract the transfer function rather than dig into precise gralloc layout.
1011 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
1012 const bool requiresDownsample = isHdrDataspace(layer.sourceDataspace) &&
1013 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
1014 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
1015 paint.setDither(true);
1016 }
1017 paint.setAlphaf(layer.alpha);
1018
1019 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1020 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
1021
1022 // SysUI creates the alpha layer as a coverage layer, which is
1023 // appropriate for the DPU. Use a color matrix to convert it to
1024 // a mask.
1025 // TODO (b/219525258): Handle input as a mask.
1026 //
1027 // The color matrix will convert A8 pixels with no alpha to
1028 // black, as described by this vector. If the display handles
1029 // the color transform, we need to invert it to find the color
1030 // that will result in black after the DPU applies the transform.
1031 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1032 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1033 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1034 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1035 black = colorSpaceMatrix * black;
1036 } else {
1037 // We'll just have to use 0,0,0 as black, which should
1038 // be close to correct.
1039 ALOGI("Could not invert colorTransform!");
1040 }
1041 }
1042 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1043 0, 0, 0, 0, black[1],
1044 0, 0, 0, 0, black[2],
1045 0, 0, 0, -1, 1);
1046 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1047 // On the other hand, if the device doesn't handle it, we
1048 // have to apply it ourselves.
1049 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1050 }
1051 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
1052 }
1053 } else {
1054 ATRACE_NAME("DrawColor");
1055 const auto color = layer.source.solidColor;
1056 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1057 .fG = color.g,
1058 .fB = color.b,
1059 .fA = layer.alpha},
1060 toSkColorSpace(layerDataspace));
1061 paint.setShader(createRuntimeEffectShader(
1062 RuntimeEffectShaderParameters{.shader = shader,
1063 .layer = layer,
1064 .display = display,
1065 .undoPremultipliedAlpha = false,
1066 .requiresLinearEffect = requiresLinearEffect,
Sally Qi628ef6e2023-03-30 14:49:03 -07001067 .layerDimmingRatio = layerDimmingRatio,
1068 .outputDataSpace = runtimeEffectDataspace}));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001069 }
1070
1071 if (layer.disableBlending) {
1072 paint.setBlendMode(SkBlendMode::kSrc);
1073 }
1074
1075 // An A8 buffer will already have the proper color filter attached to
1076 // its paint, including the displayColorTransform as needed.
1077 if (!paint.getColorFilter()) {
1078 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1079 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1080 // can assume a gamma 2.2 transfer function.
1081 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1082 const auto gammaCorrectedDimmingRatio =
1083 std::pow(layerDimmingRatio, kInverseGamma22);
1084 auto dimmingMatrix =
1085 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1086 gammaCorrectedDimmingRatio, 1.f));
1087
1088 const auto colorFilter =
1089 SkColorFilters::Matrix(toSkColorMatrix(std::move(dimmingMatrix)));
1090 paint.setColorFilter(displayColorTransform
1091 ? displayColorTransform->makeComposed(colorFilter)
1092 : colorFilter);
1093 } else {
1094 paint.setColorFilter(displayColorTransform);
1095 }
1096 }
1097
1098 if (!roundRectClip.isEmpty()) {
1099 canvas->clipRRect(roundRectClip, true);
1100 }
1101
1102 if (!bounds.isRect()) {
1103 paint.setAntiAlias(true);
1104 canvas->drawRRect(bounds, paint);
1105 } else {
1106 canvas->drawRect(bounds.rect(), paint);
1107 }
1108 if (kFlushAfterEveryLayer) {
1109 ATRACE_NAME("flush surface");
1110 activeSurface->flush();
1111 }
1112 }
1113 for (const auto& borderRenderInfo : display.borderInfoList) {
1114 SkPaint p;
1115 p.setColor(SkColor4f{borderRenderInfo.color.r, borderRenderInfo.color.g,
1116 borderRenderInfo.color.b, borderRenderInfo.color.a});
1117 p.setAntiAlias(true);
1118 p.setStyle(SkPaint::kStroke_Style);
1119 p.setStrokeWidth(borderRenderInfo.width);
1120 SkRegion sk_region;
1121 SkPath path;
1122
1123 // Construct a final SkRegion using Regions
1124 for (const auto& r : borderRenderInfo.combinedRegion) {
1125 sk_region.op({r.left, r.top, r.right, r.bottom}, SkRegion::kUnion_Op);
1126 }
1127
1128 sk_region.getBoundaryPath(&path);
1129 canvas->drawPath(path, p);
1130 path.close();
1131 }
1132
1133 surfaceAutoSaveRestore.restore();
1134 mCapture->endCapture();
1135 {
1136 ATRACE_NAME("flush surface");
1137 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1138 activeSurface->flush();
1139 }
1140
Alec Mouri0e7d8fd2023-05-03 23:58:43 +00001141 auto drawFence = sp<Fence>::make(flushAndSubmit(grContext));
1142
1143 if (ATRACE_ENABLED()) {
1144 static gui::FenceMonitor sMonitor("RE Completion");
1145 sMonitor.queueFence(drawFence);
1146 }
1147 resultPromise->set_value(std::move(drawFence));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001148}
1149
1150size_t SkiaRenderEngine::getMaxTextureSize() const {
1151 return mGrContext->maxTextureSize();
1152}
1153
1154size_t SkiaRenderEngine::getMaxViewportDims() const {
1155 return mGrContext->maxRenderTargetSize();
1156}
1157
1158void SkiaRenderEngine::drawShadow(SkCanvas* canvas,
1159 const SkRRect& casterRRect,
1160 const ShadowSettings& settings) {
1161 ATRACE_CALL();
1162 const float casterZ = settings.length / 2.0f;
1163 const auto flags =
1164 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1165
1166 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
1167 getSkPoint3(settings.lightPos), settings.lightRadius,
1168 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1169 flags);
1170}
1171
1172void SkiaRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
1173 // This cache multiplier was selected based on review of cache sizes relative
1174 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1175 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1176 // conservative default based on that analysis.
1177 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1178 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1179
1180 // start by resizing the current context
1181 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
1182
1183 // if it is possible to switch contexts then we will resize the other context
1184 const bool originalProtectedState = mInProtectedContext;
1185 useProtectedContext(!mInProtectedContext);
1186 if (mInProtectedContext != originalProtectedState) {
1187 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
1188 // reset back to the initial context that was active when this method was called
1189 useProtectedContext(originalProtectedState);
1190 }
1191}
1192
1193void SkiaRenderEngine::dump(std::string& result) {
1194 // Dump for the specific backend (GLES or Vk)
1195 appendBackendSpecificInfoToDump(result);
1196
1197 // Info about protected content
1198 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1199 supportsProtectedContent());
1200 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1201 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1202 mSkSLCacheMonitor.shadersCachedSinceLastCall());
1203
1204 std::vector<ResourcePair> cpuResourceMap = {
1205 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1206 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1207 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1208 {"skia/sk_resource_cache/tessellated", "Shadows"},
1209 {"skia", "Other"},
1210 };
1211 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1212 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1213 StringAppendF(&result, "Skia CPU Caches: ");
1214 cpuReporter.logTotals(result);
1215 cpuReporter.logOutput(result);
1216
1217 {
1218 std::lock_guard<std::mutex> lock(mRenderingMutex);
1219
1220 std::vector<ResourcePair> gpuResourceMap = {
1221 {"texture_renderbuffer", "Texture/RenderBuffer"},
1222 {"texture", "Texture"},
1223 {"gr_text_blob_cache", "Text"},
1224 {"skia", "Other"},
1225 };
1226 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1227 mGrContext->dumpMemoryStatistics(&gpuReporter);
1228 StringAppendF(&result, "Skia's GPU Caches: ");
1229 gpuReporter.logTotals(result);
1230 gpuReporter.logOutput(result);
1231 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1232 gpuReporter.logOutput(result, true);
1233
1234 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1235 mGraphicBufferExternalRefs.size());
1236 StringAppendF(&result, "Dumping buffer ids...\n");
1237 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1238 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1239 }
1240 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1241 mTextureCache.size());
1242 StringAppendF(&result, "Dumping buffer ids...\n");
1243 // TODO(178539829): It would be nice to know which layer these are coming from and what
1244 // the texture sizes are.
1245 for (const auto& [id, unused] : mTextureCache) {
1246 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1247 }
1248 StringAppendF(&result, "\n");
1249
1250 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
1251 if (mProtectedGrContext) {
1252 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1253 }
1254 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1255 gpuProtectedReporter.logTotals(result);
1256 gpuProtectedReporter.logOutput(result);
1257 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1258 gpuProtectedReporter.logOutput(result, true);
1259
1260 StringAppendF(&result, "\n");
1261 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1262 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1263 StringAppendF(&result, "- inputDataspace: %s\n",
1264 dataspaceDetails(
1265 static_cast<android_dataspace>(linearEffect.inputDataspace))
1266 .c_str());
1267 StringAppendF(&result, "- outputDataspace: %s\n",
1268 dataspaceDetails(
1269 static_cast<android_dataspace>(linearEffect.outputDataspace))
1270 .c_str());
1271 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1272 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1273 }
1274 }
1275 StringAppendF(&result, "\n");
1276}
1277
rnleec6a73642021-06-04 14:16:42 -07001278} // namespace skia
John Reck67b1e2b2020-08-26 13:17:24 -07001279} // namespace renderengine
rnleec6a73642021-06-04 14:16:42 -07001280} // namespace android