blob: e393fb2e924b8317429277fac1cea01b5c716d98 [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>
42#include <SkRect.h>
43#include <SkRefCnt.h>
44#include <SkRegion.h>
45#include <SkRRect.h>
46#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>
rnleec6a73642021-06-04 14:16:42 -070054#include <src/core/SkTraceEventCommon.h>
Lingfeng Yang00c1ff62022-06-02 09:19:28 -070055#include <android-base/stringprintf.h>
56#include <gui/TraceUtils.h>
57#include <sync/sync.h>
58#include <ui/BlurRegion.h>
59#include <ui/DataspaceUtils.h>
60#include <ui/DebugUtils.h>
61#include <ui/GraphicBuffer.h>
62#include <utils/Trace.h>
63
64#include <cmath>
65#include <cstdint>
66#include <memory>
67#include <numeric>
68
69#include "Cache.h"
70#include "ColorSpaces.h"
71#include "filters/BlurFilter.h"
72#include "filters/GaussianBlurFilter.h"
73#include "filters/KawaseBlurFilter.h"
74#include "filters/LinearEffect.h"
75#include "log/log_main.h"
76#include "skia/debug/SkiaCapture.h"
77#include "skia/debug/SkiaMemoryReporter.h"
78#include "skia/filters/StretchShaderFactory.h"
79#include "system/graphics-base-v1.0.h"
80
81namespace {
82
83// Debugging settings
84static const bool kPrintLayerSettings = false;
85static const bool kFlushAfterEveryLayer = kPrintLayerSettings;
86
87} // namespace
88
89// Utility functions related to SkRect
90
91namespace {
92
93static inline SkRect getSkRect(const android::FloatRect& rect) {
94 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
95}
96
97static inline SkRect getSkRect(const android::Rect& rect) {
98 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
99}
100
101/**
102 * Verifies that common, simple bounds + clip combinations can be converted into
103 * a single RRect draw call returning true if possible. If true the radii parameter
104 * will be filled with the correct radii values that combined with bounds param will
105 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
106 */
107static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
108 const SkRect& insetCrop, const android::vec2& cornerRadius,
109 SkVector radii[4]) {
110 const bool leftEqual = bounds.fLeft == crop.fLeft;
111 const bool topEqual = bounds.fTop == crop.fTop;
112 const bool rightEqual = bounds.fRight == crop.fRight;
113 const bool bottomEqual = bounds.fBottom == crop.fBottom;
114
115 // In the event that the corners of the bounds only partially align with the crop we
116 // need to ensure that the resulting shape can still be represented as a round rect.
117 // In particular the round rect implementation will scale the value of all corner radii
118 // if the sum of the radius along any edge is greater than the length of that edge.
119 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
120 const bool requiredWidth = bounds.width() > (cornerRadius.x * 2);
121 const bool requiredHeight = bounds.height() > (cornerRadius.y * 2);
122 if (!requiredWidth || !requiredHeight) {
123 return false;
124 }
125
126 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
127 // contained within the cropped shape and does not need rounded.
128 // compute the UpperLeft corner radius
129 if (leftEqual && topEqual) {
130 radii[0].set(cornerRadius.x, cornerRadius.y);
131 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
132 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
133 radii[0].set(0, 0);
134 } else {
135 return false;
136 }
137 // compute the UpperRight corner radius
138 if (rightEqual && topEqual) {
139 radii[1].set(cornerRadius.x, cornerRadius.y);
140 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
141 (topEqual && bounds.fRight <= insetCrop.fRight)) {
142 radii[1].set(0, 0);
143 } else {
144 return false;
145 }
146 // compute the BottomRight corner radius
147 if (rightEqual && bottomEqual) {
148 radii[2].set(cornerRadius.x, cornerRadius.y);
149 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
150 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
151 radii[2].set(0, 0);
152 } else {
153 return false;
154 }
155 // compute the BottomLeft corner radius
156 if (leftEqual && bottomEqual) {
157 radii[3].set(cornerRadius.x, cornerRadius.y);
158 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
159 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
160 radii[3].set(0, 0);
161 } else {
162 return false;
163 }
164
165 return true;
166}
167
168static inline std::pair<SkRRect, SkRRect> getBoundsAndClip(const android::FloatRect& boundsRect,
169 const android::FloatRect& cropRect,
170 const android::vec2& cornerRadius) {
171 const SkRect bounds = getSkRect(boundsRect);
172 const SkRect crop = getSkRect(cropRect);
173
174 SkRRect clip;
175 if (cornerRadius.x > 0 && cornerRadius.y > 0) {
176 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
177 if (bounds == crop || crop.isEmpty()) {
178 return {SkRRect::MakeRectXY(bounds, cornerRadius.x, cornerRadius.y), clip};
179 }
180
181 // This makes an effort to speed up common, simple bounds + clip combinations by
182 // converting them to a single RRect draw. It is possible there are other cases
183 // that can be converted.
184 if (crop.contains(bounds)) {
185 const auto insetCrop = crop.makeInset(cornerRadius.x, cornerRadius.y);
186 if (insetCrop.contains(bounds)) {
187 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
188 }
189
190 SkVector radii[4];
191 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
192 SkRRect intersectionBounds;
193 intersectionBounds.setRectRadii(bounds, radii);
194 return {intersectionBounds, clip};
195 }
196 }
197
198 // we didn't hit any of our fast paths so set the clip to the cropRect
199 clip.setRectXY(crop, cornerRadius.x, cornerRadius.y);
200 }
201
202 // if we hit this point then we either don't have rounded corners or we are going to rely
203 // on the clip to round the corners for us
204 return {SkRRect::MakeRect(bounds), clip};
205}
206
207static inline bool layerHasBlur(const android::renderengine::LayerSettings& layer,
208 bool colorTransformModifiesAlpha) {
209 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
210 // return false if the content is opaque and would therefore occlude the blur
211 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
212 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
213 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
214 }
215 return false;
216}
217
218static inline SkColor getSkColor(const android::vec4& color) {
219 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
220}
221
222static inline SkM44 getSkM44(const android::mat4& matrix) {
223 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
224 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
225 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
226 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
227}
228
229static inline SkPoint3 getSkPoint3(const android::vec3& vector) {
230 return SkPoint3::Make(vector.x, vector.y, vector.z);
231}
232
233} // namespace
rnleec6a73642021-06-04 14:16:42 -0700234
John Reck67b1e2b2020-08-26 13:17:24 -0700235namespace android {
236namespace renderengine {
rnleec6a73642021-06-04 14:16:42 -0700237namespace skia {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700238
239using base::StringAppendF;
240
241std::future<void> SkiaRenderEngine::primeCache() {
242 Cache::primeShaderCache(this);
243 return {};
244}
245
246sk_sp<SkData> SkiaRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
247 // This "cache" does not actually cache anything. It just allows us to
248 // monitor Skia's internal cache. So this method always returns null.
249 return nullptr;
250}
251
252void SkiaRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
253 const SkString& description) {
254 mShadersCachedSinceLastCall++;
255 mTotalShadersCompiled++;
256 ATRACE_FORMAT("SF cache: %i shaders", mTotalShadersCompiled);
257}
258
259int SkiaRenderEngine::reportShadersCompiled() {
260 return mSkSLCacheMonitor.totalShadersCompiled();
261}
Leon Scroggins IIIa37ca992022-02-02 18:08:20 -0500262
263void SkiaRenderEngine::setEnableTracing(bool tracingEnabled) {
264 SkAndroidFrameworkTraceUtil::setEnableTracing(tracingEnabled);
rnleec6a73642021-06-04 14:16:42 -0700265}
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700266
267SkiaRenderEngine::SkiaRenderEngine(
268 RenderEngineType type,
269 PixelFormat pixelFormat,
270 bool useColorManagement,
271 bool supportsBackgroundBlur) :
272 RenderEngine(type),
273 mDefaultPixelFormat(pixelFormat),
274 mUseColorManagement(useColorManagement) {
275 if (supportsBackgroundBlur) {
276 ALOGD("Background Blurs Enabled");
277 mBlurFilter = new KawaseBlurFilter();
278 }
279 mCapture = std::make_unique<SkiaCapture>();
280}
281
282SkiaRenderEngine::~SkiaRenderEngine() { }
283
284// To be called from backend dtors.
285void SkiaRenderEngine::finishRenderingAndAbandonContext() {
286 std::lock_guard<std::mutex> lock(mRenderingMutex);
287
288 if (mBlurFilter) {
289 delete mBlurFilter;
290 }
291
292 if (mGrContext) {
293 mGrContext->flushAndSubmit(true);
294 mGrContext->abandonContext();
295 }
296
297 if (mProtectedGrContext) {
298 mProtectedGrContext->flushAndSubmit(true);
299 mProtectedGrContext->abandonContext();
300 }
301}
302
303void SkiaRenderEngine::useProtectedContext(bool useProtectedContext) {
304 if (useProtectedContext == mInProtectedContext ||
305 (useProtectedContext && !supportsProtectedContent())) {
306 return;
307 }
308
309 // release any scratch resources before switching into a new mode
310 if (getActiveGrContext()) {
311 getActiveGrContext()->purgeUnlockedResources(true);
312 }
313
314 // Backend-specific way to switch to protected context
315 if (useProtectedContextImpl(
316 useProtectedContext ? GrProtected::kYes : GrProtected::kNo)) {
317 mInProtectedContext = useProtectedContext;
318 // given that we are sharing the same thread between two GrContexts we need to
319 // make sure that the thread state is reset when switching between the two.
320 if (getActiveGrContext()) {
321 getActiveGrContext()->resetContext();
322 }
323 }
324}
325
326GrDirectContext* SkiaRenderEngine::getActiveGrContext() {
327 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
328}
329
330static float toDegrees(uint32_t transform) {
331 switch (transform) {
332 case ui::Transform::ROT_90:
333 return 90.0;
334 case ui::Transform::ROT_180:
335 return 180.0;
336 case ui::Transform::ROT_270:
337 return 270.0;
338 default:
339 return 0.0;
340 }
341}
342
343static SkColorMatrix toSkColorMatrix(const android::mat4& matrix) {
344 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
345 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
346 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
347 matrix[3][3], 0);
348}
349
350static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
351 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
352 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
353
354 // Treat unsupported dataspaces as srgb
355 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
356 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
357 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
358 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
359 }
360
361 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
362 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
363 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
364 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
365 }
366
367 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
368 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
369 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
370 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
371
372 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
373 sourceTransfer != destTransfer;
374}
375
376void SkiaRenderEngine::ensureGrContextsCreated() {
377 if (mGrContext) {
378 return;
379 }
380
381 GrContextOptions options;
382 options.fDisableDriverCorrectnessWorkarounds = true;
383 options.fDisableDistanceFieldPaths = true;
384 options.fReducedShaderVariations = true;
385 options.fPersistentCache = &mSkSLCacheMonitor;
386 std::tie(mGrContext, mProtectedGrContext) = createDirectContexts(options);
387}
388
389void SkiaRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
390 bool isRenderable) {
Ian Elliott1f0911e2022-09-09 16:31:47 -0600391 // Only run this if RE is running on its own thread. This
392 // way the access to GL operations is guaranteed to be happening on the
393 // same thread.
394 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED &&
395 mRenderEngineType != RenderEngineType::SKIA_VK_THREADED) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700396 return;
397 }
Ian Elliott8506e362023-03-08 12:12:09 -0700398 // We don't attempt to map a buffer if the buffer contains protected content. In GL this is
399 // important because GPU resources for protected buffers are much more limited. (In Vk we
400 // simply match the existing behavior for protected buffers.) In Vk, we never cache any
401 // buffers while in a protected context, since Vk cannot share across contexts, and protected
402 // is less common.
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700403 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Ian Elliott8506e362023-03-08 12:12:09 -0700404 if (isProtectedBuffer ||
405 (mRenderEngineType == RenderEngineType::SKIA_VK_THREADED && isProtected())) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700406 return;
407 }
408 ATRACE_CALL();
409
410 // If we were to support caching protected buffers then we will need to switch the
411 // currently bound context if we are not already using the protected context (and subsequently
412 // switch back after the buffer is cached). However, for non-protected content we can bind
413 // the texture in either GL context because they are initialized with the same share_context
414 // which allows the texture state to be shared between them.
415 auto grContext = getActiveGrContext();
416 auto& cache = mTextureCache;
417
418 std::lock_guard<std::mutex> lock(mRenderingMutex);
419 mGraphicBufferExternalRefs[buffer->getId()]++;
420
421 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
422 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
423 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
424 buffer->toAHardwareBuffer(),
425 isRenderable, mTextureCleanupMgr);
426 cache.insert({buffer->getId(), imageTextureRef});
427 }
428}
429
Alec Mouri92f89fa2023-02-24 00:05:06 +0000430void SkiaRenderEngine::unmapExternalTextureBuffer(sp<GraphicBuffer>&& buffer) {
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700431 ATRACE_CALL();
432 std::lock_guard<std::mutex> lock(mRenderingMutex);
433 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
434 iter != mGraphicBufferExternalRefs.end()) {
435 if (iter->second == 0) {
436 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
437 "> from RenderEngine texture, but the "
438 "ref count was already zero!",
439 buffer->getId());
440 mGraphicBufferExternalRefs.erase(buffer->getId());
441 return;
442 }
443
444 iter->second--;
445
446 // Swap contexts if needed prior to deleting this buffer
447 // See Issue 1 of
448 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
449 // when a protected context and an unprotected context are part of the same share group,
450 // protected surfaces may not be accessed by an unprotected context, implying that protected
451 // surfaces may only be freed when a protected context is active.
452 const bool inProtected = mInProtectedContext;
453 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
454
455 if (iter->second == 0) {
456 mTextureCache.erase(buffer->getId());
457 mGraphicBufferExternalRefs.erase(buffer->getId());
458 }
459
460 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
461 // are up-to-date.
462 if (inProtected != mInProtectedContext) {
463 useProtectedContext(inProtected);
464 }
465 }
466}
467
Ian Elliott8506e362023-03-08 12:12:09 -0700468std::shared_ptr<AutoBackendTexture::LocalRef> SkiaRenderEngine::getOrCreateBackendTexture(
469 const sp<GraphicBuffer>& buffer, bool isOutputBuffer) {
470 // Do not lookup the buffer in the cache for protected contexts with the SkiaVk back-end
471 if (mRenderEngineType == RenderEngineType::SKIA_GL_THREADED ||
472 (mRenderEngineType == RenderEngineType::SKIA_VK_THREADED && !isProtected())) {
473 if (const auto& it = mTextureCache.find(buffer->getId()); it != mTextureCache.end()) {
474 return it->second;
475 }
476 }
477 return std::make_shared<AutoBackendTexture::LocalRef>(getActiveGrContext(),
478 buffer->toAHardwareBuffer(),
479 isOutputBuffer, mTextureCleanupMgr);
480}
481
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700482bool SkiaRenderEngine::canSkipPostRenderCleanup() const {
483 std::lock_guard<std::mutex> lock(mRenderingMutex);
484 return mTextureCleanupMgr.isEmpty();
485}
486
487void SkiaRenderEngine::cleanupPostRender() {
488 ATRACE_CALL();
489 std::lock_guard<std::mutex> lock(mRenderingMutex);
490 mTextureCleanupMgr.cleanup();
491}
492
493sk_sp<SkShader> SkiaRenderEngine::createRuntimeEffectShader(
494 const RuntimeEffectShaderParameters& parameters) {
495 // The given surface will be stretched by HWUI via matrix transformation
496 // which gets similar results for most surfaces
497 // Determine later on if we need to leverage the stertch shader within
498 // surface flinger
499 const auto& stretchEffect = parameters.layer.stretchEffect;
500 auto shader = parameters.shader;
501 if (stretchEffect.hasEffect()) {
502 const auto targetBuffer = parameters.layer.source.buffer.buffer;
503 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
504 if (graphicBuffer && parameters.shader) {
505 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
506 }
507 }
508
509 if (parameters.requiresLinearEffect) {
510 const ui::Dataspace inputDataspace = mUseColorManagement ? parameters.layer.sourceDataspace
511 : ui::Dataspace::V0_SRGB_LINEAR;
512 const ui::Dataspace outputDataspace = mUseColorManagement
513 ? parameters.display.outputDataspace
514 : ui::Dataspace::V0_SRGB_LINEAR;
515
516 auto effect =
517 shaders::LinearEffect{.inputDataspace = inputDataspace,
518 .outputDataspace = outputDataspace,
519 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha};
520
521 auto effectIter = mRuntimeEffects.find(effect);
522 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
523 if (effectIter == mRuntimeEffects.end()) {
524 runtimeEffect = buildRuntimeEffect(effect);
525 mRuntimeEffects.insert({effect, runtimeEffect});
526 } else {
527 runtimeEffect = effectIter->second;
528 }
529 mat4 colorTransform = parameters.layer.colorTransform;
530
531 colorTransform *=
532 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
533 parameters.layerDimmingRatio, 1.f));
534 const auto targetBuffer = parameters.layer.source.buffer.buffer;
535 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
536 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
537 return createLinearEffectShader(parameters.shader, effect, runtimeEffect, colorTransform,
538 parameters.display.maxLuminance,
539 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,
657 const std::shared_ptr<ExternalTexture>& buffer, const bool /*useFramebufferCache*/,
658 base::unique_fd&& bufferFence) {
Leon Scroggins III5a655b82022-09-07 13:17:09 -0400659 ATRACE_FORMAT("%s for %s", __func__, display.namePlusId.c_str());
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700660
661 std::lock_guard<std::mutex> lock(mRenderingMutex);
662
663 if (buffer == nullptr) {
664 ALOGE("No output buffer provided. Aborting GPU composition.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000665 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700666 return;
667 }
668
669 validateOutputBufferUsage(buffer->getBuffer());
670
671 auto grContext = getActiveGrContext();
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700672
673 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
674 DeferTextureCleanup dtc(mTextureCleanupMgr);
675
Ian Elliott8506e362023-03-08 12:12:09 -0700676 auto surfaceTextureRef = getOrCreateBackendTexture(buffer->getBuffer(), true);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700677
678 // wait on the buffer to be ready to use prior to using it
679 waitFence(grContext, bufferFence);
680
681 const ui::Dataspace dstDataspace =
682 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
683 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
684
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 &&
708 maxLayerWhitePoint > 0.f && display.targetLuminanceNits > maxLayerWhitePoint
709 ? maxLayerWhitePoint / display.targetLuminanceNits
710 : 1.f;
711
712 // Find if any layers have requested blur, we'll use that info to decide when to render to an
713 // offscreen buffer and when to render to the native buffer.
714 sk_sp<SkSurface> activeSurface(dstSurface);
715 SkCanvas* canvas = dstCanvas;
716 SkiaCapture::OffscreenState offscreenCaptureState;
717 const LayerSettings* blurCompositionLayer = nullptr;
718 if (mBlurFilter) {
719 bool requiresCompositionLayer = false;
720 for (const auto& layer : layers) {
721 // if the layer doesn't have blur or it is not visible then continue
722 if (!layerHasBlur(layer, ctModifiesAlpha)) {
723 continue;
724 }
725 if (layer.backgroundBlurRadius > 0 &&
726 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
727 requiresCompositionLayer = true;
728 }
729 for (auto region : layer.blurRegions) {
730 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
731 requiresCompositionLayer = true;
732 }
733 }
734 if (requiresCompositionLayer) {
735 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
736 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
737 blurCompositionLayer = &layer;
738 break;
739 }
740 }
741 }
742
743 AutoSaveRestore surfaceAutoSaveRestore(canvas);
744 // Clear the entire canvas with a transparent black to prevent ghost images.
745 canvas->clear(SK_ColorTRANSPARENT);
746 initCanvas(canvas, display);
747
748 if (kPrintLayerSettings) {
749 logSettings(display);
750 }
751 for (const auto& layer : layers) {
752 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
753
754 if (kPrintLayerSettings) {
755 logSettings(layer);
756 }
757
758 sk_sp<SkImage> blurInput;
759 if (blurCompositionLayer == &layer) {
760 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
761 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
762
763 // save a snapshot of the activeSurface to use as input to the blur shaders
764 blurInput = activeSurface->makeImageSnapshot();
765
766 // blit the offscreen framebuffer into the destination AHB, but only
767 // if there are blur regions. backgroundBlurRadius blurs the entire
768 // image below, so it can skip this step.
769 if (layer.blurRegions.size()) {
770 SkPaint paint;
771 paint.setBlendMode(SkBlendMode::kSrc);
772 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
773 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
774 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
775 String8::format("SurfaceID|%" PRId64, id).c_str(),
776 nullptr);
777 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
778 } else {
779 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
780 }
781 }
782
783 // assign dstCanvas to canvas and ensure that the canvas state is up to date
784 canvas = dstCanvas;
785 surfaceAutoSaveRestore.replace(canvas);
786 initCanvas(canvas, display);
787
788 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
789 dstSurface->getCanvas()->getSaveCount());
790 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
791 dstSurface->getCanvas()->getTotalMatrix());
792
793 // assign dstSurface to activeSurface
794 activeSurface = dstSurface;
795 }
796
797 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
798 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
799 // Record the name of the layer if the capture is running.
800 std::stringstream layerSettings;
801 PrintTo(layer, &layerSettings);
802 // Store the LayerSettings in additional information.
803 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
804 SkData::MakeWithCString(layerSettings.str().c_str()));
805 }
806 // Layers have a local transform that should be applied to them
807 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
808
809 const auto [bounds, roundRectClip] =
810 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
811 layer.geometry.roundedCornersRadius);
812 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
813 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
814
815 // if multiple layers have blur, then we need to take a snapshot now because
816 // only the lowest layer will have blurImage populated earlier
817 if (!blurInput) {
818 blurInput = activeSurface->makeImageSnapshot();
819 }
820 // rect to be blurred in the coordinate space of blurInput
821 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
822
823 // if the clip needs to be applied then apply it now and make sure
824 // it is restored before we attempt to draw any shadows.
825 SkAutoCanvasRestore acr(canvas, true);
826 if (!roundRectClip.isEmpty()) {
827 canvas->clipRRect(roundRectClip, true);
828 }
829
830 // TODO(b/182216890): Filter out empty layers earlier
831 if (blurRect.width() > 0 && blurRect.height() > 0) {
832 if (layer.backgroundBlurRadius > 0) {
833 ATRACE_NAME("BackgroundBlur");
834 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
835 blurInput, blurRect);
836
837 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
838
839 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
840 blurRect, blurredImage, blurInput);
841 }
842
843 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
844 for (auto region : layer.blurRegions) {
845 if (cachedBlurs[region.blurRadius] == nullptr) {
846 ATRACE_NAME("BlurRegion");
847 cachedBlurs[region.blurRadius] =
848 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
849 blurRect);
850 }
851
852 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
853 region.alpha, blurRect,
854 cachedBlurs[region.blurRadius], blurInput);
855 }
856 }
857 }
858
859 if (layer.shadow.length > 0) {
860 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
861 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
862
863 SkRRect shadowBounds, shadowClip;
864 if (layer.geometry.boundaries == layer.shadow.boundaries) {
865 shadowBounds = bounds;
866 shadowClip = roundRectClip;
867 } else {
868 std::tie(shadowBounds, shadowClip) =
869 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
870 layer.geometry.roundedCornersRadius);
871 }
872
873 // Technically, if bounds is a rect and roundRectClip is not empty,
874 // it means that the bounds and roundedCornersCrop were different
875 // enough that we should intersect them to find the proper shadow.
876 // In practice, this often happens when the two rectangles appear to
877 // not match due to rounding errors. Draw the rounded version, which
878 // looks more like the intent.
879 const auto& rrect =
880 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
881 drawShadow(canvas, rrect, layer.shadow);
882 }
883
884 const float layerDimmingRatio = layer.whitePointNits <= 0.f
885 ? displayDimmingRatio
886 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
887
888 const bool dimInLinearSpace = display.dimmingStage !=
889 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
890
891 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
892 (mUseColorManagement &&
893 needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
894 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio));
895
896 // quick abort from drawing the remaining portion of the layer
897 if (layer.skipContentDraw ||
898 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
899 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
900 continue;
901 }
902
903 // If we need to map to linear space or color management is disabled, then mark the source
904 // image with the same colorspace as the destination surface so that Skia's color
905 // management is a no-op.
906 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
907 ? dstDataspace
908 : layer.sourceDataspace;
909
910 SkPaint paint;
911 if (layer.source.buffer.buffer) {
912 ATRACE_NAME("DrawImage");
913 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
914 const auto& item = layer.source.buffer;
Ian Elliott8506e362023-03-08 12:12:09 -0700915 auto imageTextureRef = getOrCreateBackendTexture(item.buffer->getBuffer(), false);
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700916
917 // if the layer's buffer has a fence, then we must must respect the fence prior to using
918 // the buffer.
919 if (layer.source.buffer.fence != nullptr) {
920 waitFence(grContext, layer.source.buffer.fence->get());
921 }
922
923 // isOpaque means we need to ignore the alpha in the image,
924 // replacing it with the alpha specified by the LayerSettings. See
925 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
926 // The proper way to do this is to use an SkColorType that ignores
927 // alpha, like kRGB_888x_SkColorType, and that is used if the
928 // incoming image is kRGBA_8888_SkColorType. However, the incoming
929 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
930 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
931 // kRGB_101010x_SkColorType, but it is not yet supported as a source
932 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
933 // meantime, we'll use a workaround that works unless we need to do
934 // any color conversion. The workaround requires that we pretend the
935 // image is already premultiplied, so that we do not premultiply it
936 // before applying SkBlendMode::kPlus.
937 const bool useIsOpaqueWorkaround = item.isOpaque &&
938 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
939 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
940 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
941 : item.isOpaque ? kOpaque_SkAlphaType
942 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
943 : kUnpremul_SkAlphaType;
944 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
945
946 auto texMatrix = getSkM44(item.textureTransform).asM33();
947 // textureTansform was intended to be passed directly into a shader, so when
948 // building the total matrix with the textureTransform we need to first
949 // normalize it, then apply the textureTransform, then scale back up.
950 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
951 texMatrix.postScale(image->width(), image->height());
952
953 SkMatrix matrix;
954 if (!texMatrix.invert(&matrix)) {
955 matrix = texMatrix;
956 }
957 // The shader does not respect the translation, so we add it to the texture
958 // transform for the SkImage. This will make sure that the correct layer contents
959 // are drawn in the correct part of the screen.
960 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
961
962 sk_sp<SkShader> shader;
963
964 if (layer.source.buffer.useTextureFiltering) {
965 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
966 SkSamplingOptions(
967 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
968 &matrix);
969 } else {
970 shader = image->makeShader(SkSamplingOptions(), matrix);
971 }
972
973 if (useIsOpaqueWorkaround) {
974 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
975 SkShaders::Color(SkColors::kBlack,
976 toSkColorSpace(layerDataspace)));
977 }
978
979 paint.setShader(createRuntimeEffectShader(
980 RuntimeEffectShaderParameters{.shader = shader,
981 .layer = layer,
982 .display = display,
983 .undoPremultipliedAlpha = !item.isOpaque &&
984 item.usePremultipliedAlpha,
985 .requiresLinearEffect = requiresLinearEffect,
986 .layerDimmingRatio = dimInLinearSpace
987 ? layerDimmingRatio
988 : 1.f}));
989
990 // Turn on dithering when dimming beyond this (arbitrary) threshold...
991 static constexpr float kDimmingThreshold = 0.2f;
992 // ...or we're rendering an HDR layer down to an 8-bit target
993 // Most HDR standards require at least 10-bits of color depth for source content, so we
994 // can just extract the transfer function rather than dig into precise gralloc layout.
995 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
996 const bool requiresDownsample = isHdrDataspace(layer.sourceDataspace) &&
997 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
998 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
999 paint.setDither(true);
1000 }
1001 paint.setAlphaf(layer.alpha);
1002
1003 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1004 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
1005
1006 // SysUI creates the alpha layer as a coverage layer, which is
1007 // appropriate for the DPU. Use a color matrix to convert it to
1008 // a mask.
1009 // TODO (b/219525258): Handle input as a mask.
1010 //
1011 // The color matrix will convert A8 pixels with no alpha to
1012 // black, as described by this vector. If the display handles
1013 // the color transform, we need to invert it to find the color
1014 // that will result in black after the DPU applies the transform.
1015 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1016 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1017 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1018 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1019 black = colorSpaceMatrix * black;
1020 } else {
1021 // We'll just have to use 0,0,0 as black, which should
1022 // be close to correct.
1023 ALOGI("Could not invert colorTransform!");
1024 }
1025 }
1026 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1027 0, 0, 0, 0, black[1],
1028 0, 0, 0, 0, black[2],
1029 0, 0, 0, -1, 1);
1030 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1031 // On the other hand, if the device doesn't handle it, we
1032 // have to apply it ourselves.
1033 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1034 }
1035 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
1036 }
1037 } else {
1038 ATRACE_NAME("DrawColor");
1039 const auto color = layer.source.solidColor;
1040 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1041 .fG = color.g,
1042 .fB = color.b,
1043 .fA = layer.alpha},
1044 toSkColorSpace(layerDataspace));
1045 paint.setShader(createRuntimeEffectShader(
1046 RuntimeEffectShaderParameters{.shader = shader,
1047 .layer = layer,
1048 .display = display,
1049 .undoPremultipliedAlpha = false,
1050 .requiresLinearEffect = requiresLinearEffect,
1051 .layerDimmingRatio = layerDimmingRatio}));
1052 }
1053
1054 if (layer.disableBlending) {
1055 paint.setBlendMode(SkBlendMode::kSrc);
1056 }
1057
1058 // An A8 buffer will already have the proper color filter attached to
1059 // its paint, including the displayColorTransform as needed.
1060 if (!paint.getColorFilter()) {
1061 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1062 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1063 // can assume a gamma 2.2 transfer function.
1064 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1065 const auto gammaCorrectedDimmingRatio =
1066 std::pow(layerDimmingRatio, kInverseGamma22);
1067 auto dimmingMatrix =
1068 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1069 gammaCorrectedDimmingRatio, 1.f));
1070
1071 const auto colorFilter =
1072 SkColorFilters::Matrix(toSkColorMatrix(std::move(dimmingMatrix)));
1073 paint.setColorFilter(displayColorTransform
1074 ? displayColorTransform->makeComposed(colorFilter)
1075 : colorFilter);
1076 } else {
1077 paint.setColorFilter(displayColorTransform);
1078 }
1079 }
1080
1081 if (!roundRectClip.isEmpty()) {
1082 canvas->clipRRect(roundRectClip, true);
1083 }
1084
1085 if (!bounds.isRect()) {
1086 paint.setAntiAlias(true);
1087 canvas->drawRRect(bounds, paint);
1088 } else {
1089 canvas->drawRect(bounds.rect(), paint);
1090 }
1091 if (kFlushAfterEveryLayer) {
1092 ATRACE_NAME("flush surface");
1093 activeSurface->flush();
1094 }
1095 }
1096 for (const auto& borderRenderInfo : display.borderInfoList) {
1097 SkPaint p;
1098 p.setColor(SkColor4f{borderRenderInfo.color.r, borderRenderInfo.color.g,
1099 borderRenderInfo.color.b, borderRenderInfo.color.a});
1100 p.setAntiAlias(true);
1101 p.setStyle(SkPaint::kStroke_Style);
1102 p.setStrokeWidth(borderRenderInfo.width);
1103 SkRegion sk_region;
1104 SkPath path;
1105
1106 // Construct a final SkRegion using Regions
1107 for (const auto& r : borderRenderInfo.combinedRegion) {
1108 sk_region.op({r.left, r.top, r.right, r.bottom}, SkRegion::kUnion_Op);
1109 }
1110
1111 sk_region.getBoundaryPath(&path);
1112 canvas->drawPath(path, p);
1113 path.close();
1114 }
1115
1116 surfaceAutoSaveRestore.restore();
1117 mCapture->endCapture();
1118 {
1119 ATRACE_NAME("flush surface");
1120 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1121 activeSurface->flush();
1122 }
1123
1124 base::unique_fd drawFence = flushAndSubmit(grContext);
Patrick Williams2e9748f2022-08-09 22:48:18 +00001125 resultPromise->set_value(sp<Fence>::make(std::move(drawFence)));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001126}
1127
1128size_t SkiaRenderEngine::getMaxTextureSize() const {
1129 return mGrContext->maxTextureSize();
1130}
1131
1132size_t SkiaRenderEngine::getMaxViewportDims() const {
1133 return mGrContext->maxRenderTargetSize();
1134}
1135
1136void SkiaRenderEngine::drawShadow(SkCanvas* canvas,
1137 const SkRRect& casterRRect,
1138 const ShadowSettings& settings) {
1139 ATRACE_CALL();
1140 const float casterZ = settings.length / 2.0f;
1141 const auto flags =
1142 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1143
1144 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
1145 getSkPoint3(settings.lightPos), settings.lightRadius,
1146 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1147 flags);
1148}
1149
1150void SkiaRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
1151 // This cache multiplier was selected based on review of cache sizes relative
1152 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1153 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1154 // conservative default based on that analysis.
1155 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1156 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1157
1158 // start by resizing the current context
1159 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
1160
1161 // if it is possible to switch contexts then we will resize the other context
1162 const bool originalProtectedState = mInProtectedContext;
1163 useProtectedContext(!mInProtectedContext);
1164 if (mInProtectedContext != originalProtectedState) {
1165 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
1166 // reset back to the initial context that was active when this method was called
1167 useProtectedContext(originalProtectedState);
1168 }
1169}
1170
1171void SkiaRenderEngine::dump(std::string& result) {
1172 // Dump for the specific backend (GLES or Vk)
1173 appendBackendSpecificInfoToDump(result);
1174
1175 // Info about protected content
1176 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1177 supportsProtectedContent());
1178 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1179 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1180 mSkSLCacheMonitor.shadersCachedSinceLastCall());
1181
1182 std::vector<ResourcePair> cpuResourceMap = {
1183 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1184 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1185 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1186 {"skia/sk_resource_cache/tessellated", "Shadows"},
1187 {"skia", "Other"},
1188 };
1189 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1190 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1191 StringAppendF(&result, "Skia CPU Caches: ");
1192 cpuReporter.logTotals(result);
1193 cpuReporter.logOutput(result);
1194
1195 {
1196 std::lock_guard<std::mutex> lock(mRenderingMutex);
1197
1198 std::vector<ResourcePair> gpuResourceMap = {
1199 {"texture_renderbuffer", "Texture/RenderBuffer"},
1200 {"texture", "Texture"},
1201 {"gr_text_blob_cache", "Text"},
1202 {"skia", "Other"},
1203 };
1204 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1205 mGrContext->dumpMemoryStatistics(&gpuReporter);
1206 StringAppendF(&result, "Skia's GPU Caches: ");
1207 gpuReporter.logTotals(result);
1208 gpuReporter.logOutput(result);
1209 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1210 gpuReporter.logOutput(result, true);
1211
1212 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1213 mGraphicBufferExternalRefs.size());
1214 StringAppendF(&result, "Dumping buffer ids...\n");
1215 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1216 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1217 }
1218 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1219 mTextureCache.size());
1220 StringAppendF(&result, "Dumping buffer ids...\n");
1221 // TODO(178539829): It would be nice to know which layer these are coming from and what
1222 // the texture sizes are.
1223 for (const auto& [id, unused] : mTextureCache) {
1224 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1225 }
1226 StringAppendF(&result, "\n");
1227
1228 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
1229 if (mProtectedGrContext) {
1230 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1231 }
1232 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1233 gpuProtectedReporter.logTotals(result);
1234 gpuProtectedReporter.logOutput(result);
1235 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1236 gpuProtectedReporter.logOutput(result, true);
1237
1238 StringAppendF(&result, "\n");
1239 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1240 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1241 StringAppendF(&result, "- inputDataspace: %s\n",
1242 dataspaceDetails(
1243 static_cast<android_dataspace>(linearEffect.inputDataspace))
1244 .c_str());
1245 StringAppendF(&result, "- outputDataspace: %s\n",
1246 dataspaceDetails(
1247 static_cast<android_dataspace>(linearEffect.outputDataspace))
1248 .c_str());
1249 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1250 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1251 }
1252 }
1253 StringAppendF(&result, "\n");
1254}
1255
rnleec6a73642021-06-04 14:16:42 -07001256} // namespace skia
John Reck67b1e2b2020-08-26 13:17:24 -07001257} // namespace renderengine
rnleec6a73642021-06-04 14:16:42 -07001258} // namespace android