CanvasContext.h revision 0df6209a02d0ea99d2dff3a46ed9febd5925df4b
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 mRenderPipeline->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    ANDROID_API static void setTextureAtlas(RenderThread& thread,
129            const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize);
130
131    void stopDrawing();
132    void notifyFramePending();
133
134    FrameInfoVisualizer& profiler() { return mProfiler; }
135
136    void dumpFrames(int fd);
137    void resetFrameStats();
138
139    void setName(const std::string&& name) { mName = name; }
140    const std::string& name() { return mName; }
141
142    void serializeDisplayListTree();
143
144    void addRenderNode(RenderNode* node, bool placeFront) {
145        int pos = placeFront ? 0 : static_cast<int>(mRenderNodes.size());
146        mRenderNodes.emplace(mRenderNodes.begin() + pos, node);
147    }
148
149    void removeRenderNode(RenderNode* node) {
150        mRenderNodes.erase(std::remove(mRenderNodes.begin(), mRenderNodes.end(), node),
151                mRenderNodes.end());
152    }
153
154    void setContentDrawBounds(int left, int top, int right, int bottom) {
155        mContentDrawBounds.set(left, top, right, bottom);
156    }
157
158    RenderState& getRenderState() {
159        return mRenderThread.renderState();
160    }
161
162    void addFrameMetricsObserver(FrameMetricsObserver* observer) {
163        if (mFrameMetricsReporter.get() == nullptr) {
164            mFrameMetricsReporter.reset(new FrameMetricsReporter());
165        }
166
167        mFrameMetricsReporter->addObserver(observer);
168    }
169
170    void removeFrameMetricsObserver(FrameMetricsObserver* observer) {
171        if (mFrameMetricsReporter.get() != nullptr) {
172            mFrameMetricsReporter->removeObserver(observer);
173            if (!mFrameMetricsReporter->hasObservers()) {
174                mFrameMetricsReporter.reset(nullptr);
175            }
176        }
177    }
178
179    // Used to queue up work that needs to be completed before this frame completes
180    ANDROID_API void enqueueFrameWork(std::function<void()>&& func);
181
182    ANDROID_API int64_t getFrameNumber();
183
184    void waitOnFences();
185
186private:
187    CanvasContext(RenderThread& thread, bool translucent, RenderNode* rootRenderNode,
188            IContextFactory* contextFactory, std::unique_ptr<IRenderPipeline> renderPipeline);
189
190    friend class RegisterFrameCallbackTask;
191    // TODO: Replace with something better for layer & other GL object
192    // lifecycle tracking
193    friend class android::uirenderer::RenderState;
194
195    void setSurface(Surface* window);
196
197    void freePrefetchedLayers(TreeObserver* observer);
198
199    bool isSwapChainStuffed();
200
201    SkRect computeDirtyRect(const Frame& frame, SkRect* dirty);
202
203    EGLint mLastFrameWidth = 0;
204    EGLint mLastFrameHeight = 0;
205
206    RenderThread& mRenderThread;
207    sp<Surface> mNativeSurface;
208    // stopped indicates the CanvasContext will reject actual redraw operations,
209    // and defer repaint until it is un-stopped
210    bool mStopped = false;
211    // CanvasContext is dirty if it has received an update that it has not
212    // painted onto its surface.
213    bool mIsDirty = false;
214    SwapBehavior mSwapBehavior = SwapBehavior::kSwap_default;
215    struct SwapHistory {
216        SkRect damage;
217        nsecs_t vsyncTime;
218        nsecs_t swapCompletedTime;
219        nsecs_t dequeueDuration;
220        nsecs_t queueDuration;
221    };
222
223    RingBuffer<SwapHistory, 3> mSwapHistory;
224    int64_t mFrameNumber = -1;
225
226    // last vsync for a dropped frame due to stuffed queue
227    nsecs_t mLastDropVsync = 0;
228
229    bool mOpaque;
230    BakedOpRenderer::LightInfo mLightInfo;
231    FrameBuilder::LightGeometry mLightGeometry = { {0, 0, 0}, 0 };
232
233    bool mHaveNewSurface = false;
234    DamageAccumulator mDamageAccumulator;
235    LayerUpdateQueue mLayerUpdateQueue;
236    std::unique_ptr<AnimationContext> mAnimationContext;
237
238    std::vector< sp<RenderNode> > mRenderNodes;
239
240    FrameInfo* mCurrentFrameInfo = nullptr;
241    // Ring buffer large enough for 2 seconds worth of frames
242    RingBuffer<FrameInfo, 120> mFrames;
243    std::string mName;
244    JankTracker mJankTracker;
245    FrameInfoVisualizer mProfiler;
246    std::unique_ptr<FrameMetricsReporter> mFrameMetricsReporter;
247
248    std::set<RenderNode*> mPrefetchedLayers;
249
250    // Stores the bounds of the main content.
251    Rect mContentDrawBounds;
252
253    // TODO: This is really a Task<void> but that doesn't really work
254    // when Future<> expects to be able to get/set a value
255    struct FuncTask : public Task<bool> {
256        std::function<void()> func;
257    };
258    class FuncTaskProcessor;
259
260    std::vector< sp<FuncTask> > mFrameFences;
261    sp<TaskProcessor<bool> > mFrameWorkProcessor;
262    std::unique_ptr<IRenderPipeline> mRenderPipeline;
263};
264
265} /* namespace renderthread */
266} /* namespace uirenderer */
267} /* namespace android */
268