• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 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 #pragma once
18 
19 #include "DamageAccumulator.h"
20 #include "FrameInfo.h"
21 #include "FrameInfoVisualizer.h"
22 #include "FrameMetricsReporter.h"
23 #include "IContextFactory.h"
24 #include "IRenderPipeline.h"
25 #include "JankTracker.h"
26 #include "LayerUpdateQueue.h"
27 #include "Lighting.h"
28 #include "ReliableSurface.h"
29 #include "RenderNode.h"
30 #include "renderthread/RenderTask.h"
31 #include "renderthread/RenderThread.h"
32 #include "utils/RingBuffer.h"
33 #include "ColorMode.h"
34 
35 #include <SkBitmap.h>
36 #include <SkRect.h>
37 #include <SkSize.h>
38 #include <cutils/compiler.h>
39 #include <utils/Functor.h>
40 #include <utils/Mutex.h>
41 
42 #include <functional>
43 #include <future>
44 #include <set>
45 #include <string>
46 #include <utility>
47 #include <vector>
48 
49 namespace android {
50 namespace uirenderer {
51 
52 class AnimationContext;
53 class DeferredLayerUpdater;
54 class ErrorHandler;
55 class Layer;
56 class Rect;
57 class RenderState;
58 
59 namespace renderthread {
60 
61 class Frame;
62 
63 // This per-renderer class manages the bridge between the global EGL context
64 // and the render surface.
65 // TODO: Rename to Renderer or some other per-window, top-level manager
66 class CanvasContext : public IFrameCallback {
67 public:
68     static CanvasContext* create(RenderThread& thread, bool translucent, RenderNode* rootRenderNode,
69                                  IContextFactory* contextFactory);
70     virtual ~CanvasContext();
71 
72     /**
73      * Update or create a layer specific for the provided RenderNode. The layer
74      * attached to the node will be specific to the RenderPipeline used by this
75      * context
76      *
77      *  @return true if the layer has been created or updated
78      */
createOrUpdateLayer(RenderNode * node,const DamageAccumulator & dmgAccumulator,ErrorHandler * errorHandler)79     bool createOrUpdateLayer(RenderNode* node, const DamageAccumulator& dmgAccumulator,
80                              ErrorHandler* errorHandler) {
81         return mRenderPipeline->createOrUpdateLayer(node, dmgAccumulator, errorHandler);
82     }
83 
84     /**
85      * Pin any mutable images to the GPU cache. A pinned images is guaranteed to
86      * remain in the cache until it has been unpinned. We leverage this feature
87      * to avoid making a CPU copy of the pixels.
88      *
89      * @return true if all images have been successfully pinned to the GPU cache
90      *         and false otherwise (e.g. cache limits have been exceeded).
91      */
pinImages(std::vector<SkImage * > & mutableImages)92     bool pinImages(std::vector<SkImage*>& mutableImages) {
93         return mRenderPipeline->pinImages(mutableImages);
94     }
pinImages(LsaVector<sk_sp<Bitmap>> & images)95     bool pinImages(LsaVector<sk_sp<Bitmap>>& images) { return mRenderPipeline->pinImages(images); }
96 
97     /**
98      * Unpin any image that had be previously pinned to the GPU cache
99      */
unpinImages()100     void unpinImages() { mRenderPipeline->unpinImages(); }
101 
102     static void invokeFunctor(const RenderThread& thread, Functor* functor);
103 
104     static void prepareToDraw(const RenderThread& thread, Bitmap* bitmap);
105 
106     /*
107      * If Properties::isSkiaEnabled() is true then this will return the Skia
108      * grContext associated with the current RenderPipeline.
109      */
getGrContext()110     GrDirectContext* getGrContext() const { return mRenderThread.getGrContext(); }
111 
getSurfaceControl()112     ASurfaceControl* getSurfaceControl() const { return mSurfaceControl; }
getSurfaceControlGenerationId()113     int32_t getSurfaceControlGenerationId() const { return mSurfaceControlGenerationId; }
114 
115     // Won't take effect until next EGLSurface creation
116     void setSwapBehavior(SwapBehavior swapBehavior);
117 
118     void setSurface(ANativeWindow* window, bool enableTimeout = true);
119     void setSurfaceControl(ASurfaceControl* surfaceControl);
120     bool pauseSurface();
121     void setStopped(bool stopped);
hasSurface()122     bool hasSurface() const { return mNativeSurface.get(); }
123     void allocateBuffers();
124 
125     void setLightAlpha(uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha);
126     void setLightGeometry(const Vector3& lightCenter, float lightRadius);
127     void setOpaque(bool opaque);
128     void setColorMode(ColorMode mode);
129     bool makeCurrent();
130     void prepareTree(TreeInfo& info, int64_t* uiFrameInfo, int64_t syncQueued, RenderNode* target);
131     // Returns the DequeueBufferDuration.
132     nsecs_t draw();
133     void destroy();
134 
135     // IFrameCallback, Choreographer-driven frame callback entry point
136     virtual void doFrame() override;
137     void prepareAndDraw(RenderNode* node);
138 
139     void buildLayer(RenderNode* node);
140     void markLayerInUse(RenderNode* node);
141 
142     void destroyHardwareResources();
143     static void trimMemory(RenderThread& thread, int level);
144 
145     DeferredLayerUpdater* createTextureLayer();
146 
147     void stopDrawing();
148     void notifyFramePending();
149 
profiler()150     FrameInfoVisualizer& profiler() { return mProfiler; }
151 
152     void dumpFrames(int fd);
153     void resetFrameStats();
154 
155     void setName(const std::string&& name);
156 
157     void addRenderNode(RenderNode* node, bool placeFront);
158     void removeRenderNode(RenderNode* node);
159 
setContentDrawBounds(const Rect & bounds)160     void setContentDrawBounds(const Rect& bounds) { mContentDrawBounds = bounds; }
161 
addFrameMetricsObserver(FrameMetricsObserver * observer)162     void addFrameMetricsObserver(FrameMetricsObserver* observer) {
163         std::scoped_lock lock(mFrameMetricsReporterMutex);
164         if (mFrameMetricsReporter.get() == nullptr) {
165             mFrameMetricsReporter.reset(new FrameMetricsReporter());
166         }
167 
168         mFrameMetricsReporter->addObserver(observer);
169     }
170 
removeFrameMetricsObserver(FrameMetricsObserver * observer)171     void removeFrameMetricsObserver(FrameMetricsObserver* observer) {
172         std::scoped_lock lock(mFrameMetricsReporterMutex);
173         if (mFrameMetricsReporter.get() != nullptr) {
174             mFrameMetricsReporter->removeObserver(observer);
175             if (!mFrameMetricsReporter->hasObservers()) {
176                 mFrameMetricsReporter.reset(nullptr);
177             }
178         }
179     }
180 
181     // Used to queue up work that needs to be completed before this frame completes
182     void enqueueFrameWork(std::function<void()>&& func);
183 
184     int64_t getFrameNumber();
185 
186     void waitOnFences();
187 
getRenderPipeline()188     IRenderPipeline* getRenderPipeline() { return mRenderPipeline.get(); }
189 
addFrameCompleteListener(std::function<void (int64_t)> && func)190     void addFrameCompleteListener(std::function<void(int64_t)>&& func) {
191         mFrameCompleteCallbacks.push_back(std::move(func));
192     }
193 
setPictureCapturedCallback(const std::function<void (sk_sp<SkPicture> &&)> & callback)194     void setPictureCapturedCallback(const std::function<void(sk_sp<SkPicture>&&)>& callback) {
195         mRenderPipeline->setPictureCapturedCallback(callback);
196     }
197 
setForceDark(bool enable)198     void setForceDark(bool enable) { mUseForceDark = enable; }
199 
useForceDark()200     bool useForceDark() {
201         return mUseForceDark;
202     }
203 
204     SkISize getNextFrameSize() const;
205 
206     // Called when SurfaceStats are available.
207     static void onSurfaceStatsAvailable(void* context, ASurfaceControl* control,
208             ASurfaceControlStats* stats);
209 
setASurfaceTransactionCallback(const std::function<bool (int64_t,int64_t,int64_t)> & callback)210     void setASurfaceTransactionCallback(
211             const std::function<bool(int64_t, int64_t, int64_t)>& callback) {
212         mASurfaceTransactionCallback = callback;
213     }
214 
215     bool mergeTransaction(ASurfaceTransaction* transaction, ASurfaceControl* control);
216 
setPrepareSurfaceControlForWebviewCallback(const std::function<void ()> & callback)217     void setPrepareSurfaceControlForWebviewCallback(const std::function<void()>& callback) {
218         mPrepareSurfaceControlForWebviewCallback = callback;
219     }
220 
221     void prepareSurfaceControlForWebview();
222 
223     static CanvasContext* getActiveContext();
224 
225 private:
226     CanvasContext(RenderThread& thread, bool translucent, RenderNode* rootRenderNode,
227                   IContextFactory* contextFactory, std::unique_ptr<IRenderPipeline> renderPipeline);
228 
229     friend class RegisterFrameCallbackTask;
230     // TODO: Replace with something better for layer & other GL object
231     // lifecycle tracking
232     friend class android::uirenderer::RenderState;
233 
234     void freePrefetchedLayers();
235 
236     bool isSwapChainStuffed();
237     bool surfaceRequiresRedraw();
238     void setupPipelineSurface();
239 
240     SkRect computeDirtyRect(const Frame& frame, SkRect* dirty);
241     void finishFrame(FrameInfo* frameInfo);
242 
243     /**
244      * Invoke 'reportFrameMetrics' on the last frame stored in 'mLast4FrameInfos'.
245      * Populate the 'presentTime' field before calling.
246      */
247     void reportMetricsWithPresentTime();
248 
249     FrameInfo* getFrameInfoFromLast4(uint64_t frameNumber);
250 
251     // The same type as Frame.mWidth and Frame.mHeight
252     int32_t mLastFrameWidth = 0;
253     int32_t mLastFrameHeight = 0;
254 
255     RenderThread& mRenderThread;
256     std::unique_ptr<ReliableSurface> mNativeSurface;
257     // The SurfaceControl reference is passed from ViewRootImpl, can be set to
258     // NULL to remove the reference
259     ASurfaceControl* mSurfaceControl = nullptr;
260     // id to track surface control changes and WebViewFunctor uses it to determine
261     // whether reparenting is needed
262     int32_t mSurfaceControlGenerationId = 0;
263     // stopped indicates the CanvasContext will reject actual redraw operations,
264     // and defer repaint until it is un-stopped
265     bool mStopped = false;
266     // Incremented each time the CanvasContext is stopped. Used to ignore
267     // delayed messages that are triggered after stopping.
268     int mGenerationID;
269     // CanvasContext is dirty if it has received an update that it has not
270     // painted onto its surface.
271     bool mIsDirty = false;
272     SwapBehavior mSwapBehavior = SwapBehavior::kSwap_default;
273     struct SwapHistory {
274         SkRect damage;
275         nsecs_t vsyncTime;
276         nsecs_t swapCompletedTime;
277         nsecs_t dequeueDuration;
278         nsecs_t queueDuration;
279     };
280 
281     // Need at least 4 because we do quad buffer. Add a 5th for good measure.
282     RingBuffer<SwapHistory, 5> mSwapHistory;
283     int64_t mFrameNumber = -1;
284     int64_t mDamageId = 0;
285 
286     // last vsync for a dropped frame due to stuffed queue
287     nsecs_t mLastDropVsync = 0;
288 
289     bool mOpaque;
290     bool mUseForceDark = false;
291     LightInfo mLightInfo;
292     LightGeometry mLightGeometry = {{0, 0, 0}, 0};
293 
294     bool mHaveNewSurface = false;
295     DamageAccumulator mDamageAccumulator;
296     LayerUpdateQueue mLayerUpdateQueue;
297     std::unique_ptr<AnimationContext> mAnimationContext;
298 
299     std::vector<sp<RenderNode>> mRenderNodes;
300 
301     FrameInfo* mCurrentFrameInfo = nullptr;
302 
303     // List of frames that are awaiting GPU completion reporting
304     RingBuffer<std::pair<FrameInfo*, int64_t>, 4> mLast4FrameInfos
305             GUARDED_BY(mLast4FrameInfosMutex);
306     std::mutex mLast4FrameInfosMutex;
307 
308     std::string mName;
309     JankTracker mJankTracker;
310     FrameInfoVisualizer mProfiler;
311     std::unique_ptr<FrameMetricsReporter> mFrameMetricsReporter
312             GUARDED_BY(mFrameMetricsReporterMutex);
313     std::mutex mFrameMetricsReporterMutex;
314 
315     std::set<RenderNode*> mPrefetchedLayers;
316 
317     // Stores the bounds of the main content.
318     Rect mContentDrawBounds;
319 
320     std::vector<std::future<void>> mFrameFences;
321     std::unique_ptr<IRenderPipeline> mRenderPipeline;
322 
323     std::vector<std::function<void(int64_t)>> mFrameCompleteCallbacks;
324 
325     // If set to true, we expect that callbacks into onSurfaceStatsAvailable
326     bool mExpectSurfaceStats = false;
327 
328     std::function<bool(int64_t, int64_t, int64_t)> mASurfaceTransactionCallback;
329     std::function<void()> mPrepareSurfaceControlForWebviewCallback;
330 
331     void cleanupResources();
332 };
333 
334 } /* namespace renderthread */
335 } /* namespace uirenderer */
336 } /* namespace android */
337