blob: 6e393f03fabcc58b8d011815ae6efc7e801d8aeb [file] [log] [blame]
John Reck67b1e2b2020-08-26 13:17:24 -07001/*
2 * Copyright 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
John Reck67b1e2b2020-08-26 13:17:24 -070017#undef LOG_TAG
18#define LOG_TAG "RenderEngine"
19#define ATRACE_TAG ATRACE_TAG_GRAPHICS
20
rnleec6a73642021-06-04 14:16:42 -070021#include "SkiaRenderEngine.h"
22
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070023#include <GrBackendSemaphore.h>
24#include <GrContextOptions.h>
Kevin Lubick4011eb92023-09-12 14:18:19 +000025#include <GrTypes.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070026#include <SkBlendMode.h>
27#include <SkCanvas.h>
28#include <SkColor.h>
29#include <SkColorFilter.h>
30#include <SkColorMatrix.h>
31#include <SkColorSpace.h>
32#include <SkData.h>
33#include <SkGraphics.h>
34#include <SkImage.h>
35#include <SkImageFilters.h>
36#include <SkImageInfo.h>
37#include <SkM44.h>
38#include <SkMatrix.h>
39#include <SkPaint.h>
40#include <SkPath.h>
41#include <SkPoint.h>
42#include <SkPoint3.h>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000043#include <SkRRect.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070044#include <SkRect.h>
45#include <SkRefCnt.h>
46#include <SkRegion.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070047#include <SkRuntimeEffect.h>
48#include <SkSamplingOptions.h>
49#include <SkScalar.h>
50#include <SkShader.h>
51#include <SkShadowUtils.h>
52#include <SkString.h>
53#include <SkSurface.h>
54#include <SkTileMode.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070055#include <android-base/stringprintf.h>
Leon Scroggins IIIdf8166e2024-01-25 15:50:56 -050056#include <common/FlagManager.h>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000057#include <gui/FenceMonitor.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070058#include <gui/TraceUtils.h>
Sally Qif6918d42023-08-07 15:28:30 -070059#include <include/gpu/ganesh/SkSurfaceGanesh.h>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000060#include <pthread.h>
61#include <src/core/SkTraceEventCommon.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070062#include <sync/sync.h>
63#include <ui/BlurRegion.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070064#include <ui/DebugUtils.h>
65#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070066#include <ui/HdrRenderTypeUtils.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070067#include <utils/Trace.h>
68
69#include <cmath>
70#include <cstdint>
Alec Mouri0e7d8fd2023-05-03 23:58:43 +000071#include <deque>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070072#include <memory>
73#include <numeric>
74
75#include "Cache.h"
76#include "ColorSpaces.h"
77#include "filters/BlurFilter.h"
78#include "filters/GaussianBlurFilter.h"
79#include "filters/KawaseBlurFilter.h"
80#include "filters/LinearEffect.h"
81#include "log/log_main.h"
82#include "skia/debug/SkiaCapture.h"
83#include "skia/debug/SkiaMemoryReporter.h"
84#include "skia/filters/StretchShaderFactory.h"
85#include "system/graphics-base-v1.0.h"
86
87namespace {
88
89// Debugging settings
90static const bool kPrintLayerSettings = false;
91static const bool kFlushAfterEveryLayer = kPrintLayerSettings;
John Reck5b02fc42023-06-14 14:41:10 -040092static constexpr bool kEnableLayerBrightening = true;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070093
94} // namespace
95
96// Utility functions related to SkRect
97
98namespace {
99
100static inline SkRect getSkRect(const android::FloatRect& rect) {
101 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
102}
103
104static inline SkRect getSkRect(const android::Rect& rect) {
105 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
106}
107
108/**
109 * Verifies that common, simple bounds + clip combinations can be converted into
110 * a single RRect draw call returning true if possible. If true the radii parameter
111 * will be filled with the correct radii values that combined with bounds param will
112 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
113 */
114static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
115 const SkRect& insetCrop, const android::vec2& cornerRadius,
116 SkVector radii[4]) {
117 const bool leftEqual = bounds.fLeft == crop.fLeft;
118 const bool topEqual = bounds.fTop == crop.fTop;
119 const bool rightEqual = bounds.fRight == crop.fRight;
120 const bool bottomEqual = bounds.fBottom == crop.fBottom;
121
122 // In the event that the corners of the bounds only partially align with the crop we
123 // need to ensure that the resulting shape can still be represented as a round rect.
124 // In particular the round rect implementation will scale the value of all corner radii
125 // if the sum of the radius along any edge is greater than the length of that edge.
126 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
127 const bool requiredWidth = bounds.width() > (cornerRadius.x * 2);
128 const bool requiredHeight = bounds.height() > (cornerRadius.y * 2);
129 if (!requiredWidth || !requiredHeight) {
130 return false;
131 }
132
133 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
134 // contained within the cropped shape and does not need rounded.
135 // compute the UpperLeft corner radius
136 if (leftEqual && topEqual) {
137 radii[0].set(cornerRadius.x, cornerRadius.y);
138 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
139 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
140 radii[0].set(0, 0);
141 } else {
142 return false;
143 }
144 // compute the UpperRight corner radius
145 if (rightEqual && topEqual) {
146 radii[1].set(cornerRadius.x, cornerRadius.y);
147 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
148 (topEqual && bounds.fRight <= insetCrop.fRight)) {
149 radii[1].set(0, 0);
150 } else {
151 return false;
152 }
153 // compute the BottomRight corner radius
154 if (rightEqual && bottomEqual) {
155 radii[2].set(cornerRadius.x, cornerRadius.y);
156 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
157 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
158 radii[2].set(0, 0);
159 } else {
160 return false;
161 }
162 // compute the BottomLeft corner radius
163 if (leftEqual && bottomEqual) {
164 radii[3].set(cornerRadius.x, cornerRadius.y);
165 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
166 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
167 radii[3].set(0, 0);
168 } else {
169 return false;
170 }
171
172 return true;
173}
174
175static inline std::pair<SkRRect, SkRRect> getBoundsAndClip(const android::FloatRect& boundsRect,
176 const android::FloatRect& cropRect,
177 const android::vec2& cornerRadius) {
178 const SkRect bounds = getSkRect(boundsRect);
179 const SkRect crop = getSkRect(cropRect);
180
181 SkRRect clip;
182 if (cornerRadius.x > 0 && cornerRadius.y > 0) {
183 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
184 if (bounds == crop || crop.isEmpty()) {
185 return {SkRRect::MakeRectXY(bounds, cornerRadius.x, cornerRadius.y), clip};
186 }
187
188 // This makes an effort to speed up common, simple bounds + clip combinations by
189 // converting them to a single RRect draw. It is possible there are other cases
190 // that can be converted.
191 if (crop.contains(bounds)) {
192 const auto insetCrop = crop.makeInset(cornerRadius.x, cornerRadius.y);
193 if (insetCrop.contains(bounds)) {
194 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
195 }
196
197 SkVector radii[4];
198 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
199 SkRRect intersectionBounds;
200 intersectionBounds.setRectRadii(bounds, radii);
201 return {intersectionBounds, clip};
202 }
203 }
204
205 // we didn't hit any of our fast paths so set the clip to the cropRect
206 clip.setRectXY(crop, cornerRadius.x, cornerRadius.y);
207 }
208
209 // if we hit this point then we either don't have rounded corners or we are going to rely
210 // on the clip to round the corners for us
211 return {SkRRect::MakeRect(bounds), clip};
212}
213
214static inline bool layerHasBlur(const android::renderengine::LayerSettings& layer,
215 bool colorTransformModifiesAlpha) {
216 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
217 // return false if the content is opaque and would therefore occlude the blur
218 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
219 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
220 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
221 }
222 return false;
223}
224
225static inline SkColor getSkColor(const android::vec4& color) {
226 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
227}
228
229static inline SkM44 getSkM44(const android::mat4& matrix) {
230 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
231 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
232 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
233 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
234}
235
236static inline SkPoint3 getSkPoint3(const android::vec3& vector) {
237 return SkPoint3::Make(vector.x, vector.y, vector.z);
238}
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700239} // namespace
rnleec6a73642021-06-04 14:16:42 -0700240
John Reck67b1e2b2020-08-26 13:17:24 -0700241namespace android {
242namespace renderengine {
rnleec6a73642021-06-04 14:16:42 -0700243namespace skia {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700244
245using base::StringAppendF;
246
Bruno BELANYIb9b5b702023-10-13 13:25:11 +0000247std::future<void> SkiaRenderEngine::primeCache(bool shouldPrimeUltraHDR) {
248 Cache::primeShaderCache(this, shouldPrimeUltraHDR);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700249 return {};
250}
251
252sk_sp<SkData> SkiaRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
253 // This "cache" does not actually cache anything. It just allows us to
254 // monitor Skia's internal cache. So this method always returns null.
255 return nullptr;
256}
257
258void SkiaRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
259 const SkString& description) {
260 mShadersCachedSinceLastCall++;
261 mTotalShadersCompiled++;
262 ATRACE_FORMAT("SF cache: %i shaders", mTotalShadersCompiled);
263}
264
265int SkiaRenderEngine::reportShadersCompiled() {
266 return mSkSLCacheMonitor.totalShadersCompiled();
267}
Leon Scroggins IIIa37ca992022-02-02 18:08:20 -0500268
269void SkiaRenderEngine::setEnableTracing(bool tracingEnabled) {
270 SkAndroidFrameworkTraceUtil::setEnableTracing(tracingEnabled);
rnleec6a73642021-06-04 14:16:42 -0700271}
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700272
Leon Scroggins III696bf932024-01-24 15:21:05 -0500273SkiaRenderEngine::SkiaRenderEngine(Threaded threaded, PixelFormat pixelFormat,
Alec Mouri47bcb072023-08-15 02:02:49 +0000274 bool supportsBackgroundBlur)
Leon Scroggins III696bf932024-01-24 15:21:05 -0500275 : RenderEngine(threaded), mDefaultPixelFormat(pixelFormat) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700276 if (supportsBackgroundBlur) {
277 ALOGD("Background Blurs Enabled");
278 mBlurFilter = new KawaseBlurFilter();
279 }
280 mCapture = std::make_unique<SkiaCapture>();
281}
282
283SkiaRenderEngine::~SkiaRenderEngine() { }
284
285// To be called from backend dtors.
286void SkiaRenderEngine::finishRenderingAndAbandonContext() {
287 std::lock_guard<std::mutex> lock(mRenderingMutex);
288
289 if (mBlurFilter) {
290 delete mBlurFilter;
291 }
292
293 if (mGrContext) {
Kevin Lubick4011eb92023-09-12 14:18:19 +0000294 mGrContext->flushAndSubmit(GrSyncCpu::kYes);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700295 mGrContext->abandonContext();
296 }
297
298 if (mProtectedGrContext) {
Kevin Lubick4011eb92023-09-12 14:18:19 +0000299 mProtectedGrContext->flushAndSubmit(GrSyncCpu::kYes);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700300 mProtectedGrContext->abandonContext();
301 }
302}
303
304void SkiaRenderEngine::useProtectedContext(bool useProtectedContext) {
305 if (useProtectedContext == mInProtectedContext ||
306 (useProtectedContext && !supportsProtectedContent())) {
307 return;
308 }
309
310 // release any scratch resources before switching into a new mode
311 if (getActiveGrContext()) {
Kevin Lubick4011eb92023-09-12 14:18:19 +0000312 getActiveGrContext()->purgeUnlockedResources(GrPurgeResourceOptions::kScratchResourcesOnly);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700313 }
314
315 // Backend-specific way to switch to protected context
316 if (useProtectedContextImpl(
317 useProtectedContext ? GrProtected::kYes : GrProtected::kNo)) {
318 mInProtectedContext = useProtectedContext;
319 // given that we are sharing the same thread between two GrContexts we need to
320 // make sure that the thread state is reset when switching between the two.
321 if (getActiveGrContext()) {
322 getActiveGrContext()->resetContext();
323 }
324 }
325}
326
327GrDirectContext* SkiaRenderEngine::getActiveGrContext() {
328 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
329}
330
331static float toDegrees(uint32_t transform) {
332 switch (transform) {
333 case ui::Transform::ROT_90:
334 return 90.0;
335 case ui::Transform::ROT_180:
336 return 180.0;
337 case ui::Transform::ROT_270:
338 return 270.0;
339 default:
340 return 0.0;
341 }
342}
343
344static SkColorMatrix toSkColorMatrix(const android::mat4& matrix) {
345 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
346 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
347 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
348 matrix[3][3], 0);
349}
350
351static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
352 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
353 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
354
355 // Treat unsupported dataspaces as srgb
356 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
357 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
358 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
359 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
360 }
361
362 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
363 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
364 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
365 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
366 }
367
368 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
369 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
370 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
371 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
372
373 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
374 sourceTransfer != destTransfer;
375}
376
377void SkiaRenderEngine::ensureGrContextsCreated() {
378 if (mGrContext) {
379 return;
380 }
381
382 GrContextOptions options;
383 options.fDisableDriverCorrectnessWorkarounds = true;
384 options.fDisableDistanceFieldPaths = true;
385 options.fReducedShaderVariations = true;
386 options.fPersistentCache = &mSkSLCacheMonitor;
387 std::tie(mGrContext, mProtectedGrContext) = createDirectContexts(options);
388}
389
390void SkiaRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
391 bool isRenderable) {
Ian Elliott1f0911e2022-09-09 16:31:47 -0600392 // Only run this if RE is running on its own thread. This
Leon Scroggins III696bf932024-01-24 15:21:05 -0500393 // way the access to GL/VK operations is guaranteed to be happening on the
Ian Elliott1f0911e2022-09-09 16:31:47 -0600394 // same thread.
Leon Scroggins III696bf932024-01-24 15:21:05 -0500395 if (!isThreaded()) {
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
Robert Phillips59f71732023-08-23 15:18:27 -0400400 // simply match the existing behavior for protected buffers.) We also never cache any
401 // buffers while in a protected context.
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700402 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Alec Mouri07196db2023-09-12 23:33:49 +0000403 // Don't attempt to map buffers if we're not gpu sampleable. Callers shouldn't send a buffer
404 // over to RenderEngine.
405 const bool isGpuSampleable = buffer->getUsage() & GRALLOC_USAGE_HW_TEXTURE;
406 if (isProtectedBuffer || isProtected() || !isGpuSampleable) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700407 return;
408 }
409 ATRACE_CALL();
410
411 // If we were to support caching protected buffers then we will need to switch the
412 // currently bound context if we are not already using the protected context (and subsequently
413 // switch back after the buffer is cached). However, for non-protected content we can bind
414 // the texture in either GL context because they are initialized with the same share_context
415 // which allows the texture state to be shared between them.
416 auto grContext = getActiveGrContext();
417 auto& cache = mTextureCache;
418
419 std::lock_guard<std::mutex> lock(mRenderingMutex);
420 mGraphicBufferExternalRefs[buffer->getId()]++;
421
422 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Leon Scroggins IIIdf8166e2024-01-25 15:50:56 -0500423 if (FlagManager::getInstance().renderable_buffer_usage()) {
424 isRenderable = buffer->getUsage() & GRALLOC_USAGE_HW_RENDER;
425 }
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700426 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
427 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
428 buffer->toAHardwareBuffer(),
429 isRenderable, mTextureCleanupMgr);
430 cache.insert({buffer->getId(), imageTextureRef});
431 }
432}
433
Alec Mouri92f89fa2023-02-24 00:05:06 +0000434void SkiaRenderEngine::unmapExternalTextureBuffer(sp<GraphicBuffer>&& buffer) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700435 ATRACE_CALL();
436 std::lock_guard<std::mutex> lock(mRenderingMutex);
437 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
438 iter != mGraphicBufferExternalRefs.end()) {
439 if (iter->second == 0) {
440 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
441 "> from RenderEngine texture, but the "
442 "ref count was already zero!",
443 buffer->getId());
444 mGraphicBufferExternalRefs.erase(buffer->getId());
445 return;
446 }
447
448 iter->second--;
449
450 // Swap contexts if needed prior to deleting this buffer
451 // See Issue 1 of
452 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
453 // when a protected context and an unprotected context are part of the same share group,
454 // protected surfaces may not be accessed by an unprotected context, implying that protected
455 // surfaces may only be freed when a protected context is active.
456 const bool inProtected = mInProtectedContext;
457 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
458
459 if (iter->second == 0) {
460 mTextureCache.erase(buffer->getId());
461 mGraphicBufferExternalRefs.erase(buffer->getId());
462 }
463
464 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
465 // are up-to-date.
466 if (inProtected != mInProtectedContext) {
467 useProtectedContext(inProtected);
468 }
469 }
470}
471
Ian Elliott8506e362023-03-08 12:12:09 -0700472std::shared_ptr<AutoBackendTexture::LocalRef> SkiaRenderEngine::getOrCreateBackendTexture(
473 const sp<GraphicBuffer>& buffer, bool isOutputBuffer) {
Robert Phillips59f71732023-08-23 15:18:27 -0400474 // Do not lookup the buffer in the cache for protected contexts
475 if (!isProtected()) {
Ian Elliott8506e362023-03-08 12:12:09 -0700476 if (const auto& it = mTextureCache.find(buffer->getId()); it != mTextureCache.end()) {
477 return it->second;
478 }
479 }
480 return std::make_shared<AutoBackendTexture::LocalRef>(getActiveGrContext(),
481 buffer->toAHardwareBuffer(),
482 isOutputBuffer, mTextureCleanupMgr);
483}
484
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700485bool SkiaRenderEngine::canSkipPostRenderCleanup() const {
486 std::lock_guard<std::mutex> lock(mRenderingMutex);
487 return mTextureCleanupMgr.isEmpty();
488}
489
490void SkiaRenderEngine::cleanupPostRender() {
491 ATRACE_CALL();
492 std::lock_guard<std::mutex> lock(mRenderingMutex);
493 mTextureCleanupMgr.cleanup();
494}
495
496sk_sp<SkShader> SkiaRenderEngine::createRuntimeEffectShader(
497 const RuntimeEffectShaderParameters& parameters) {
498 // The given surface will be stretched by HWUI via matrix transformation
499 // which gets similar results for most surfaces
500 // Determine later on if we need to leverage the stertch shader within
501 // surface flinger
502 const auto& stretchEffect = parameters.layer.stretchEffect;
503 auto shader = parameters.shader;
504 if (stretchEffect.hasEffect()) {
505 const auto targetBuffer = parameters.layer.source.buffer.buffer;
506 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
507 if (graphicBuffer && parameters.shader) {
508 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
509 }
510 }
511
512 if (parameters.requiresLinearEffect) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700513 auto effect =
Sally Qi628ef6e2023-03-30 14:49:03 -0700514 shaders::LinearEffect{.inputDataspace = parameters.layer.sourceDataspace,
515 .outputDataspace = parameters.outputDataSpace,
Alec Mourie0bb6f42023-08-02 22:41:52 +0000516 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha,
517 .fakeOutputDataspace = parameters.fakeOutputDataspace};
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700518
519 auto effectIter = mRuntimeEffects.find(effect);
520 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
521 if (effectIter == mRuntimeEffects.end()) {
522 runtimeEffect = buildRuntimeEffect(effect);
523 mRuntimeEffects.insert({effect, runtimeEffect});
524 } else {
525 runtimeEffect = effectIter->second;
526 }
Alec Mouri3e5965f2023-04-07 18:00:58 +0000527
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700528 mat4 colorTransform = parameters.layer.colorTransform;
529
530 colorTransform *=
531 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
532 parameters.layerDimmingRatio, 1.f));
Alec Mouri3e5965f2023-04-07 18:00:58 +0000533
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700534 const auto targetBuffer = parameters.layer.source.buffer.buffer;
535 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
536 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouri3e5965f2023-04-07 18:00:58 +0000537 return createLinearEffectShader(parameters.shader, effect, runtimeEffect,
538 std::move(colorTransform), parameters.display.maxLuminance,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700539 parameters.display.currentLuminanceNits,
540 parameters.layer.source.buffer.maxLuminanceNits,
541 hardwareBuffer, parameters.display.renderIntent);
542 }
543 return parameters.shader;
544}
545
546void SkiaRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
547 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
548 // Record display settings when capture is running.
549 std::stringstream displaySettings;
550 PrintTo(display, &displaySettings);
551 // Store the DisplaySettings in additional information.
552 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
553 SkData::MakeWithCString(displaySettings.str().c_str()));
554 }
555
556 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
557 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
558 // displays might have different scaling when compared to the physical screen.
559
560 canvas->clipRect(getSkRect(display.physicalDisplay));
561 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
562
563 const auto clipWidth = display.clip.width();
564 const auto clipHeight = display.clip.height();
565 auto rotatedClipWidth = clipWidth;
566 auto rotatedClipHeight = clipHeight;
567 // Scale is contingent on the rotation result.
568 if (display.orientation & ui::Transform::ROT_90) {
569 std::swap(rotatedClipWidth, rotatedClipHeight);
570 }
571 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
572 static_cast<SkScalar>(rotatedClipWidth);
573 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
574 static_cast<SkScalar>(rotatedClipHeight);
575 canvas->scale(scaleX, scaleY);
576
577 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
578 // back so that the top left corner of the clip is at (0, 0).
579 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
580 canvas->rotate(toDegrees(display.orientation));
581 canvas->translate(-clipWidth / 2, -clipHeight / 2);
582 canvas->translate(-display.clip.left, -display.clip.top);
583}
584
585class AutoSaveRestore {
586public:
587 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
588 ~AutoSaveRestore() { restore(); }
589 void replace(SkCanvas* canvas) {
590 mCanvas = canvas;
591 mSaveCount = canvas->save();
592 }
593 void restore() {
594 if (mCanvas) {
595 mCanvas->restoreToCount(mSaveCount);
596 mCanvas = nullptr;
597 }
598 }
599
600private:
601 SkCanvas* mCanvas;
602 int mSaveCount;
603};
604
605static SkRRect getBlurRRect(const BlurRegion& region) {
606 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
607 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
608 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
609 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
610 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
611 SkRRect roundedRect;
612 roundedRect.setRectRadii(rect, radii);
613 return roundedRect;
614}
615
616// Arbitrary default margin which should be close enough to zero.
617constexpr float kDefaultMargin = 0.0001f;
618static bool equalsWithinMargin(float expected, float value, float margin = kDefaultMargin) {
619 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
620 return std::abs(expected - value) < margin;
621}
622
623namespace {
624template <typename T>
625void logSettings(const T& t) {
626 std::stringstream stream;
627 PrintTo(t, &stream);
628 auto string = stream.str();
629 size_t pos = 0;
630 // Perfetto ignores \n, so split up manually into separate ALOGD statements.
631 const size_t size = string.size();
632 while (pos < size) {
633 const size_t end = std::min(string.find("\n", pos), size);
634 ALOGD("%s", string.substr(pos, end - pos).c_str());
635 pos = end + 1;
636 }
637}
638} // namespace
639
640// Helper class intended to be used on the stack to ensure that texture cleanup
641// is deferred until after this class goes out of scope.
642class DeferTextureCleanup final {
643public:
644 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
645 mMgr.setDeferredStatus(true);
646 }
647 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
648
649private:
650 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
651 AutoBackendTexture::CleanupManager& mMgr;
652};
653
654void SkiaRenderEngine::drawLayersInternal(
Patrick Williams2e9748f2022-08-09 22:48:18 +0000655 const std::shared_ptr<std::promise<FenceResult>>&& resultPromise,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700656 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
Alec Mourif29700f2023-08-17 21:53:31 +0000657 const std::shared_ptr<ExternalTexture>& buffer, base::unique_fd&& bufferFence) {
Leon Scroggins III5a655b82022-09-07 13:17:09 -0400658 ATRACE_FORMAT("%s for %s", __func__, display.namePlusId.c_str());
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700659
660 std::lock_guard<std::mutex> lock(mRenderingMutex);
661
662 if (buffer == nullptr) {
663 ALOGE("No output buffer provided. Aborting GPU composition.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000664 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700665 return;
666 }
667
668 validateOutputBufferUsage(buffer->getBuffer());
669
670 auto grContext = getActiveGrContext();
Leon Scroggins III41c00c52023-06-21 15:55:55 -0400671 LOG_ALWAYS_FATAL_IF(grContext->abandoned(), "GrContext is abandoned/device lost at start of %s",
672 __func__);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700673
674 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
675 DeferTextureCleanup dtc(mTextureCleanupMgr);
676
Ian Elliott8506e362023-03-08 12:12:09 -0700677 auto surfaceTextureRef = getOrCreateBackendTexture(buffer->getBuffer(), true);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700678
679 // wait on the buffer to be ready to use prior to using it
680 waitFence(grContext, bufferFence);
681
Sally Qi628ef6e2023-03-30 14:49:03 -0700682 sk_sp<SkSurface> dstSurface =
683 surfaceTextureRef->getOrCreateSurface(display.outputDataspace, grContext);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700684
685 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
686 if (dstCanvas == nullptr) {
687 ALOGE("Cannot acquire canvas from Skia.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000688 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700689 return;
690 }
691
692 // setup color filter if necessary
693 sk_sp<SkColorFilter> displayColorTransform;
694 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
695 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
696 }
697 const bool ctModifiesAlpha =
698 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
699
700 // Find the max layer white point to determine the max luminance of the scene...
701 const float maxLayerWhitePoint = std::transform_reduce(
702 layers.cbegin(), layers.cend(), 0.f,
703 [](float left, float right) { return std::max(left, right); },
704 [&](const auto& l) { return l.whitePointNits; });
705
706 // ...and compute the dimming ratio if dimming is requested
707 const float displayDimmingRatio = display.targetLuminanceNits > 0.f &&
John Reck5b02fc42023-06-14 14:41:10 -0400708 maxLayerWhitePoint > 0.f &&
709 (kEnableLayerBrightening || display.targetLuminanceNits > maxLayerWhitePoint)
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700710 ? maxLayerWhitePoint / display.targetLuminanceNits
711 : 1.f;
712
713 // Find if any layers have requested blur, we'll use that info to decide when to render to an
714 // offscreen buffer and when to render to the native buffer.
715 sk_sp<SkSurface> activeSurface(dstSurface);
716 SkCanvas* canvas = dstCanvas;
717 SkiaCapture::OffscreenState offscreenCaptureState;
718 const LayerSettings* blurCompositionLayer = nullptr;
Leon Scroggins IIIf31b4bc2023-08-25 10:40:27 -0400719 if (mBlurFilter) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700720 bool requiresCompositionLayer = false;
721 for (const auto& layer : layers) {
722 // if the layer doesn't have blur or it is not visible then continue
723 if (!layerHasBlur(layer, ctModifiesAlpha)) {
724 continue;
725 }
726 if (layer.backgroundBlurRadius > 0 &&
727 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
728 requiresCompositionLayer = true;
729 }
730 for (auto region : layer.blurRegions) {
731 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
732 requiresCompositionLayer = true;
733 }
734 }
735 if (requiresCompositionLayer) {
736 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
737 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
738 blurCompositionLayer = &layer;
739 break;
740 }
741 }
742 }
743
744 AutoSaveRestore surfaceAutoSaveRestore(canvas);
745 // Clear the entire canvas with a transparent black to prevent ghost images.
746 canvas->clear(SK_ColorTRANSPARENT);
747 initCanvas(canvas, display);
748
749 if (kPrintLayerSettings) {
750 logSettings(display);
751 }
752 for (const auto& layer : layers) {
753 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
754
755 if (kPrintLayerSettings) {
756 logSettings(layer);
757 }
758
759 sk_sp<SkImage> blurInput;
760 if (blurCompositionLayer == &layer) {
761 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
762 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
763
764 // save a snapshot of the activeSurface to use as input to the blur shaders
765 blurInput = activeSurface->makeImageSnapshot();
766
Leon Scroggins III48a60cc2024-01-31 12:41:33 -0500767 // blit the offscreen framebuffer into the destination AHB. This ensures that
768 // even if the blurred image does not cover the screen (for example, during
769 // a rotation animation, or if blur regions are used), the entire screen is
770 // initialized.
771 if (layer.blurRegions.size() || FlagManager::getInstance().restore_blur_step()) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700772 SkPaint paint;
773 paint.setBlendMode(SkBlendMode::kSrc);
774 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
775 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
776 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
777 String8::format("SurfaceID|%" PRId64, id).c_str(),
778 nullptr);
779 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
780 } else {
781 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
782 }
783 }
784
785 // assign dstCanvas to canvas and ensure that the canvas state is up to date
786 canvas = dstCanvas;
787 surfaceAutoSaveRestore.replace(canvas);
788 initCanvas(canvas, display);
789
790 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
791 dstSurface->getCanvas()->getSaveCount());
792 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
793 dstSurface->getCanvas()->getTotalMatrix());
794
795 // assign dstSurface to activeSurface
796 activeSurface = dstSurface;
797 }
798
799 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
800 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
801 // Record the name of the layer if the capture is running.
802 std::stringstream layerSettings;
803 PrintTo(layer, &layerSettings);
804 // Store the LayerSettings in additional information.
805 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
806 SkData::MakeWithCString(layerSettings.str().c_str()));
807 }
808 // Layers have a local transform that should be applied to them
809 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
810
811 const auto [bounds, roundRectClip] =
812 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
813 layer.geometry.roundedCornersRadius);
Leon Scroggins IIIf31b4bc2023-08-25 10:40:27 -0400814 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700815 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
816
817 // if multiple layers have blur, then we need to take a snapshot now because
818 // only the lowest layer will have blurImage populated earlier
819 if (!blurInput) {
820 blurInput = activeSurface->makeImageSnapshot();
821 }
Leon Scroggins IIIa09cddc2023-07-25 09:34:11 -0400822
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700823 // rect to be blurred in the coordinate space of blurInput
Leon Scroggins IIIa09cddc2023-07-25 09:34:11 -0400824 SkRect blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
825
826 // Some layers may be much bigger than the screen. If we used
827 // `blurRect` directly, this would allocate a large buffer with no
828 // benefit. Apply the clip, which already takes the display size
829 // into account. The clipped size will then be used to calculate the
830 // size of the buffer we will create for blurring.
831 if (!blurRect.intersect(SkRect::Make(canvas->getDeviceClipBounds()))) {
832 // This should not happen, but if it did, we would use the full
833 // sized layer, which should still be fine.
834 ALOGW("blur bounds does not intersect display clip!");
835 }
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700836
837 // if the clip needs to be applied then apply it now and make sure
838 // it is restored before we attempt to draw any shadows.
839 SkAutoCanvasRestore acr(canvas, true);
840 if (!roundRectClip.isEmpty()) {
841 canvas->clipRRect(roundRectClip, true);
842 }
843
844 // TODO(b/182216890): Filter out empty layers earlier
845 if (blurRect.width() > 0 && blurRect.height() > 0) {
846 if (layer.backgroundBlurRadius > 0) {
847 ATRACE_NAME("BackgroundBlur");
848 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
849 blurInput, blurRect);
850
851 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
852
853 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
854 blurRect, blurredImage, blurInput);
855 }
856
857 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
858 for (auto region : layer.blurRegions) {
859 if (cachedBlurs[region.blurRadius] == nullptr) {
860 ATRACE_NAME("BlurRegion");
861 cachedBlurs[region.blurRadius] =
862 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
863 blurRect);
864 }
865
866 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
867 region.alpha, blurRect,
868 cachedBlurs[region.blurRadius], blurInput);
869 }
870 }
871 }
872
873 if (layer.shadow.length > 0) {
874 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
875 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
876
877 SkRRect shadowBounds, shadowClip;
878 if (layer.geometry.boundaries == layer.shadow.boundaries) {
879 shadowBounds = bounds;
880 shadowClip = roundRectClip;
881 } else {
882 std::tie(shadowBounds, shadowClip) =
883 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
884 layer.geometry.roundedCornersRadius);
885 }
886
887 // Technically, if bounds is a rect and roundRectClip is not empty,
888 // it means that the bounds and roundedCornersCrop were different
889 // enough that we should intersect them to find the proper shadow.
890 // In practice, this often happens when the two rectangles appear to
891 // not match due to rounding errors. Draw the rounded version, which
892 // looks more like the intent.
893 const auto& rrect =
894 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
895 drawShadow(canvas, rrect, layer.shadow);
896 }
897
898 const float layerDimmingRatio = layer.whitePointNits <= 0.f
899 ? displayDimmingRatio
900 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
901
902 const bool dimInLinearSpace = display.dimmingStage !=
903 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
904
Sally Qi628ef6e2023-03-30 14:49:03 -0700905 const bool isExtendedHdr = (layer.sourceDataspace & ui::Dataspace::RANGE_MASK) ==
906 static_cast<int32_t>(ui::Dataspace::RANGE_EXTENDED) &&
907 (display.outputDataspace & ui::Dataspace::TRANSFER_MASK) ==
908 static_cast<int32_t>(ui::Dataspace::TRANSFER_SRGB);
909
Alec Mourie0bb6f42023-08-02 22:41:52 +0000910 const bool useFakeOutputDataspaceForRuntimeEffect = !dimInLinearSpace && isExtendedHdr;
911
912 const ui::Dataspace fakeDataspace = useFakeOutputDataspaceForRuntimeEffect
Sally Qi628ef6e2023-03-30 14:49:03 -0700913 ? static_cast<ui::Dataspace>(
914 (display.outputDataspace & ui::Dataspace::STANDARD_MASK) |
915 ui::Dataspace::TRANSFER_GAMMA2_2 |
916 (display.outputDataspace & ui::Dataspace::RANGE_MASK))
Alec Mourie0bb6f42023-08-02 22:41:52 +0000917 : ui::Dataspace::UNKNOWN;
Sally Qi628ef6e2023-03-30 14:49:03 -0700918
919 // If the input dataspace is range extended, the output dataspace transfer is sRGB
920 // and dimmingStage is GAMMA_OETF, dim in linear space instead, and
921 // set the output dataspace's transfer to be GAMMA2_2.
922 // This allows DPU side to use oetf_gamma_2p2 for extended HDR layer
923 // to avoid tone shift.
924 // The reason of tone shift here is because HDR layers manage white point
925 // luminance in linear space, which color pipelines request GAMMA_OETF break
926 // without a gamma 2.2 fixup.
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700927 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
Alec Mouri47bcb072023-08-15 02:02:49 +0000928 (needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
Sally Qi628ef6e2023-03-30 14:49:03 -0700929 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio)) ||
930 (!dimInLinearSpace && isExtendedHdr);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700931
932 // quick abort from drawing the remaining portion of the layer
933 if (layer.skipContentDraw ||
934 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
935 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
936 continue;
937 }
938
Alec Mouri47bcb072023-08-15 02:02:49 +0000939 const ui::Dataspace layerDataspace = layer.sourceDataspace;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700940
941 SkPaint paint;
942 if (layer.source.buffer.buffer) {
943 ATRACE_NAME("DrawImage");
944 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
945 const auto& item = layer.source.buffer;
Ian Elliott8506e362023-03-08 12:12:09 -0700946 auto imageTextureRef = getOrCreateBackendTexture(item.buffer->getBuffer(), false);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700947
948 // if the layer's buffer has a fence, then we must must respect the fence prior to using
949 // the buffer.
950 if (layer.source.buffer.fence != nullptr) {
951 waitFence(grContext, layer.source.buffer.fence->get());
952 }
953
954 // isOpaque means we need to ignore the alpha in the image,
955 // replacing it with the alpha specified by the LayerSettings. See
956 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
957 // The proper way to do this is to use an SkColorType that ignores
958 // alpha, like kRGB_888x_SkColorType, and that is used if the
959 // incoming image is kRGBA_8888_SkColorType. However, the incoming
960 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
961 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
962 // kRGB_101010x_SkColorType, but it is not yet supported as a source
963 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
964 // meantime, we'll use a workaround that works unless we need to do
965 // any color conversion. The workaround requires that we pretend the
966 // image is already premultiplied, so that we do not premultiply it
967 // before applying SkBlendMode::kPlus.
968 const bool useIsOpaqueWorkaround = item.isOpaque &&
969 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
970 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
971 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
972 : item.isOpaque ? kOpaque_SkAlphaType
973 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
974 : kUnpremul_SkAlphaType;
975 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
976
977 auto texMatrix = getSkM44(item.textureTransform).asM33();
978 // textureTansform was intended to be passed directly into a shader, so when
979 // building the total matrix with the textureTransform we need to first
980 // normalize it, then apply the textureTransform, then scale back up.
981 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
982 texMatrix.postScale(image->width(), image->height());
983
984 SkMatrix matrix;
985 if (!texMatrix.invert(&matrix)) {
986 matrix = texMatrix;
987 }
988 // The shader does not respect the translation, so we add it to the texture
989 // transform for the SkImage. This will make sure that the correct layer contents
990 // are drawn in the correct part of the screen.
991 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
992
993 sk_sp<SkShader> shader;
994
995 if (layer.source.buffer.useTextureFiltering) {
996 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
997 SkSamplingOptions(
998 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
999 &matrix);
1000 } else {
1001 shader = image->makeShader(SkSamplingOptions(), matrix);
1002 }
1003
1004 if (useIsOpaqueWorkaround) {
1005 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1006 SkShaders::Color(SkColors::kBlack,
1007 toSkColorSpace(layerDataspace)));
1008 }
1009
1010 paint.setShader(createRuntimeEffectShader(
1011 RuntimeEffectShaderParameters{.shader = shader,
1012 .layer = layer,
1013 .display = display,
1014 .undoPremultipliedAlpha = !item.isOpaque &&
1015 item.usePremultipliedAlpha,
1016 .requiresLinearEffect = requiresLinearEffect,
1017 .layerDimmingRatio = dimInLinearSpace
1018 ? layerDimmingRatio
Sally Qi628ef6e2023-03-30 14:49:03 -07001019 : 1.f,
Alec Mourie0bb6f42023-08-02 22:41:52 +00001020 .outputDataSpace = display.outputDataspace,
1021 .fakeOutputDataspace = fakeDataspace}));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001022
1023 // Turn on dithering when dimming beyond this (arbitrary) threshold...
linkai296566e2024-01-22 20:58:15 +08001024 static constexpr float kDimmingThreshold = 0.9f;
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001025 // ...or we're rendering an HDR layer down to an 8-bit target
1026 // Most HDR standards require at least 10-bits of color depth for source content, so we
1027 // can just extract the transfer function rather than dig into precise gralloc layout.
1028 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
Sally Qif6918d42023-08-07 15:28:30 -07001029 const bool requiresDownsample =
1030 getHdrRenderType(layer.sourceDataspace,
1031 std::optional<ui::PixelFormat>(static_cast<ui::PixelFormat>(
1032 buffer->getPixelFormat()))) != HdrRenderType::SDR &&
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001033 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
1034 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
1035 paint.setDither(true);
1036 }
1037 paint.setAlphaf(layer.alpha);
1038
1039 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1040 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
1041
1042 // SysUI creates the alpha layer as a coverage layer, which is
1043 // appropriate for the DPU. Use a color matrix to convert it to
1044 // a mask.
1045 // TODO (b/219525258): Handle input as a mask.
1046 //
1047 // The color matrix will convert A8 pixels with no alpha to
1048 // black, as described by this vector. If the display handles
1049 // the color transform, we need to invert it to find the color
1050 // that will result in black after the DPU applies the transform.
1051 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1052 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1053 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1054 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1055 black = colorSpaceMatrix * black;
1056 } else {
1057 // We'll just have to use 0,0,0 as black, which should
1058 // be close to correct.
1059 ALOGI("Could not invert colorTransform!");
1060 }
1061 }
1062 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1063 0, 0, 0, 0, black[1],
1064 0, 0, 0, 0, black[2],
1065 0, 0, 0, -1, 1);
1066 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1067 // On the other hand, if the device doesn't handle it, we
1068 // have to apply it ourselves.
1069 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1070 }
1071 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
1072 }
1073 } else {
1074 ATRACE_NAME("DrawColor");
1075 const auto color = layer.source.solidColor;
1076 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1077 .fG = color.g,
1078 .fB = color.b,
1079 .fA = layer.alpha},
1080 toSkColorSpace(layerDataspace));
1081 paint.setShader(createRuntimeEffectShader(
1082 RuntimeEffectShaderParameters{.shader = shader,
1083 .layer = layer,
1084 .display = display,
1085 .undoPremultipliedAlpha = false,
1086 .requiresLinearEffect = requiresLinearEffect,
Sally Qi628ef6e2023-03-30 14:49:03 -07001087 .layerDimmingRatio = layerDimmingRatio,
Alec Mourie0bb6f42023-08-02 22:41:52 +00001088 .outputDataSpace = display.outputDataspace,
1089 .fakeOutputDataspace = fakeDataspace}));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001090 }
1091
1092 if (layer.disableBlending) {
1093 paint.setBlendMode(SkBlendMode::kSrc);
1094 }
1095
1096 // An A8 buffer will already have the proper color filter attached to
1097 // its paint, including the displayColorTransform as needed.
1098 if (!paint.getColorFilter()) {
1099 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1100 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1101 // can assume a gamma 2.2 transfer function.
1102 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1103 const auto gammaCorrectedDimmingRatio =
1104 std::pow(layerDimmingRatio, kInverseGamma22);
1105 auto dimmingMatrix =
1106 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1107 gammaCorrectedDimmingRatio, 1.f));
1108
1109 const auto colorFilter =
1110 SkColorFilters::Matrix(toSkColorMatrix(std::move(dimmingMatrix)));
1111 paint.setColorFilter(displayColorTransform
1112 ? displayColorTransform->makeComposed(colorFilter)
1113 : colorFilter);
1114 } else {
1115 paint.setColorFilter(displayColorTransform);
1116 }
1117 }
1118
1119 if (!roundRectClip.isEmpty()) {
1120 canvas->clipRRect(roundRectClip, true);
1121 }
1122
1123 if (!bounds.isRect()) {
1124 paint.setAntiAlias(true);
1125 canvas->drawRRect(bounds, paint);
1126 } else {
1127 canvas->drawRect(bounds.rect(), paint);
1128 }
1129 if (kFlushAfterEveryLayer) {
1130 ATRACE_NAME("flush surface");
Kevin Lubick208e11a2023-05-31 19:34:46 +00001131 skgpu::ganesh::Flush(activeSurface);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001132 }
1133 }
1134 for (const auto& borderRenderInfo : display.borderInfoList) {
1135 SkPaint p;
1136 p.setColor(SkColor4f{borderRenderInfo.color.r, borderRenderInfo.color.g,
1137 borderRenderInfo.color.b, borderRenderInfo.color.a});
1138 p.setAntiAlias(true);
1139 p.setStyle(SkPaint::kStroke_Style);
1140 p.setStrokeWidth(borderRenderInfo.width);
1141 SkRegion sk_region;
1142 SkPath path;
1143
1144 // Construct a final SkRegion using Regions
1145 for (const auto& r : borderRenderInfo.combinedRegion) {
1146 sk_region.op({r.left, r.top, r.right, r.bottom}, SkRegion::kUnion_Op);
1147 }
1148
1149 sk_region.getBoundaryPath(&path);
1150 canvas->drawPath(path, p);
1151 path.close();
1152 }
1153
1154 surfaceAutoSaveRestore.restore();
1155 mCapture->endCapture();
1156 {
1157 ATRACE_NAME("flush surface");
1158 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
Kevin Lubick208e11a2023-05-31 19:34:46 +00001159 skgpu::ganesh::Flush(activeSurface);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001160 }
1161
Alec Mouri0e7d8fd2023-05-03 23:58:43 +00001162 auto drawFence = sp<Fence>::make(flushAndSubmit(grContext));
1163
1164 if (ATRACE_ENABLED()) {
1165 static gui::FenceMonitor sMonitor("RE Completion");
1166 sMonitor.queueFence(drawFence);
1167 }
1168 resultPromise->set_value(std::move(drawFence));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001169}
1170
1171size_t SkiaRenderEngine::getMaxTextureSize() const {
1172 return mGrContext->maxTextureSize();
1173}
1174
1175size_t SkiaRenderEngine::getMaxViewportDims() const {
1176 return mGrContext->maxRenderTargetSize();
1177}
1178
1179void SkiaRenderEngine::drawShadow(SkCanvas* canvas,
1180 const SkRRect& casterRRect,
1181 const ShadowSettings& settings) {
1182 ATRACE_CALL();
1183 const float casterZ = settings.length / 2.0f;
1184 const auto flags =
1185 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1186
1187 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
1188 getSkPoint3(settings.lightPos), settings.lightRadius,
1189 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1190 flags);
1191}
1192
1193void SkiaRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
1194 // This cache multiplier was selected based on review of cache sizes relative
1195 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1196 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1197 // conservative default based on that analysis.
1198 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1199 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1200
1201 // start by resizing the current context
1202 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
1203
1204 // if it is possible to switch contexts then we will resize the other context
1205 const bool originalProtectedState = mInProtectedContext;
1206 useProtectedContext(!mInProtectedContext);
1207 if (mInProtectedContext != originalProtectedState) {
1208 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
1209 // reset back to the initial context that was active when this method was called
1210 useProtectedContext(originalProtectedState);
1211 }
1212}
1213
1214void SkiaRenderEngine::dump(std::string& result) {
1215 // Dump for the specific backend (GLES or Vk)
1216 appendBackendSpecificInfoToDump(result);
1217
1218 // Info about protected content
1219 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1220 supportsProtectedContent());
1221 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1222 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1223 mSkSLCacheMonitor.shadersCachedSinceLastCall());
1224
1225 std::vector<ResourcePair> cpuResourceMap = {
1226 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1227 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1228 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1229 {"skia/sk_resource_cache/tessellated", "Shadows"},
1230 {"skia", "Other"},
1231 };
1232 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1233 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1234 StringAppendF(&result, "Skia CPU Caches: ");
1235 cpuReporter.logTotals(result);
1236 cpuReporter.logOutput(result);
1237
1238 {
1239 std::lock_guard<std::mutex> lock(mRenderingMutex);
1240
1241 std::vector<ResourcePair> gpuResourceMap = {
1242 {"texture_renderbuffer", "Texture/RenderBuffer"},
1243 {"texture", "Texture"},
1244 {"gr_text_blob_cache", "Text"},
1245 {"skia", "Other"},
1246 };
1247 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1248 mGrContext->dumpMemoryStatistics(&gpuReporter);
1249 StringAppendF(&result, "Skia's GPU Caches: ");
1250 gpuReporter.logTotals(result);
1251 gpuReporter.logOutput(result);
1252 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1253 gpuReporter.logOutput(result, true);
1254
1255 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1256 mGraphicBufferExternalRefs.size());
1257 StringAppendF(&result, "Dumping buffer ids...\n");
1258 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1259 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1260 }
1261 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1262 mTextureCache.size());
1263 StringAppendF(&result, "Dumping buffer ids...\n");
1264 // TODO(178539829): It would be nice to know which layer these are coming from and what
1265 // the texture sizes are.
1266 for (const auto& [id, unused] : mTextureCache) {
1267 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1268 }
1269 StringAppendF(&result, "\n");
1270
1271 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
1272 if (mProtectedGrContext) {
1273 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1274 }
1275 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1276 gpuProtectedReporter.logTotals(result);
1277 gpuProtectedReporter.logOutput(result);
1278 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1279 gpuProtectedReporter.logOutput(result, true);
1280
1281 StringAppendF(&result, "\n");
1282 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1283 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1284 StringAppendF(&result, "- inputDataspace: %s\n",
1285 dataspaceDetails(
1286 static_cast<android_dataspace>(linearEffect.inputDataspace))
1287 .c_str());
1288 StringAppendF(&result, "- outputDataspace: %s\n",
1289 dataspaceDetails(
1290 static_cast<android_dataspace>(linearEffect.outputDataspace))
1291 .c_str());
1292 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1293 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1294 }
1295 }
1296 StringAppendF(&result, "\n");
1297}
1298
rnleec6a73642021-06-04 14:16:42 -07001299} // namespace skia
John Reck67b1e2b2020-08-26 13:17:24 -07001300} // namespace renderengine
rnleec6a73642021-06-04 14:16:42 -07001301} // namespace android