CanvasContext.h revision 768e39335b668e8ef25fef30ab42b2d6d29a4735
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    // Won't take effect until next EGLSurface creation
72    void setSwapBehavior(SwapBehavior swapBehavior);
73
74    void initialize(Surface* surface);
75    void updateSurface(Surface* surface);
76    bool pauseSurface(Surface* surface);
77    void setStopped(bool stopped);
78    bool hasSurface() { return mNativeSurface.get(); }
79
80    void setup(float lightRadius,
81            uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha);
82    void setLightCenter(const Vector3& lightCenter);
83    void setOpaque(bool opaque);
84    bool makeCurrent();
85    void prepareTree(TreeInfo& info, int64_t* uiFrameInfo,
86            int64_t syncQueued, RenderNode* target);
87    void draw();
88    void destroy(TreeObserver* observer);
89
90    // IFrameCallback, Choreographer-driven frame callback entry point
91    virtual void doFrame() override;
92    void prepareAndDraw(RenderNode* node);
93
94    void buildLayer(RenderNode* node, TreeObserver* observer);
95    bool copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap);
96    void markLayerInUse(RenderNode* node);
97
98    void destroyHardwareResources(TreeObserver* observer);
99    static void trimMemory(RenderThread& thread, int level);
100
101    static void invokeFunctor(RenderThread& thread, Functor* functor);
102    static bool isSkiaEnabled();
103
104    Layer* createTextureLayer();
105
106    ANDROID_API static void setTextureAtlas(RenderThread& thread,
107            const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize);
108
109    void stopDrawing();
110    void notifyFramePending();
111
112    FrameInfoVisualizer& profiler() { return mProfiler; }
113
114    void dumpFrames(int fd);
115    void resetFrameStats();
116
117    void setName(const std::string&& name) { mName = name; }
118    const std::string& name() { return mName; }
119
120    void serializeDisplayListTree();
121
122    void addRenderNode(RenderNode* node, bool placeFront) {
123        int pos = placeFront ? 0 : static_cast<int>(mRenderNodes.size());
124        mRenderNodes.emplace(mRenderNodes.begin() + pos, node);
125    }
126
127    void removeRenderNode(RenderNode* node) {
128        mRenderNodes.erase(std::remove(mRenderNodes.begin(), mRenderNodes.end(), node),
129                mRenderNodes.end());
130    }
131
132    void setContentDrawBounds(int left, int top, int right, int bottom) {
133        mContentDrawBounds.set(left, top, right, bottom);
134    }
135
136    RenderState& getRenderState() {
137        return mRenderThread.renderState();
138    }
139
140    void addFrameMetricsObserver(FrameMetricsObserver* observer) {
141        if (mFrameMetricsReporter.get() == nullptr) {
142            mFrameMetricsReporter.reset(new FrameMetricsReporter());
143        }
144
145        mFrameMetricsReporter->addObserver(observer);
146    }
147
148    void removeFrameMetricsObserver(FrameMetricsObserver* observer) {
149        if (mFrameMetricsReporter.get() != nullptr) {
150            mFrameMetricsReporter->removeObserver(observer);
151            if (!mFrameMetricsReporter->hasObservers()) {
152                mFrameMetricsReporter.reset(nullptr);
153            }
154        }
155    }
156
157    // Used to queue up work that needs to be completed before this frame completes
158    ANDROID_API void enqueueFrameWork(std::function<void()>&& func);
159
160    ANDROID_API int64_t getFrameNumber();
161
162private:
163    CanvasContext(RenderThread& thread, bool translucent, RenderNode* rootRenderNode,
164            IContextFactory* contextFactory, std::unique_ptr<IRenderPipeline> renderPipeline);
165
166    friend class RegisterFrameCallbackTask;
167    // TODO: Replace with something better for layer & other GL object
168    // lifecycle tracking
169    friend class android::uirenderer::RenderState;
170
171    void setSurface(Surface* window);
172
173    void freePrefetchedLayers(TreeObserver* observer);
174
175    void waitOnFences();
176
177    bool isSwapChainStuffed();
178
179    SkRect computeDirtyRect(const Frame& frame, SkRect* dirty);
180
181    EGLint mLastFrameWidth = 0;
182    EGLint mLastFrameHeight = 0;
183
184    RenderThread& mRenderThread;
185    sp<Surface> mNativeSurface;
186    // stopped indicates the CanvasContext will reject actual redraw operations,
187    // and defer repaint until it is un-stopped
188    bool mStopped = false;
189    // CanvasContext is dirty if it has received an update that it has not
190    // painted onto its surface.
191    bool mIsDirty = false;
192    SwapBehavior mSwapBehavior = SwapBehavior::kSwap_default;
193    struct SwapHistory {
194        SkRect damage;
195        nsecs_t vsyncTime;
196        nsecs_t swapCompletedTime;
197        nsecs_t dequeueDuration;
198        nsecs_t queueDuration;
199    };
200
201    RingBuffer<SwapHistory, 3> mSwapHistory;
202    int64_t mFrameNumber = -1;
203
204    bool mOpaque;
205    BakedOpRenderer::LightInfo mLightInfo;
206    FrameBuilder::LightGeometry mLightGeometry = { {0, 0, 0}, 0 };
207
208    bool mHaveNewSurface = false;
209    DamageAccumulator mDamageAccumulator;
210    LayerUpdateQueue mLayerUpdateQueue;
211    std::unique_ptr<AnimationContext> mAnimationContext;
212
213    std::vector< sp<RenderNode> > mRenderNodes;
214
215    FrameInfo* mCurrentFrameInfo = nullptr;
216    // Ring buffer large enough for 2 seconds worth of frames
217    RingBuffer<FrameInfo, 120> mFrames;
218    std::string mName;
219    JankTracker mJankTracker;
220    FrameInfoVisualizer mProfiler;
221    std::unique_ptr<FrameMetricsReporter> mFrameMetricsReporter;
222
223    std::set<RenderNode*> mPrefetchedLayers;
224
225    // Stores the bounds of the main content.
226    Rect mContentDrawBounds;
227
228    // TODO: This is really a Task<void> but that doesn't really work
229    // when Future<> expects to be able to get/set a value
230    struct FuncTask : public Task<bool> {
231        std::function<void()> func;
232    };
233    class FuncTaskProcessor;
234
235    std::vector< sp<FuncTask> > mFrameFences;
236    sp<TaskProcessor<bool> > mFrameWorkProcessor;
237    std::unique_ptr<IRenderPipeline> mRenderPipeline;
238};
239
240} /* namespace renderthread */
241} /* namespace uirenderer */
242} /* namespace android */
243