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