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