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 "renderthread/RenderTask.h"
31#include "renderthread/RenderThread.h"
32#include "thread/Task.h"
33#include "thread/TaskProcessor.h"
34
35#include <EGL/egl.h>
36#include <SkBitmap.h>
37#include <SkRect.h>
38#include <cutils/compiler.h>
39#include <gui/Surface.h>
40#include <utils/Functor.h>
41
42#include <functional>
43#include <set>
44#include <string>
45#include <vector>
46
47namespace android {
48namespace uirenderer {
49
50class AnimationContext;
51class DeferredLayerUpdater;
52class ErrorHandler;
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, RenderNode* rootRenderNode,
68                                 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                             ErrorHandler* errorHandler) {
80        return mRenderPipeline->createOrUpdateLayer(node, dmgAccumulator, mWideColorGamut,
81                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        return mRenderPipeline->pinImages(mutableImages);
94    }
95    bool pinImages(LsaVector<sk_sp<Bitmap>>& images) { return mRenderPipeline->pinImages(images); }
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 setSurface(sp<Surface>&& surface);
122    bool pauseSurface();
123    void setStopped(bool stopped);
124    bool hasSurface() { return mNativeSurface.get(); }
125
126    void setup(float lightRadius, uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha);
127    void setLightCenter(const Vector3& lightCenter);
128    void setOpaque(bool opaque);
129    void setWideGamut(bool wideGamut);
130    bool makeCurrent();
131    void prepareTree(TreeInfo& info, int64_t* uiFrameInfo, int64_t syncQueued, RenderNode* target);
132    void draw();
133    void destroy();
134
135    // IFrameCallback, Choreographer-driven frame callback entry point
136    virtual void doFrame() override;
137    void prepareAndDraw(RenderNode* node);
138
139    void buildLayer(RenderNode* node);
140    bool copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap);
141    void markLayerInUse(RenderNode* node);
142
143    void destroyHardwareResources();
144    static void trimMemory(RenderThread& thread, int level);
145
146    DeferredLayerUpdater* createTextureLayer();
147
148    void stopDrawing();
149    void notifyFramePending();
150
151    FrameInfoVisualizer& profiler() { return mProfiler; }
152
153    void dumpFrames(int fd);
154    void resetFrameStats();
155
156    void setName(const std::string&& name);
157
158    void serializeDisplayListTree();
159
160    void addRenderNode(RenderNode* node, bool placeFront);
161    void removeRenderNode(RenderNode* node);
162
163    void setContentDrawBounds(const Rect& bounds) { mContentDrawBounds = bounds; }
164
165    RenderState& getRenderState() { return mRenderThread.renderState(); }
166
167    void addFrameMetricsObserver(FrameMetricsObserver* observer) {
168        if (mFrameMetricsReporter.get() == nullptr) {
169            mFrameMetricsReporter.reset(new FrameMetricsReporter());
170        }
171
172        mFrameMetricsReporter->addObserver(observer);
173    }
174
175    void removeFrameMetricsObserver(FrameMetricsObserver* observer) {
176        if (mFrameMetricsReporter.get() != nullptr) {
177            mFrameMetricsReporter->removeObserver(observer);
178            if (!mFrameMetricsReporter->hasObservers()) {
179                mFrameMetricsReporter.reset(nullptr);
180            }
181        }
182    }
183
184    // Used to queue up work that needs to be completed before this frame completes
185    ANDROID_API void enqueueFrameWork(std::function<void()>&& func);
186
187    ANDROID_API int64_t getFrameNumber();
188
189    void waitOnFences();
190
191    IRenderPipeline* getRenderPipeline() { return mRenderPipeline.get(); }
192
193    void addFrameCompleteListener(std::function<void(int64_t)>&& func) {
194        mFrameCompleteCallbacks.push_back(std::move(func));
195    }
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 freePrefetchedLayers();
207
208    bool isSwapChainStuffed();
209
210    SkRect computeDirtyRect(const Frame& frame, SkRect* dirty);
211
212    EGLint mLastFrameWidth = 0;
213    EGLint mLastFrameHeight = 0;
214
215    RenderThread& mRenderThread;
216    sp<Surface> mNativeSurface;
217    // stopped indicates the CanvasContext will reject actual redraw operations,
218    // and defer repaint until it is un-stopped
219    bool mStopped = false;
220    // Incremented each time the CanvasContext is stopped. Used to ignore
221    // delayed messages that are triggered after stopping.
222    int mGenerationID;
223    // CanvasContext is dirty if it has received an update that it has not
224    // painted onto its surface.
225    bool mIsDirty = false;
226    SwapBehavior mSwapBehavior = SwapBehavior::kSwap_default;
227    struct SwapHistory {
228        SkRect damage;
229        nsecs_t vsyncTime;
230        nsecs_t swapCompletedTime;
231        nsecs_t dequeueDuration;
232        nsecs_t queueDuration;
233    };
234
235    RingBuffer<SwapHistory, 3> mSwapHistory;
236    int64_t mFrameNumber = -1;
237
238    // last vsync for a dropped frame due to stuffed queue
239    nsecs_t mLastDropVsync = 0;
240
241    bool mOpaque;
242    bool mWideColorGamut = false;
243    BakedOpRenderer::LightInfo mLightInfo;
244    FrameBuilder::LightGeometry mLightGeometry = {{0, 0, 0}, 0};
245
246    bool mHaveNewSurface = false;
247    DamageAccumulator mDamageAccumulator;
248    LayerUpdateQueue mLayerUpdateQueue;
249    std::unique_ptr<AnimationContext> mAnimationContext;
250
251    std::vector<sp<RenderNode>> mRenderNodes;
252
253    FrameInfo* mCurrentFrameInfo = nullptr;
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    std::vector<std::function<void(int64_t)>> mFrameCompleteCallbacks;
276};
277
278} /* namespace renderthread */
279} /* namespace uirenderer */
280} /* namespace android */
281