Debian Codegraph @

libs/hwui/renderthread/CanvasContext.h

raw symbols SCIP
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 */
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 */
92 bool pinImages(std::vector<SkImage*>& mutableImages) {
93 if (!Properties::isDrawingEnabled()) {
94 return true;
95 }
96 return mRenderPipeline->pinImages(mutableImages);
97 }
98 bool pinImages(LsaVector<sk_sp<Bitmap>>& images) {
99 if (!Properties::isDrawingEnabled()) {
100 return true;
101 }
102 return mRenderPipeline->pinImages(images);
103 }
104
105 /**
106 * Unpin any image that had be previously pinned to the GPU cache
107 */
108 void unpinImages() { mRenderPipeline->unpinImages(); }
109
110 static void invokeFunctor(const RenderThread& thread, Functor* functor);
111
112 static void prepareToDraw(const RenderThread& thread, Bitmap* bitmap);
113
114 /*
115 * If Properties::isSkiaEnabled() is true then this will return the Skia
116 * grContext associated with the current RenderPipeline.
117 */
118 GrDirectContext* getGrContext() const { return mRenderThread.getGrContext(); }
119
120 ASurfaceControl* getSurfaceControl() const { return mSurfaceControl; }
121 int32_t getSurfaceControlGenerationId() const { return mSurfaceControlGenerationId; }
122
123 // Won't take effect until next EGLSurface creation
124 void setSwapBehavior(SwapBehavior swapBehavior);
125
126 void setSurface(ANativeWindow* window, bool enableTimeout = true);
127 void setSurfaceControl(ASurfaceControl* surfaceControl);
128 bool pauseSurface();
129 void setStopped(bool stopped);
130 bool hasSurface() const { return mNativeSurface.get(); }
131 void allocateBuffers();
132
133 void setLightAlpha(uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha);
134 void setLightGeometry(const Vector3& lightCenter, float lightRadius);
135 void setOpaque(bool opaque);
136 void setColorMode(ColorMode mode);
137 bool makeCurrent();
138 void prepareTree(TreeInfo& info, int64_t* uiFrameInfo, int64_t syncQueued, RenderNode* target);
139 // Returns the DequeueBufferDuration.
140 nsecs_t draw();
141 void destroy();
142
143 // IFrameCallback, Choreographer-driven frame callback entry point
144 virtual void doFrame() override;
145 void prepareAndDraw(RenderNode* node);
146
147 void buildLayer(RenderNode* node);
148 void markLayerInUse(RenderNode* node);
149
150 void destroyHardwareResources();
151 static void trimMemory(RenderThread& thread, int level);
152
153 DeferredLayerUpdater* createTextureLayer();
154
155 void stopDrawing();
156 void notifyFramePending();
157
158 FrameInfoVisualizer& profiler() { return mProfiler; }
159
160 void dumpFrames(int fd);
161 void resetFrameStats();
162
163 void setName(const std::string&& name);
164
165 void addRenderNode(RenderNode* node, bool placeFront);
166 void removeRenderNode(RenderNode* node);
167
168 void setContentDrawBounds(const Rect& bounds) { mContentDrawBounds = bounds; }
169
170 void addFrameMetricsObserver(FrameMetricsObserver* observer);
171 void removeFrameMetricsObserver(FrameMetricsObserver* observer);
172
173 // Used to queue up work that needs to be completed before this frame completes
174 void enqueueFrameWork(std::function<void()>&& func);
175
176 uint64_t getFrameNumber();
177
178 void waitOnFences();
179
180 IRenderPipeline* getRenderPipeline() { return mRenderPipeline.get(); }
181
182 void addFrameCommitListener(std::function<void(bool)>&& func) {
183 mFrameCommitCallbacks.push_back(std::move(func));
184 }
185
186 void setPictureCapturedCallback(const std::function<void(sk_sp<SkPicture>&&)>& callback) {
187 mRenderPipeline->setPictureCapturedCallback(callback);
188 }
189
190 void setForceDark(bool enable) { mUseForceDark = enable; }
191
192 bool useForceDark() {
193 return mUseForceDark;
194 }
195
196 SkISize getNextFrameSize() const;
197
198 // Called when SurfaceStats are available.
199 static void onSurfaceStatsAvailable(void* context, int32_t surfaceControlId,
200 ASurfaceControlStats* stats);
201
202 void setASurfaceTransactionCallback(
203 const std::function<bool(int64_t, int64_t, int64_t)>& callback) {
204 mASurfaceTransactionCallback = callback;
205 }
206
207 bool mergeTransaction(ASurfaceTransaction* transaction, ASurfaceControl* control);
208
209 void setPrepareSurfaceControlForWebviewCallback(const std::function<void()>& callback) {
210 mPrepareSurfaceControlForWebviewCallback = callback;
211 }
212
213 void prepareSurfaceControlForWebview();
214
215 static CanvasContext* getActiveContext();
216
217 private:
218 CanvasContext(RenderThread& thread, bool translucent, RenderNode* rootRenderNode,
219 IContextFactory* contextFactory, std::unique_ptr<IRenderPipeline> renderPipeline);
220
221 friend class RegisterFrameCallbackTask;
222 // TODO: Replace with something better for layer & other GL object
223 // lifecycle tracking
224 friend class android::uirenderer::RenderState;
225
226 void freePrefetchedLayers();
227
228 bool isSwapChainStuffed();
229 bool surfaceRequiresRedraw();
230 void setupPipelineSurface();
231
232 SkRect computeDirtyRect(const Frame& frame, SkRect* dirty);
233 void finishFrame(FrameInfo* frameInfo);
234
235 /**
236 * Invoke 'reportFrameMetrics' on the last frame stored in 'mLast4FrameInfos'.
237 * Populate the 'presentTime' field before calling.
238 */
239 void reportMetricsWithPresentTime();
240
241 struct FrameMetricsInfo {
242 FrameInfo* frameInfo;
243 int64_t frameNumber;
244 int32_t surfaceId;
245 };
246
247 FrameInfo* getFrameInfoFromLast4(uint64_t frameNumber, uint32_t surfaceControlId);
248
249 // The same type as Frame.mWidth and Frame.mHeight
250 int32_t mLastFrameWidth = 0;
251 int32_t mLastFrameHeight = 0;
252
253 RenderThread& mRenderThread;
254 std::unique_ptr<ReliableSurface> mNativeSurface;
255 // The SurfaceControl reference is passed from ViewRootImpl, can be set to
256 // NULL to remove the reference
257 ASurfaceControl* mSurfaceControl = nullptr;
258 // id to track surface control changes and WebViewFunctor uses it to determine
259 // whether reparenting is needed also used by FrameMetricsReporter to determine
260 // if a frame is from an "old" surface (i.e. one that existed before the
261 // observer was attched) and therefore shouldn't be reported.
262 // NOTE: It is important that this is an increasing counter.
263 int32_t mSurfaceControlGenerationId = 0;
264 // stopped indicates the CanvasContext will reject actual redraw operations,
265 // and defer repaint until it is un-stopped
266 bool mStopped = false;
267 // Incremented each time the CanvasContext is stopped. Used to ignore
268 // delayed messages that are triggered after stopping.
269 int mGenerationID;
270 // CanvasContext is dirty if it has received an update that it has not
271 // painted onto its surface.
272 bool mIsDirty = false;
273 SwapBehavior mSwapBehavior = SwapBehavior::kSwap_default;
274 struct SwapHistory {
275 SkRect damage;
276 nsecs_t vsyncTime;
277 nsecs_t swapCompletedTime;
278 nsecs_t dequeueDuration;
279 nsecs_t queueDuration;
280 };
281
282 // Need at least 4 because we do quad buffer. Add a few more for good measure.
283 RingBuffer<SwapHistory, 7> mSwapHistory;
284 // Frame numbers start at 1, 0 means uninitialized
285 uint64_t mFrameNumber = 0;
286 int64_t mDamageId = 0;
287
288 // last vsync for a dropped frame due to stuffed queue
289 nsecs_t mLastDropVsync = 0;
290
291 bool mOpaque;
292 bool mUseForceDark = false;
293 LightInfo mLightInfo;
294 LightGeometry mLightGeometry = {{0, 0, 0}, 0};
295
296 bool mHaveNewSurface = false;
297 DamageAccumulator mDamageAccumulator;
298 LayerUpdateQueue mLayerUpdateQueue;
299 std::unique_ptr<AnimationContext> mAnimationContext;
300
301 std::vector<sp<RenderNode>> mRenderNodes;
302
303 FrameInfo* mCurrentFrameInfo = nullptr;
304
305 // List of data of frames that are awaiting GPU completion reporting. Used to compute frame
306 // metrics and determine whether or not to report the metrics.
307 RingBuffer<FrameMetricsInfo, 4> mLast4FrameMetricsInfos
308 GUARDED_BY(mLast4FrameMetricsInfosMutex);
309 std::mutex mLast4FrameMetricsInfosMutex;
310
311 std::string mName;
312 JankTracker mJankTracker;
313 FrameInfoVisualizer mProfiler;
314 std::unique_ptr<FrameMetricsReporter> mFrameMetricsReporter
315 GUARDED_BY(mFrameMetricsReporterMutex);
316 std::mutex mFrameMetricsReporterMutex;
317
318 std::set<RenderNode*> mPrefetchedLayers;
319
320 // Stores the bounds of the main content.
321 Rect mContentDrawBounds;
322
323 std::vector<std::future<void>> mFrameFences;
324 std::unique_ptr<IRenderPipeline> mRenderPipeline;
325
326 std::vector<std::function<void(bool)>> mFrameCommitCallbacks;
327
328 // If set to true, we expect that callbacks into onSurfaceStatsAvailable
329 bool mExpectSurfaceStats = false;
330
331 std::function<bool(int64_t, int64_t, int64_t)> mASurfaceTransactionCallback;
332 std::function<void()> mPrepareSurfaceControlForWebviewCallback;
333
334 void cleanupResources();
335 };
336
337 } /* namespace renderthread */
338 } /* namespace uirenderer */
339 } /* namespace android */