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_SKIAGLRENDERENGINE_H_
18 #define SF_SKIAGLRENDERENGINE_H_
19 
20 #include <EGL/egl.h>
21 #include <EGL/eglext.h>
22 #include <GLES2/gl2.h>
23 #include <GrDirectContext.h>
24 #include <SkSurface.h>
25 #include <android-base/thread_annotations.h>
26 #include <renderengine/ExternalTexture.h>
27 #include <renderengine/RenderEngine.h>
28 #include <sys/types.h>
29 
30 #include <mutex>
31 #include <unordered_map>
32 
33 #include "AutoBackendTexture.h"
34 #include "EGL/egl.h"
35 #include "GrContextOptions.h"
36 #include "SkImageInfo.h"
37 #include "SkiaRenderEngine.h"
38 #include "android-base/macros.h"
39 #include "debug/SkiaCapture.h"
40 #include "filters/BlurFilter.h"
41 #include "filters/LinearEffect.h"
42 #include "filters/StretchShaderFactory.h"
43 
44 namespace android {
45 namespace renderengine {
46 namespace skia {
47 
48 class SkiaGLRenderEngine : public skia::SkiaRenderEngine {
49 public:
50     static std::unique_ptr<SkiaGLRenderEngine> create(const RenderEngineCreationArgs& args);
51     SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display, EGLContext ctxt,
52                        EGLSurface placeholder, EGLContext protectedContext,
53                        EGLSurface protectedPlaceholder);
54     ~SkiaGLRenderEngine() override EXCLUDES(mRenderingMutex);
55 
56     std::future<void> primeCache() override;
57     status_t drawLayers(const DisplaySettings& display,
58                         const std::vector<const LayerSettings*>& layers,
59                         const std::shared_ptr<ExternalTexture>& buffer,
60                         const bool useFramebufferCache, base::unique_fd&& bufferFence,
61                         base::unique_fd* drawFence) override;
62     void cleanupPostRender() override;
cleanFramebufferCache()63     void cleanFramebufferCache() override{};
64     int getContextPriority() override;
isProtected()65     bool isProtected() const override { return mInProtectedContext; }
66     bool supportsProtectedContent() const override;
67     void useProtectedContext(bool useProtectedContext) override;
supportsBackgroundBlur()68     bool supportsBackgroundBlur() override { return mBlurFilter != nullptr; }
69     void assertShadersCompiled(int numShaders) override;
70     void onActiveDisplaySizeChanged(ui::Size size) override;
71     int reportShadersCompiled() override;
72 
73 protected:
74     void dump(std::string& result) override;
75     size_t getMaxTextureSize() const override;
76     size_t getMaxViewportDims() const override;
77     void mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer, bool isRenderable) override;
78     void unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) override;
79     bool canSkipPostRenderCleanup() const override;
80 
81 private:
82     static EGLConfig chooseEglConfig(EGLDisplay display, int format, bool logConfig);
83     static EGLContext createEglContext(EGLDisplay display, EGLConfig config,
84                                        EGLContext shareContext,
85                                        std::optional<ContextPriority> contextPriority,
86                                        Protection protection);
87     static std::optional<RenderEngine::ContextPriority> createContextPriority(
88             const RenderEngineCreationArgs& args);
89     static EGLSurface createPlaceholderEglPbufferSurface(EGLDisplay display, EGLConfig config,
90                                                          int hwcFormat, Protection protection);
91     inline SkRect getSkRect(const FloatRect& layer);
92     inline SkRect getSkRect(const Rect& layer);
93     inline std::pair<SkRRect, SkRRect> getBoundsAndClip(const FloatRect& bounds,
94                                                         const FloatRect& crop, float cornerRadius);
95     inline bool layerHasBlur(const LayerSettings* layer, bool colorTransformModifiesAlpha);
96     inline SkColor getSkColor(const vec4& color);
97     inline SkM44 getSkM44(const mat4& matrix);
98     inline SkPoint3 getSkPoint3(const vec3& vector);
99     inline GrDirectContext* getActiveGrContext() const;
100 
101     base::unique_fd flush();
102     // waitFence attempts to wait in the GPU, and if unable to waits on the CPU instead.
103     void waitFence(base::borrowed_fd fenceFd);
104     bool waitGpuFence(base::borrowed_fd fenceFd);
105 
106     void initCanvas(SkCanvas* canvas, const DisplaySettings& display);
107     void drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
108                     const ShadowSettings& shadowSettings);
109     // If requiresLinearEffect is true or the layer has a stretchEffect a new shader is returned.
110     // Otherwise it returns the input shader.
111     sk_sp<SkShader> createRuntimeEffectShader(sk_sp<SkShader> shader,
112                                               const LayerSettings* layer,
113                                               const DisplaySettings& display,
114                                               bool undoPremultipliedAlpha,
115                                               bool requiresLinearEffect);
116 
117     EGLDisplay mEGLDisplay;
118     EGLContext mEGLContext;
119     EGLSurface mPlaceholderSurface;
120     EGLContext mProtectedEGLContext;
121     EGLSurface mProtectedPlaceholderSurface;
122     BlurFilter* mBlurFilter = nullptr;
123 
124     const PixelFormat mDefaultPixelFormat;
125     const bool mUseColorManagement;
126 
127     // Identifier used or various mappings of layers to various
128     // textures or shaders
129     using GraphicBufferId = uint64_t;
130 
131     // Number of external holders of ExternalTexture references, per GraphicBuffer ID.
132     std::unordered_map<GraphicBufferId, int32_t> mGraphicBufferExternalRefs
133             GUARDED_BY(mRenderingMutex);
134     // Cache of GL textures that we'll store per GraphicBuffer ID, shared between GPU contexts.
135     std::unordered_map<GraphicBufferId, std::shared_ptr<AutoBackendTexture::LocalRef>> mTextureCache
136             GUARDED_BY(mRenderingMutex);
137     std::unordered_map<LinearEffect, sk_sp<SkRuntimeEffect>, LinearEffectHasher> mRuntimeEffects;
138     AutoBackendTexture::CleanupManager mTextureCleanupMgr GUARDED_BY(mRenderingMutex);
139 
140     StretchShaderFactory mStretchShaderFactory;
141     // Mutex guarding rendering operations, so that:
142     // 1. GL operations aren't interleaved, and
143     // 2. Internal state related to rendering that is potentially modified by
144     // multiple threads is guaranteed thread-safe.
145     mutable std::mutex mRenderingMutex;
146 
147     sp<Fence> mLastDrawFence;
148 
149     // Graphics context used for creating surfaces and submitting commands
150     sk_sp<GrDirectContext> mGrContext;
151     // Same as above, but for protected content (eg. DRM)
152     sk_sp<GrDirectContext> mProtectedGrContext;
153 
154     bool mInProtectedContext = false;
155     // Object to capture commands send to Skia.
156     std::unique_ptr<SkiaCapture> mCapture;
157 
158     // Implements PersistentCache as a way to monitor what SkSL shaders Skia has
159     // cached.
160     class SkSLCacheMonitor : public GrContextOptions::PersistentCache {
161     public:
162         SkSLCacheMonitor() = default;
163         ~SkSLCacheMonitor() override = default;
164 
165         sk_sp<SkData> load(const SkData& key) override;
166 
167         void store(const SkData& key, const SkData& data, const SkString& description) override;
168 
shadersCachedSinceLastCall()169         int shadersCachedSinceLastCall() {
170             const int shadersCachedSinceLastCall = mShadersCachedSinceLastCall;
171             mShadersCachedSinceLastCall = 0;
172             return shadersCachedSinceLastCall;
173         }
174 
175     private:
176         int mShadersCachedSinceLastCall = 0;
177     };
178 
179     SkSLCacheMonitor mSkSLCacheMonitor;
180 };
181 
182 } // namespace skia
183 } // namespace renderengine
184 } // namespace android
185 
186 #endif /* SF_GLESRENDERENGINE_H_ */
187