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