CanvasContext.h revision df1742ed47da1e9b61afeae16fa448d5302a8aa0
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     * Pin any mutable images to the GPU cache. A pinned images is guaranteed to
84     * remain in the cache until it has been unpinned. We leverage this feature
85     * to avoid making a CPU copy of the pixels.
86     *
87     * @return true if all images have been successfully pinned to the GPU cache
88     *         and false otherwise (e.g. cache limits have been exceeded).
89     */
90    bool pinImages(std::vector<SkImage*>& mutableImages) {
91        return mRenderPipeline->pinImages(mutableImages);
92    }
93    bool pinImages(LsaVector<sk_sp<Bitmap>>& images) {
94        return mRenderPipeline->pinImages(images);
95    }
96
97    /**
98     * Unpin any image that had be previously pinned to the GPU cache
99     */
100    void unpinImages() { mRenderPipeline->unpinImages(); }
101
102    /**
103     * Destroy any layers that have been attached to the provided RenderNode removing
104     * any state that may have been set during createOrUpdateLayer().
105     */
106    static void destroyLayer(RenderNode* node);
107
108    static void invokeFunctor(const RenderThread& thread, Functor* functor);
109
110    static void prepareToDraw(const RenderThread& thread, Bitmap* bitmap);
111
112    /*
113     * If Properties::isSkiaEnabled() is true then this will return the Skia
114     * grContext associated with the current RenderPipeline.
115     */
116    GrContext* getGrContext() const { return mRenderThread.getGrContext(); }
117
118    // Won't take effect until next EGLSurface creation
119    void setSwapBehavior(SwapBehavior swapBehavior);
120
121    void initialize(Surface* surface);
122    void updateSurface(Surface* surface);
123    bool pauseSurface(Surface* surface);
124    void setStopped(bool stopped);
125    bool hasSurface() { return mNativeSurface.get(); }
126
127    void setup(float lightRadius,
128            uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha);
129    void setLightCenter(const Vector3& lightCenter);
130    void setOpaque(bool opaque);
131    bool makeCurrent();
132    void prepareTree(TreeInfo& info, int64_t* uiFrameInfo,
133            int64_t syncQueued, RenderNode* target);
134    void draw();
135    void destroy();
136
137    // IFrameCallback, Choreographer-driven frame callback entry point
138    virtual void doFrame() override;
139    void prepareAndDraw(RenderNode* node);
140
141    void buildLayer(RenderNode* node);
142    bool copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap);
143    void markLayerInUse(RenderNode* node);
144
145    void destroyHardwareResources();
146    static void trimMemory(RenderThread& thread, int level);
147
148    DeferredLayerUpdater* createTextureLayer();
149
150    void stopDrawing();
151    void notifyFramePending();
152
153    FrameInfoVisualizer& profiler() { return mProfiler; }
154
155    void dumpFrames(int fd);
156    void resetFrameStats();
157
158    void setName(const std::string&& name);
159
160    void serializeDisplayListTree();
161
162    void addRenderNode(RenderNode* node, bool placeFront);
163    void removeRenderNode(RenderNode* node);
164
165    void setContentDrawBounds(int left, int top, int right, int bottom) {
166        mContentDrawBounds.set(left, top, right, bottom);
167    }
168
169    RenderState& getRenderState() {
170        return mRenderThread.renderState();
171    }
172
173    void addFrameMetricsObserver(FrameMetricsObserver* observer) {
174        if (mFrameMetricsReporter.get() == nullptr) {
175            mFrameMetricsReporter.reset(new FrameMetricsReporter());
176        }
177
178        mFrameMetricsReporter->addObserver(observer);
179    }
180
181    void removeFrameMetricsObserver(FrameMetricsObserver* observer) {
182        if (mFrameMetricsReporter.get() != nullptr) {
183            mFrameMetricsReporter->removeObserver(observer);
184            if (!mFrameMetricsReporter->hasObservers()) {
185                mFrameMetricsReporter.reset(nullptr);
186            }
187        }
188    }
189
190    // Used to queue up work that needs to be completed before this frame completes
191    ANDROID_API void enqueueFrameWork(std::function<void()>&& func);
192
193    ANDROID_API int64_t getFrameNumber();
194
195    void waitOnFences();
196
197private:
198    CanvasContext(RenderThread& thread, bool translucent, RenderNode* rootRenderNode,
199            IContextFactory* contextFactory, std::unique_ptr<IRenderPipeline> renderPipeline);
200
201    friend class RegisterFrameCallbackTask;
202    // TODO: Replace with something better for layer & other GL object
203    // lifecycle tracking
204    friend class android::uirenderer::RenderState;
205
206    void setSurface(Surface* window);
207
208    void freePrefetchedLayers();
209
210    bool isSwapChainStuffed();
211
212    SkRect computeDirtyRect(const Frame& frame, SkRect* dirty);
213
214    EGLint mLastFrameWidth = 0;
215    EGLint mLastFrameHeight = 0;
216
217    RenderThread& mRenderThread;
218    sp<Surface> mNativeSurface;
219    // stopped indicates the CanvasContext will reject actual redraw operations,
220    // and defer repaint until it is un-stopped
221    bool mStopped = false;
222    // CanvasContext is dirty if it has received an update that it has not
223    // painted onto its surface.
224    bool mIsDirty = false;
225    SwapBehavior mSwapBehavior = SwapBehavior::kSwap_default;
226    struct SwapHistory {
227        SkRect damage;
228        nsecs_t vsyncTime;
229        nsecs_t swapCompletedTime;
230        nsecs_t dequeueDuration;
231        nsecs_t queueDuration;
232    };
233
234    RingBuffer<SwapHistory, 3> mSwapHistory;
235    int64_t mFrameNumber = -1;
236
237    // last vsync for a dropped frame due to stuffed queue
238    nsecs_t mLastDropVsync = 0;
239
240    bool mOpaque;
241    BakedOpRenderer::LightInfo mLightInfo;
242    FrameBuilder::LightGeometry mLightGeometry = { {0, 0, 0}, 0 };
243
244    bool mHaveNewSurface = false;
245    DamageAccumulator mDamageAccumulator;
246    LayerUpdateQueue mLayerUpdateQueue;
247    std::unique_ptr<AnimationContext> mAnimationContext;
248
249    std::vector< sp<RenderNode> > mRenderNodes;
250
251    FrameInfo* mCurrentFrameInfo = nullptr;
252    // Ring buffer large enough for 2 seconds worth of frames
253    RingBuffer<FrameInfo, 120> mFrames;
254    std::string mName;
255    JankTracker mJankTracker;
256    FrameInfoVisualizer mProfiler;
257    std::unique_ptr<FrameMetricsReporter> mFrameMetricsReporter;
258
259    std::set<RenderNode*> mPrefetchedLayers;
260
261    // Stores the bounds of the main content.
262    Rect mContentDrawBounds;
263
264    // TODO: This is really a Task<void> but that doesn't really work
265    // when Future<> expects to be able to get/set a value
266    struct FuncTask : public Task<bool> {
267        std::function<void()> func;
268    };
269    class FuncTaskProcessor;
270
271    std::vector< sp<FuncTask> > mFrameFences;
272    sp<TaskProcessor<bool> > mFrameWorkProcessor;
273    std::unique_ptr<IRenderPipeline> mRenderPipeline;
274};
275
276} /* namespace renderthread */
277} /* namespace uirenderer */
278} /* namespace android */
279