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