xref: /aosp_15_r20/frameworks/native/libs/renderengine/skia/SkiaRenderEngine.h (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 #ifndef SF_SKIARENDERENGINE_H_
18 #define SF_SKIARENDERENGINE_H_
19 
20 #include <renderengine/RenderEngine.h>
21 
22 #include <android-base/thread_annotations.h>
23 #include <include/core/SkImageInfo.h>
24 #include <include/core/SkSurface.h>
25 #include <include/gpu/ganesh/GrBackendSemaphore.h>
26 #include <include/gpu/ganesh/GrContextOptions.h>
27 #include <renderengine/ExternalTexture.h>
28 #include <renderengine/RenderEngine.h>
29 #include <sys/types.h>
30 
31 #include <memory>
32 #include <mutex>
33 #include <unordered_map>
34 
35 #include "AutoBackendTexture.h"
36 #include "android-base/macros.h"
37 #include "compat/SkiaGpuContext.h"
38 #include "debug/SkiaCapture.h"
39 #include "filters/BlurFilter.h"
40 #include "filters/EdgeExtensionShaderFactory.h"
41 #include "filters/LinearEffect.h"
42 #include "filters/LutShader.h"
43 #include "filters/StretchShaderFactory.h"
44 
45 class SkData;
46 
47 struct SkPoint3;
48 
49 namespace android {
50 
51 namespace renderengine {
52 
53 class Mesh;
54 class Texture;
55 
56 namespace skia {
57 
58 class BlurFilter;
59 
60 class SkiaRenderEngine : public RenderEngine {
61 public:
62     static std::unique_ptr<SkiaRenderEngine> create(const RenderEngineCreationArgs& args);
63     SkiaRenderEngine(Threaded, PixelFormat pixelFormat, BlurAlgorithm);
64     ~SkiaRenderEngine() override;
65 
66     std::future<void> primeCache(PrimeCacheConfig config) override final;
67     void cleanupPostRender() override final;
supportsBackgroundBlur()68     bool supportsBackgroundBlur() override final {
69         return mBlurFilter != nullptr;
70     }
71     void onActiveDisplaySizeChanged(ui::Size size) override final;
72     int reportShadersCompiled();
73 
74     virtual void setEnableTracing(bool tracingEnabled) override final;
75 
76     void useProtectedContext(bool useProtectedContext) override;
supportsProtectedContent()77     bool supportsProtectedContent() const override {
78         return supportsProtectedContentImpl();
79     }
80     void ensureContextsCreated();
81 
82 protected:
83     // This is so backends can stop the generic rendering state first before cleaning up
84     // backend-specific state. SkiaGpuContexts are invalid after invocation.
85     void finishRenderingAndAbandonContexts();
86 
87     // Functions that a given backend (GLES, Vulkan) must implement
88     using Contexts = std::pair<unique_ptr<SkiaGpuContext>, unique_ptr<SkiaGpuContext>>;
89     virtual Contexts createContexts() = 0;
90     virtual bool supportsProtectedContentImpl() const = 0;
91     virtual bool useProtectedContextImpl(GrProtected isProtected) = 0;
92     virtual void waitFence(SkiaGpuContext* context, base::borrowed_fd fenceFd) = 0;
93     virtual base::unique_fd flushAndSubmit(SkiaGpuContext* context,
94                                            sk_sp<SkSurface> dstSurface) = 0;
95     virtual void appendBackendSpecificInfoToDump(std::string& result) = 0;
96 
97     size_t getMaxTextureSize() const override final;
98     size_t getMaxViewportDims() const override final;
99     // TODO: b/293371537 - Return reference instead of pointer? (Cleanup)
100     SkiaGpuContext* getActiveContext();
101 
isProtected()102     bool isProtected() const { return mInProtectedContext; }
103 
104     // Implements PersistentCache as a way to monitor what SkSL shaders Skia has
105     // cached.
106     class SkSLCacheMonitor : public GrContextOptions::PersistentCache {
107     public:
108         SkSLCacheMonitor() = default;
109         ~SkSLCacheMonitor() override = default;
110 
111         sk_sp<SkData> load(const SkData& key) override;
112 
113         void store(const SkData& key, const SkData& data, const SkString& description) override;
114 
shadersCachedSinceLastCall()115         int shadersCachedSinceLastCall() {
116             const int shadersCachedSinceLastCall = mShadersCachedSinceLastCall;
117             mShadersCachedSinceLastCall = 0;
118             return shadersCachedSinceLastCall;
119         }
120 
totalShadersCompiled()121         int totalShadersCompiled() const { return mTotalShadersCompiled; }
122 
123     private:
124         int mShadersCachedSinceLastCall = 0;
125         int mTotalShadersCompiled = 0;
126     };
127 
128     SkSLCacheMonitor mSkSLCacheMonitor;
129 
130 private:
131     void mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
132                                   bool isRenderable) override final;
133     void unmapExternalTextureBuffer(sp<GraphicBuffer>&& buffer) override final;
134     bool canSkipPostRenderCleanup() const override final;
135 
136     std::shared_ptr<AutoBackendTexture::LocalRef> getOrCreateBackendTexture(
137             const sp<GraphicBuffer>& buffer, bool isOutputBuffer) REQUIRES(mRenderingMutex);
138     void initCanvas(SkCanvas* canvas, const DisplaySettings& display);
139     void drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
140                     const ShadowSettings& shadowSettings);
141     void drawLayersInternal(const std::shared_ptr<std::promise<FenceResult>>&& resultPromise,
142                             const DisplaySettings& display,
143                             const std::vector<LayerSettings>& layers,
144                             const std::shared_ptr<ExternalTexture>& buffer,
145                             base::unique_fd&& bufferFence) override final;
146     void drawGainmapInternal(const std::shared_ptr<std::promise<FenceResult>>&& resultPromise,
147                              const std::shared_ptr<ExternalTexture>& sdr,
148                              base::borrowed_fd&& sdrFence,
149                              const std::shared_ptr<ExternalTexture>& hdr,
150                              base::borrowed_fd&& hdrFence, float hdrSdrRatio,
151                              ui::Dataspace dataspace,
152                              const std::shared_ptr<ExternalTexture>& gainmap) override final;
153 
154     void dump(std::string& result) override final;
155 
156     // If requiresLinearEffect is true or the layer has a stretchEffect a new shader is returned.
157     // Otherwise it returns the input shader.
158     struct RuntimeEffectShaderParameters {
159         sk_sp<SkShader> shader;
160         const LayerSettings& layer;
161         const DisplaySettings& display;
162         bool undoPremultipliedAlpha;
163         bool requiresLinearEffect;
164         float layerDimmingRatio;
165         const ui::Dataspace outputDataSpace;
166         const ui::Dataspace fakeOutputDataspace;
167         const SkRect& imageBounds;
168     };
169     sk_sp<SkShader> createRuntimeEffectShader(const RuntimeEffectShaderParameters&);
170 
171     const PixelFormat mDefaultPixelFormat;
172 
173     // Identifier used for various mappings of layers to various
174     // textures or shaders
175     using GraphicBufferId = uint64_t;
176 
177     // Number of external holders of ExternalTexture references, per GraphicBuffer ID.
178     std::unordered_map<GraphicBufferId, int32_t> mGraphicBufferExternalRefs
179             GUARDED_BY(mRenderingMutex);
180     std::unordered_map<GraphicBufferId, std::shared_ptr<AutoBackendTexture::LocalRef>> mTextureCache
181             GUARDED_BY(mRenderingMutex);
182     std::unordered_map<shaders::LinearEffect, sk_sp<SkRuntimeEffect>, shaders::LinearEffectHasher>
183             mRuntimeEffects;
184     AutoBackendTexture::CleanupManager mTextureCleanupMgr GUARDED_BY(mRenderingMutex);
185 
186     StretchShaderFactory mStretchShaderFactory;
187     EdgeExtensionShaderFactory mEdgeExtensionShaderFactory;
188     LutShader mLutShader;
189 
190     sp<Fence> mLastDrawFence;
191     BlurFilter* mBlurFilter = nullptr;
192 
193     // Object to capture commands send to Skia.
194     std::unique_ptr<SkiaCapture> mCapture;
195 
196     // Mutex guarding rendering operations, so that internal state related to
197     // rendering that is potentially modified by multiple threads is guaranteed thread-safe.
198     mutable std::mutex mRenderingMutex;
199 
200     // Graphics context used for creating surfaces and submitting commands
201     unique_ptr<SkiaGpuContext> mContext;
202     // Same as above, but for protected content (eg. DRM)
203     unique_ptr<SkiaGpuContext> mProtectedContext;
204     bool mInProtectedContext = false;
205 };
206 
207 } // namespace skia
208 } // namespace renderengine
209 } // namespace android
210 
211 #endif /* SF_GLESRENDERENGINE_H_ */
212