CanvasContext.h revision 98f75d53dbe243b1661c616643698e025d4978f6
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 "BakedOpDispatcher.h"
20#include "BakedOpRenderer.h"
21#include "DamageAccumulator.h"
22#include "FrameBuilder.h"
23#include "FrameInfo.h"
24#include "FrameInfoVisualizer.h"
25#include "FrameMetricsReporter.h"
26#include "IContextFactory.h"
27#include "IRenderPipeline.h"
28#include "LayerUpdateQueue.h"
29#include "RenderNode.h"
30#include "thread/Task.h"
31#include "thread/TaskProcessor.h"
32#include "utils/RingBuffer.h"
33#include "renderthread/RenderTask.h"
34#include "renderthread/RenderThread.h"
35
36#include <cutils/compiler.h>
37#include <EGL/egl.h>
38#include <SkBitmap.h>
39#include <SkRect.h>
40#include <utils/Functor.h>
41#include <gui/Surface.h>
42
43#include <functional>
44#include <set>
45#include <string>
46#include <vector>
47
48namespace android {
49namespace uirenderer {
50
51class AnimationContext;
52class DeferredLayerUpdater;
53class Layer;
54class Rect;
55class RenderState;
56
57namespace renderthread {
58
59class EglManager;
60class Frame;
61
62// This per-renderer class manages the bridge between the global EGL context
63// and the render surface.
64// TODO: Rename to Renderer or some other per-window, top-level manager
65class CanvasContext : public IFrameCallback {
66public:
67    static CanvasContext* create(RenderThread& thread, bool translucent,
68            RenderNode* rootRenderNode, IContextFactory* contextFactory);
69    virtual ~CanvasContext();
70
71    /**
72     * Update or create a layer specific for the provided RenderNode. The layer
73     * attached to the node will be specific to the RenderPipeline used by this
74     * context
75     *
76     *  @return true if the layer has been created or updated
77     */
78    bool createOrUpdateLayer(RenderNode* node, const DamageAccumulator& dmgAccumulator) {
79        return mRenderPipeline->createOrUpdateLayer(node, dmgAccumulator);
80    }
81
82    /**
83     * Destroy any layers that have been attached to the provided RenderNode removing
84     * any state that may have been set during createOrUpdateLayer().
85     */
86    static void destroyLayer(RenderNode* node);
87
88    /*
89     * If Properties::isSkiaEnabled() is true then this will return the Skia
90     * grContext associated with the current RenderPipeline.
91     */
92    GrContext* getGrContext() const { return mRenderThread.getGrContext(); }
93
94    // Won't take effect until next EGLSurface creation
95    void setSwapBehavior(SwapBehavior swapBehavior);
96
97    void initialize(Surface* surface);
98    void updateSurface(Surface* surface);
99    bool pauseSurface(Surface* surface);
100    void setStopped(bool stopped);
101    bool hasSurface() { return mNativeSurface.get(); }
102
103    void setup(float lightRadius,
104            uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha);
105    void setLightCenter(const Vector3& lightCenter);
106    void setOpaque(bool opaque);
107    bool makeCurrent();
108    void prepareTree(TreeInfo& info, int64_t* uiFrameInfo,
109            int64_t syncQueued, RenderNode* target);
110    void draw();
111    void destroy(TreeObserver* observer);
112
113    // IFrameCallback, Choreographer-driven frame callback entry point
114    virtual void doFrame() override;
115    void prepareAndDraw(RenderNode* node);
116
117    void buildLayer(RenderNode* node, TreeObserver* observer);
118    bool copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap);
119    void markLayerInUse(RenderNode* node);
120
121    void destroyHardwareResources(TreeObserver* observer);
122    static void trimMemory(RenderThread& thread, int level);
123
124    static void invokeFunctor(RenderThread& thread, Functor* functor);
125
126    DeferredLayerUpdater* createTextureLayer();
127
128    void stopDrawing();
129    void notifyFramePending();
130
131    FrameInfoVisualizer& profiler() { return mProfiler; }
132
133    void dumpFrames(int fd);
134    void resetFrameStats();
135
136    void setName(const std::string&& name) { mName = name; }
137    const std::string& name() { return mName; }
138
139    void serializeDisplayListTree();
140
141    void addRenderNode(RenderNode* node, bool placeFront) {
142        int pos = placeFront ? 0 : static_cast<int>(mRenderNodes.size());
143        mRenderNodes.emplace(mRenderNodes.begin() + pos, node);
144    }
145
146    void removeRenderNode(RenderNode* node) {
147        mRenderNodes.erase(std::remove(mRenderNodes.begin(), mRenderNodes.end(), node),
148                mRenderNodes.end());
149    }
150
151    void setContentDrawBounds(int left, int top, int right, int bottom) {
152        mContentDrawBounds.set(left, top, right, bottom);
153    }
154
155    RenderState& getRenderState() {
156        return mRenderThread.renderState();
157    }
158
159    void addFrameMetricsObserver(FrameMetricsObserver* observer) {
160        if (mFrameMetricsReporter.get() == nullptr) {
161            mFrameMetricsReporter.reset(new FrameMetricsReporter());
162        }
163
164        mFrameMetricsReporter->addObserver(observer);
165    }
166
167    void removeFrameMetricsObserver(FrameMetricsObserver* observer) {
168        if (mFrameMetricsReporter.get() != nullptr) {
169            mFrameMetricsReporter->removeObserver(observer);
170            if (!mFrameMetricsReporter->hasObservers()) {
171                mFrameMetricsReporter.reset(nullptr);
172            }
173        }
174    }
175
176    // Used to queue up work that needs to be completed before this frame completes
177    ANDROID_API void enqueueFrameWork(std::function<void()>&& func);
178
179    ANDROID_API int64_t getFrameNumber();
180
181    void waitOnFences();
182
183private:
184    CanvasContext(RenderThread& thread, bool translucent, RenderNode* rootRenderNode,
185            IContextFactory* contextFactory, std::unique_ptr<IRenderPipeline> renderPipeline);
186
187    friend class RegisterFrameCallbackTask;
188    // TODO: Replace with something better for layer & other GL object
189    // lifecycle tracking
190    friend class android::uirenderer::RenderState;
191
192    void setSurface(Surface* window);
193
194    void freePrefetchedLayers(TreeObserver* observer);
195
196    bool isSwapChainStuffed();
197
198    SkRect computeDirtyRect(const Frame& frame, SkRect* dirty);
199
200    EGLint mLastFrameWidth = 0;
201    EGLint mLastFrameHeight = 0;
202
203    RenderThread& mRenderThread;
204    sp<Surface> mNativeSurface;
205    // stopped indicates the CanvasContext will reject actual redraw operations,
206    // and defer repaint until it is un-stopped
207    bool mStopped = false;
208    // CanvasContext is dirty if it has received an update that it has not
209    // painted onto its surface.
210    bool mIsDirty = false;
211    SwapBehavior mSwapBehavior = SwapBehavior::kSwap_default;
212    struct SwapHistory {
213        SkRect damage;
214        nsecs_t vsyncTime;
215        nsecs_t swapCompletedTime;
216        nsecs_t dequeueDuration;
217        nsecs_t queueDuration;
218    };
219
220    RingBuffer<SwapHistory, 3> mSwapHistory;
221    int64_t mFrameNumber = -1;
222
223    // last vsync for a dropped frame due to stuffed queue
224    nsecs_t mLastDropVsync = 0;
225
226    bool mOpaque;
227    BakedOpRenderer::LightInfo mLightInfo;
228    FrameBuilder::LightGeometry mLightGeometry = { {0, 0, 0}, 0 };
229
230    bool mHaveNewSurface = false;
231    DamageAccumulator mDamageAccumulator;
232    LayerUpdateQueue mLayerUpdateQueue;
233    std::unique_ptr<AnimationContext> mAnimationContext;
234
235    std::vector< sp<RenderNode> > mRenderNodes;
236
237    FrameInfo* mCurrentFrameInfo = nullptr;
238    // Ring buffer large enough for 2 seconds worth of frames
239    RingBuffer<FrameInfo, 120> mFrames;
240    std::string mName;
241    JankTracker mJankTracker;
242    FrameInfoVisualizer mProfiler;
243    std::unique_ptr<FrameMetricsReporter> mFrameMetricsReporter;
244
245    std::set<RenderNode*> mPrefetchedLayers;
246
247    // Stores the bounds of the main content.
248    Rect mContentDrawBounds;
249
250    // TODO: This is really a Task<void> but that doesn't really work
251    // when Future<> expects to be able to get/set a value
252    struct FuncTask : public Task<bool> {
253        std::function<void()> func;
254    };
255    class FuncTaskProcessor;
256
257    std::vector< sp<FuncTask> > mFrameFences;
258    sp<TaskProcessor<bool> > mFrameWorkProcessor;
259    std::unique_ptr<IRenderPipeline> mRenderPipeline;
260};
261
262} /* namespace renderthread */
263} /* namespace uirenderer */
264} /* namespace android */
265