blob: c3f66497f059629cea4b81b50c15b0beb339a524 [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 }
398 // We currently don't attempt to map a buffer if the buffer contains protected content
399 // because GPU resources for protected buffers is much more limited.
400 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
401 if (isProtectedBuffer) {
402 return;
403 }
404 ATRACE_CALL();
405
406 // If we were to support caching protected buffers then we will need to switch the
407 // currently bound context if we are not already using the protected context (and subsequently
408 // switch back after the buffer is cached). However, for non-protected content we can bind
409 // the texture in either GL context because they are initialized with the same share_context
410 // which allows the texture state to be shared between them.
411 auto grContext = getActiveGrContext();
412 auto& cache = mTextureCache;
413
414 std::lock_guard<std::mutex> lock(mRenderingMutex);
415 mGraphicBufferExternalRefs[buffer->getId()]++;
416
417 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
418 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
419 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
420 buffer->toAHardwareBuffer(),
421 isRenderable, mTextureCleanupMgr);
422 cache.insert({buffer->getId(), imageTextureRef});
423 }
424}
425
426void SkiaRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
427 ATRACE_CALL();
428 std::lock_guard<std::mutex> lock(mRenderingMutex);
429 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
430 iter != mGraphicBufferExternalRefs.end()) {
431 if (iter->second == 0) {
432 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
433 "> from RenderEngine texture, but the "
434 "ref count was already zero!",
435 buffer->getId());
436 mGraphicBufferExternalRefs.erase(buffer->getId());
437 return;
438 }
439
440 iter->second--;
441
442 // Swap contexts if needed prior to deleting this buffer
443 // See Issue 1 of
444 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
445 // when a protected context and an unprotected context are part of the same share group,
446 // protected surfaces may not be accessed by an unprotected context, implying that protected
447 // surfaces may only be freed when a protected context is active.
448 const bool inProtected = mInProtectedContext;
449 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
450
451 if (iter->second == 0) {
452 mTextureCache.erase(buffer->getId());
453 mGraphicBufferExternalRefs.erase(buffer->getId());
454 }
455
456 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
457 // are up-to-date.
458 if (inProtected != mInProtectedContext) {
459 useProtectedContext(inProtected);
460 }
461 }
462}
463
464bool SkiaRenderEngine::canSkipPostRenderCleanup() const {
465 std::lock_guard<std::mutex> lock(mRenderingMutex);
466 return mTextureCleanupMgr.isEmpty();
467}
468
469void SkiaRenderEngine::cleanupPostRender() {
470 ATRACE_CALL();
471 std::lock_guard<std::mutex> lock(mRenderingMutex);
472 mTextureCleanupMgr.cleanup();
473}
474
475sk_sp<SkShader> SkiaRenderEngine::createRuntimeEffectShader(
476 const RuntimeEffectShaderParameters& parameters) {
477 // The given surface will be stretched by HWUI via matrix transformation
478 // which gets similar results for most surfaces
479 // Determine later on if we need to leverage the stertch shader within
480 // surface flinger
481 const auto& stretchEffect = parameters.layer.stretchEffect;
482 auto shader = parameters.shader;
483 if (stretchEffect.hasEffect()) {
484 const auto targetBuffer = parameters.layer.source.buffer.buffer;
485 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
486 if (graphicBuffer && parameters.shader) {
487 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
488 }
489 }
490
491 if (parameters.requiresLinearEffect) {
492 const ui::Dataspace inputDataspace = mUseColorManagement ? parameters.layer.sourceDataspace
493 : ui::Dataspace::V0_SRGB_LINEAR;
494 const ui::Dataspace outputDataspace = mUseColorManagement
495 ? parameters.display.outputDataspace
496 : ui::Dataspace::V0_SRGB_LINEAR;
497
498 auto effect =
499 shaders::LinearEffect{.inputDataspace = inputDataspace,
500 .outputDataspace = outputDataspace,
501 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha};
502
503 auto effectIter = mRuntimeEffects.find(effect);
504 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
505 if (effectIter == mRuntimeEffects.end()) {
506 runtimeEffect = buildRuntimeEffect(effect);
507 mRuntimeEffects.insert({effect, runtimeEffect});
508 } else {
509 runtimeEffect = effectIter->second;
510 }
511 mat4 colorTransform = parameters.layer.colorTransform;
512
513 colorTransform *=
514 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
515 parameters.layerDimmingRatio, 1.f));
516 const auto targetBuffer = parameters.layer.source.buffer.buffer;
517 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
518 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
519 return createLinearEffectShader(parameters.shader, effect, runtimeEffect, colorTransform,
520 parameters.display.maxLuminance,
521 parameters.display.currentLuminanceNits,
522 parameters.layer.source.buffer.maxLuminanceNits,
523 hardwareBuffer, parameters.display.renderIntent);
524 }
525 return parameters.shader;
526}
527
528void SkiaRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
529 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
530 // Record display settings when capture is running.
531 std::stringstream displaySettings;
532 PrintTo(display, &displaySettings);
533 // Store the DisplaySettings in additional information.
534 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
535 SkData::MakeWithCString(displaySettings.str().c_str()));
536 }
537
538 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
539 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
540 // displays might have different scaling when compared to the physical screen.
541
542 canvas->clipRect(getSkRect(display.physicalDisplay));
543 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
544
545 const auto clipWidth = display.clip.width();
546 const auto clipHeight = display.clip.height();
547 auto rotatedClipWidth = clipWidth;
548 auto rotatedClipHeight = clipHeight;
549 // Scale is contingent on the rotation result.
550 if (display.orientation & ui::Transform::ROT_90) {
551 std::swap(rotatedClipWidth, rotatedClipHeight);
552 }
553 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
554 static_cast<SkScalar>(rotatedClipWidth);
555 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
556 static_cast<SkScalar>(rotatedClipHeight);
557 canvas->scale(scaleX, scaleY);
558
559 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
560 // back so that the top left corner of the clip is at (0, 0).
561 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
562 canvas->rotate(toDegrees(display.orientation));
563 canvas->translate(-clipWidth / 2, -clipHeight / 2);
564 canvas->translate(-display.clip.left, -display.clip.top);
565}
566
567class AutoSaveRestore {
568public:
569 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
570 ~AutoSaveRestore() { restore(); }
571 void replace(SkCanvas* canvas) {
572 mCanvas = canvas;
573 mSaveCount = canvas->save();
574 }
575 void restore() {
576 if (mCanvas) {
577 mCanvas->restoreToCount(mSaveCount);
578 mCanvas = nullptr;
579 }
580 }
581
582private:
583 SkCanvas* mCanvas;
584 int mSaveCount;
585};
586
587static SkRRect getBlurRRect(const BlurRegion& region) {
588 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
589 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
590 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
591 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
592 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
593 SkRRect roundedRect;
594 roundedRect.setRectRadii(rect, radii);
595 return roundedRect;
596}
597
598// Arbitrary default margin which should be close enough to zero.
599constexpr float kDefaultMargin = 0.0001f;
600static bool equalsWithinMargin(float expected, float value, float margin = kDefaultMargin) {
601 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
602 return std::abs(expected - value) < margin;
603}
604
605namespace {
606template <typename T>
607void logSettings(const T& t) {
608 std::stringstream stream;
609 PrintTo(t, &stream);
610 auto string = stream.str();
611 size_t pos = 0;
612 // Perfetto ignores \n, so split up manually into separate ALOGD statements.
613 const size_t size = string.size();
614 while (pos < size) {
615 const size_t end = std::min(string.find("\n", pos), size);
616 ALOGD("%s", string.substr(pos, end - pos).c_str());
617 pos = end + 1;
618 }
619}
620} // namespace
621
622// Helper class intended to be used on the stack to ensure that texture cleanup
623// is deferred until after this class goes out of scope.
624class DeferTextureCleanup final {
625public:
626 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
627 mMgr.setDeferredStatus(true);
628 }
629 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
630
631private:
632 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
633 AutoBackendTexture::CleanupManager& mMgr;
634};
635
636void SkiaRenderEngine::drawLayersInternal(
Patrick Williams2e9748f2022-08-09 22:48:18 +0000637 const std::shared_ptr<std::promise<FenceResult>>&& resultPromise,
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700638 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
639 const std::shared_ptr<ExternalTexture>& buffer, const bool /*useFramebufferCache*/,
640 base::unique_fd&& bufferFence) {
641 ATRACE_NAME("SkiaGL::drawLayersInternal");
642
643 std::lock_guard<std::mutex> lock(mRenderingMutex);
644
645 if (buffer == nullptr) {
646 ALOGE("No output buffer provided. Aborting GPU composition.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000647 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700648 return;
649 }
650
651 validateOutputBufferUsage(buffer->getBuffer());
652
653 auto grContext = getActiveGrContext();
654 auto& cache = mTextureCache;
655
656 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
657 DeferTextureCleanup dtc(mTextureCleanupMgr);
658
659 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
660 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
661 surfaceTextureRef = it->second;
662 } else {
663 surfaceTextureRef =
664 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
665 buffer->getBuffer()
666 ->toAHardwareBuffer(),
667 true, mTextureCleanupMgr);
668 }
669
670 // wait on the buffer to be ready to use prior to using it
671 waitFence(grContext, bufferFence);
672
673 const ui::Dataspace dstDataspace =
674 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
675 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
676
677 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
678 if (dstCanvas == nullptr) {
679 ALOGE("Cannot acquire canvas from Skia.");
Patrick Williams2e9748f2022-08-09 22:48:18 +0000680 resultPromise->set_value(base::unexpected(BAD_VALUE));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -0700681 return;
682 }
683
684 // setup color filter if necessary
685 sk_sp<SkColorFilter> displayColorTransform;
686 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
687 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
688 }
689 const bool ctModifiesAlpha =
690 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
691
692 // Find the max layer white point to determine the max luminance of the scene...
693 const float maxLayerWhitePoint = std::transform_reduce(
694 layers.cbegin(), layers.cend(), 0.f,
695 [](float left, float right) { return std::max(left, right); },
696 [&](const auto& l) { return l.whitePointNits; });
697
698 // ...and compute the dimming ratio if dimming is requested
699 const float displayDimmingRatio = display.targetLuminanceNits > 0.f &&
700 maxLayerWhitePoint > 0.f && display.targetLuminanceNits > maxLayerWhitePoint
701 ? maxLayerWhitePoint / display.targetLuminanceNits
702 : 1.f;
703
704 // Find if any layers have requested blur, we'll use that info to decide when to render to an
705 // offscreen buffer and when to render to the native buffer.
706 sk_sp<SkSurface> activeSurface(dstSurface);
707 SkCanvas* canvas = dstCanvas;
708 SkiaCapture::OffscreenState offscreenCaptureState;
709 const LayerSettings* blurCompositionLayer = nullptr;
710 if (mBlurFilter) {
711 bool requiresCompositionLayer = false;
712 for (const auto& layer : layers) {
713 // if the layer doesn't have blur or it is not visible then continue
714 if (!layerHasBlur(layer, ctModifiesAlpha)) {
715 continue;
716 }
717 if (layer.backgroundBlurRadius > 0 &&
718 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
719 requiresCompositionLayer = true;
720 }
721 for (auto region : layer.blurRegions) {
722 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
723 requiresCompositionLayer = true;
724 }
725 }
726 if (requiresCompositionLayer) {
727 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
728 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
729 blurCompositionLayer = &layer;
730 break;
731 }
732 }
733 }
734
735 AutoSaveRestore surfaceAutoSaveRestore(canvas);
736 // Clear the entire canvas with a transparent black to prevent ghost images.
737 canvas->clear(SK_ColorTRANSPARENT);
738 initCanvas(canvas, display);
739
740 if (kPrintLayerSettings) {
741 logSettings(display);
742 }
743 for (const auto& layer : layers) {
744 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
745
746 if (kPrintLayerSettings) {
747 logSettings(layer);
748 }
749
750 sk_sp<SkImage> blurInput;
751 if (blurCompositionLayer == &layer) {
752 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
753 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
754
755 // save a snapshot of the activeSurface to use as input to the blur shaders
756 blurInput = activeSurface->makeImageSnapshot();
757
758 // blit the offscreen framebuffer into the destination AHB, but only
759 // if there are blur regions. backgroundBlurRadius blurs the entire
760 // image below, so it can skip this step.
761 if (layer.blurRegions.size()) {
762 SkPaint paint;
763 paint.setBlendMode(SkBlendMode::kSrc);
764 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
765 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
766 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
767 String8::format("SurfaceID|%" PRId64, id).c_str(),
768 nullptr);
769 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
770 } else {
771 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
772 }
773 }
774
775 // assign dstCanvas to canvas and ensure that the canvas state is up to date
776 canvas = dstCanvas;
777 surfaceAutoSaveRestore.replace(canvas);
778 initCanvas(canvas, display);
779
780 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
781 dstSurface->getCanvas()->getSaveCount());
782 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
783 dstSurface->getCanvas()->getTotalMatrix());
784
785 // assign dstSurface to activeSurface
786 activeSurface = dstSurface;
787 }
788
789 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
790 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
791 // Record the name of the layer if the capture is running.
792 std::stringstream layerSettings;
793 PrintTo(layer, &layerSettings);
794 // Store the LayerSettings in additional information.
795 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
796 SkData::MakeWithCString(layerSettings.str().c_str()));
797 }
798 // Layers have a local transform that should be applied to them
799 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
800
801 const auto [bounds, roundRectClip] =
802 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
803 layer.geometry.roundedCornersRadius);
804 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
805 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
806
807 // if multiple layers have blur, then we need to take a snapshot now because
808 // only the lowest layer will have blurImage populated earlier
809 if (!blurInput) {
810 blurInput = activeSurface->makeImageSnapshot();
811 }
812 // rect to be blurred in the coordinate space of blurInput
813 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
814
815 // if the clip needs to be applied then apply it now and make sure
816 // it is restored before we attempt to draw any shadows.
817 SkAutoCanvasRestore acr(canvas, true);
818 if (!roundRectClip.isEmpty()) {
819 canvas->clipRRect(roundRectClip, true);
820 }
821
822 // TODO(b/182216890): Filter out empty layers earlier
823 if (blurRect.width() > 0 && blurRect.height() > 0) {
824 if (layer.backgroundBlurRadius > 0) {
825 ATRACE_NAME("BackgroundBlur");
826 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
827 blurInput, blurRect);
828
829 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
830
831 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
832 blurRect, blurredImage, blurInput);
833 }
834
835 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
836 for (auto region : layer.blurRegions) {
837 if (cachedBlurs[region.blurRadius] == nullptr) {
838 ATRACE_NAME("BlurRegion");
839 cachedBlurs[region.blurRadius] =
840 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
841 blurRect);
842 }
843
844 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
845 region.alpha, blurRect,
846 cachedBlurs[region.blurRadius], blurInput);
847 }
848 }
849 }
850
851 if (layer.shadow.length > 0) {
852 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
853 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
854
855 SkRRect shadowBounds, shadowClip;
856 if (layer.geometry.boundaries == layer.shadow.boundaries) {
857 shadowBounds = bounds;
858 shadowClip = roundRectClip;
859 } else {
860 std::tie(shadowBounds, shadowClip) =
861 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
862 layer.geometry.roundedCornersRadius);
863 }
864
865 // Technically, if bounds is a rect and roundRectClip is not empty,
866 // it means that the bounds and roundedCornersCrop were different
867 // enough that we should intersect them to find the proper shadow.
868 // In practice, this often happens when the two rectangles appear to
869 // not match due to rounding errors. Draw the rounded version, which
870 // looks more like the intent.
871 const auto& rrect =
872 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
873 drawShadow(canvas, rrect, layer.shadow);
874 }
875
876 const float layerDimmingRatio = layer.whitePointNits <= 0.f
877 ? displayDimmingRatio
878 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
879
880 const bool dimInLinearSpace = display.dimmingStage !=
881 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
882
883 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
884 (mUseColorManagement &&
885 needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
886 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio));
887
888 // quick abort from drawing the remaining portion of the layer
889 if (layer.skipContentDraw ||
890 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
891 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
892 continue;
893 }
894
895 // If we need to map to linear space or color management is disabled, then mark the source
896 // image with the same colorspace as the destination surface so that Skia's color
897 // management is a no-op.
898 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
899 ? dstDataspace
900 : layer.sourceDataspace;
901
902 SkPaint paint;
903 if (layer.source.buffer.buffer) {
904 ATRACE_NAME("DrawImage");
905 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
906 const auto& item = layer.source.buffer;
907 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
908
909 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
910 iter != cache.end()) {
911 imageTextureRef = iter->second;
912 } else {
913 // If we didn't find the image in the cache, then create a local ref but don't cache
914 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
915 // we didn't find anything in the cache then we intentionally did not cache this
916 // buffer's resources.
917 imageTextureRef = std::make_shared<
918 AutoBackendTexture::LocalRef>(grContext,
919 item.buffer->getBuffer()->toAHardwareBuffer(),
920 false, mTextureCleanupMgr);
921 }
922
923 // if the layer's buffer has a fence, then we must must respect the fence prior to using
924 // the buffer.
925 if (layer.source.buffer.fence != nullptr) {
926 waitFence(grContext, layer.source.buffer.fence->get());
927 }
928
929 // isOpaque means we need to ignore the alpha in the image,
930 // replacing it with the alpha specified by the LayerSettings. See
931 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
932 // The proper way to do this is to use an SkColorType that ignores
933 // alpha, like kRGB_888x_SkColorType, and that is used if the
934 // incoming image is kRGBA_8888_SkColorType. However, the incoming
935 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
936 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
937 // kRGB_101010x_SkColorType, but it is not yet supported as a source
938 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
939 // meantime, we'll use a workaround that works unless we need to do
940 // any color conversion. The workaround requires that we pretend the
941 // image is already premultiplied, so that we do not premultiply it
942 // before applying SkBlendMode::kPlus.
943 const bool useIsOpaqueWorkaround = item.isOpaque &&
944 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
945 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
946 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
947 : item.isOpaque ? kOpaque_SkAlphaType
948 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
949 : kUnpremul_SkAlphaType;
950 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
951
952 auto texMatrix = getSkM44(item.textureTransform).asM33();
953 // textureTansform was intended to be passed directly into a shader, so when
954 // building the total matrix with the textureTransform we need to first
955 // normalize it, then apply the textureTransform, then scale back up.
956 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
957 texMatrix.postScale(image->width(), image->height());
958
959 SkMatrix matrix;
960 if (!texMatrix.invert(&matrix)) {
961 matrix = texMatrix;
962 }
963 // The shader does not respect the translation, so we add it to the texture
964 // transform for the SkImage. This will make sure that the correct layer contents
965 // are drawn in the correct part of the screen.
966 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
967
968 sk_sp<SkShader> shader;
969
970 if (layer.source.buffer.useTextureFiltering) {
971 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
972 SkSamplingOptions(
973 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
974 &matrix);
975 } else {
976 shader = image->makeShader(SkSamplingOptions(), matrix);
977 }
978
979 if (useIsOpaqueWorkaround) {
980 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
981 SkShaders::Color(SkColors::kBlack,
982 toSkColorSpace(layerDataspace)));
983 }
984
985 paint.setShader(createRuntimeEffectShader(
986 RuntimeEffectShaderParameters{.shader = shader,
987 .layer = layer,
988 .display = display,
989 .undoPremultipliedAlpha = !item.isOpaque &&
990 item.usePremultipliedAlpha,
991 .requiresLinearEffect = requiresLinearEffect,
992 .layerDimmingRatio = dimInLinearSpace
993 ? layerDimmingRatio
994 : 1.f}));
995
996 // Turn on dithering when dimming beyond this (arbitrary) threshold...
997 static constexpr float kDimmingThreshold = 0.2f;
998 // ...or we're rendering an HDR layer down to an 8-bit target
999 // Most HDR standards require at least 10-bits of color depth for source content, so we
1000 // can just extract the transfer function rather than dig into precise gralloc layout.
1001 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
1002 const bool requiresDownsample = isHdrDataspace(layer.sourceDataspace) &&
1003 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
1004 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
1005 paint.setDither(true);
1006 }
1007 paint.setAlphaf(layer.alpha);
1008
1009 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1010 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
1011
1012 // SysUI creates the alpha layer as a coverage layer, which is
1013 // appropriate for the DPU. Use a color matrix to convert it to
1014 // a mask.
1015 // TODO (b/219525258): Handle input as a mask.
1016 //
1017 // The color matrix will convert A8 pixels with no alpha to
1018 // black, as described by this vector. If the display handles
1019 // the color transform, we need to invert it to find the color
1020 // that will result in black after the DPU applies the transform.
1021 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1022 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1023 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1024 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1025 black = colorSpaceMatrix * black;
1026 } else {
1027 // We'll just have to use 0,0,0 as black, which should
1028 // be close to correct.
1029 ALOGI("Could not invert colorTransform!");
1030 }
1031 }
1032 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1033 0, 0, 0, 0, black[1],
1034 0, 0, 0, 0, black[2],
1035 0, 0, 0, -1, 1);
1036 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1037 // On the other hand, if the device doesn't handle it, we
1038 // have to apply it ourselves.
1039 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1040 }
1041 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
1042 }
1043 } else {
1044 ATRACE_NAME("DrawColor");
1045 const auto color = layer.source.solidColor;
1046 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1047 .fG = color.g,
1048 .fB = color.b,
1049 .fA = layer.alpha},
1050 toSkColorSpace(layerDataspace));
1051 paint.setShader(createRuntimeEffectShader(
1052 RuntimeEffectShaderParameters{.shader = shader,
1053 .layer = layer,
1054 .display = display,
1055 .undoPremultipliedAlpha = false,
1056 .requiresLinearEffect = requiresLinearEffect,
1057 .layerDimmingRatio = layerDimmingRatio}));
1058 }
1059
1060 if (layer.disableBlending) {
1061 paint.setBlendMode(SkBlendMode::kSrc);
1062 }
1063
1064 // An A8 buffer will already have the proper color filter attached to
1065 // its paint, including the displayColorTransform as needed.
1066 if (!paint.getColorFilter()) {
1067 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1068 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1069 // can assume a gamma 2.2 transfer function.
1070 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1071 const auto gammaCorrectedDimmingRatio =
1072 std::pow(layerDimmingRatio, kInverseGamma22);
1073 auto dimmingMatrix =
1074 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1075 gammaCorrectedDimmingRatio, 1.f));
1076
1077 const auto colorFilter =
1078 SkColorFilters::Matrix(toSkColorMatrix(std::move(dimmingMatrix)));
1079 paint.setColorFilter(displayColorTransform
1080 ? displayColorTransform->makeComposed(colorFilter)
1081 : colorFilter);
1082 } else {
1083 paint.setColorFilter(displayColorTransform);
1084 }
1085 }
1086
1087 if (!roundRectClip.isEmpty()) {
1088 canvas->clipRRect(roundRectClip, true);
1089 }
1090
1091 if (!bounds.isRect()) {
1092 paint.setAntiAlias(true);
1093 canvas->drawRRect(bounds, paint);
1094 } else {
1095 canvas->drawRect(bounds.rect(), paint);
1096 }
1097 if (kFlushAfterEveryLayer) {
1098 ATRACE_NAME("flush surface");
1099 activeSurface->flush();
1100 }
1101 }
1102 for (const auto& borderRenderInfo : display.borderInfoList) {
1103 SkPaint p;
1104 p.setColor(SkColor4f{borderRenderInfo.color.r, borderRenderInfo.color.g,
1105 borderRenderInfo.color.b, borderRenderInfo.color.a});
1106 p.setAntiAlias(true);
1107 p.setStyle(SkPaint::kStroke_Style);
1108 p.setStrokeWidth(borderRenderInfo.width);
1109 SkRegion sk_region;
1110 SkPath path;
1111
1112 // Construct a final SkRegion using Regions
1113 for (const auto& r : borderRenderInfo.combinedRegion) {
1114 sk_region.op({r.left, r.top, r.right, r.bottom}, SkRegion::kUnion_Op);
1115 }
1116
1117 sk_region.getBoundaryPath(&path);
1118 canvas->drawPath(path, p);
1119 path.close();
1120 }
1121
1122 surfaceAutoSaveRestore.restore();
1123 mCapture->endCapture();
1124 {
1125 ATRACE_NAME("flush surface");
1126 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1127 activeSurface->flush();
1128 }
1129
1130 base::unique_fd drawFence = flushAndSubmit(grContext);
Patrick Williams2e9748f2022-08-09 22:48:18 +00001131 resultPromise->set_value(sp<Fence>::make(std::move(drawFence)));
Lingfeng Yang00c1ff62022-06-02 09:19:28 -07001132}
1133
1134size_t SkiaRenderEngine::getMaxTextureSize() const {
1135 return mGrContext->maxTextureSize();
1136}
1137
1138size_t SkiaRenderEngine::getMaxViewportDims() const {
1139 return mGrContext->maxRenderTargetSize();
1140}
1141
1142void SkiaRenderEngine::drawShadow(SkCanvas* canvas,
1143 const SkRRect& casterRRect,
1144 const ShadowSettings& settings) {
1145 ATRACE_CALL();
1146 const float casterZ = settings.length / 2.0f;
1147 const auto flags =
1148 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1149
1150 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
1151 getSkPoint3(settings.lightPos), settings.lightRadius,
1152 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1153 flags);
1154}
1155
1156void SkiaRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
1157 // This cache multiplier was selected based on review of cache sizes relative
1158 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1159 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1160 // conservative default based on that analysis.
1161 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1162 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1163
1164 // start by resizing the current context
1165 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
1166
1167 // if it is possible to switch contexts then we will resize the other context
1168 const bool originalProtectedState = mInProtectedContext;
1169 useProtectedContext(!mInProtectedContext);
1170 if (mInProtectedContext != originalProtectedState) {
1171 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
1172 // reset back to the initial context that was active when this method was called
1173 useProtectedContext(originalProtectedState);
1174 }
1175}
1176
1177void SkiaRenderEngine::dump(std::string& result) {
1178 // Dump for the specific backend (GLES or Vk)
1179 appendBackendSpecificInfoToDump(result);
1180
1181 // Info about protected content
1182 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1183 supportsProtectedContent());
1184 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1185 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1186 mSkSLCacheMonitor.shadersCachedSinceLastCall());
1187
1188 std::vector<ResourcePair> cpuResourceMap = {
1189 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1190 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1191 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1192 {"skia/sk_resource_cache/tessellated", "Shadows"},
1193 {"skia", "Other"},
1194 };
1195 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1196 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1197 StringAppendF(&result, "Skia CPU Caches: ");
1198 cpuReporter.logTotals(result);
1199 cpuReporter.logOutput(result);
1200
1201 {
1202 std::lock_guard<std::mutex> lock(mRenderingMutex);
1203
1204 std::vector<ResourcePair> gpuResourceMap = {
1205 {"texture_renderbuffer", "Texture/RenderBuffer"},
1206 {"texture", "Texture"},
1207 {"gr_text_blob_cache", "Text"},
1208 {"skia", "Other"},
1209 };
1210 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1211 mGrContext->dumpMemoryStatistics(&gpuReporter);
1212 StringAppendF(&result, "Skia's GPU Caches: ");
1213 gpuReporter.logTotals(result);
1214 gpuReporter.logOutput(result);
1215 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1216 gpuReporter.logOutput(result, true);
1217
1218 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1219 mGraphicBufferExternalRefs.size());
1220 StringAppendF(&result, "Dumping buffer ids...\n");
1221 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1222 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1223 }
1224 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1225 mTextureCache.size());
1226 StringAppendF(&result, "Dumping buffer ids...\n");
1227 // TODO(178539829): It would be nice to know which layer these are coming from and what
1228 // the texture sizes are.
1229 for (const auto& [id, unused] : mTextureCache) {
1230 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1231 }
1232 StringAppendF(&result, "\n");
1233
1234 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
1235 if (mProtectedGrContext) {
1236 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1237 }
1238 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1239 gpuProtectedReporter.logTotals(result);
1240 gpuProtectedReporter.logOutput(result);
1241 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1242 gpuProtectedReporter.logOutput(result, true);
1243
1244 StringAppendF(&result, "\n");
1245 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1246 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1247 StringAppendF(&result, "- inputDataspace: %s\n",
1248 dataspaceDetails(
1249 static_cast<android_dataspace>(linearEffect.inputDataspace))
1250 .c_str());
1251 StringAppendF(&result, "- outputDataspace: %s\n",
1252 dataspaceDetails(
1253 static_cast<android_dataspace>(linearEffect.outputDataspace))
1254 .c_str());
1255 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1256 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1257 }
1258 }
1259 StringAppendF(&result, "\n");
1260}
1261
rnleec6a73642021-06-04 14:16:42 -07001262} // namespace skia
John Reck67b1e2b2020-08-26 13:17:24 -07001263} // namespace renderengine
rnleec6a73642021-06-04 14:16:42 -07001264} // namespace android