CanvasContext.cpp revision aa95a88327d9a3ac8a4a00b065b78ac0f28b3a19
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#include "CanvasContext.h"
18
19#include <algorithm>
20#include <private/hwui/DrawGlInfo.h>
21#include <strings.h>
22
23#include "EglManager.h"
24#include "RenderThread.h"
25#include "../AnimationContext.h"
26#include "../Caches.h"
27#include "../DeferredLayerUpdater.h"
28#include "../RenderState.h"
29#include "../LayerRenderer.h"
30#include "../OpenGLRenderer.h"
31#include "../Stencil.h"
32
33#define TRIM_MEMORY_COMPLETE 80
34#define TRIM_MEMORY_UI_HIDDEN 20
35
36namespace android {
37namespace uirenderer {
38namespace renderthread {
39
40CanvasContext::CanvasContext(RenderThread& thread, bool translucent,
41        RenderNode* rootRenderNode, IContextFactory* contextFactory)
42        : mRenderThread(thread)
43        , mEglManager(thread.eglManager())
44        , mEglSurface(EGL_NO_SURFACE)
45        , mBufferPreserved(false)
46        , mSwapBehavior(kSwap_default)
47        , mOpaque(!translucent)
48        , mCanvas(NULL)
49        , mHaveNewSurface(false)
50        , mRootRenderNode(rootRenderNode) {
51    mAnimationContext = contextFactory->createAnimationContext(mRenderThread.timeLord());
52    mRenderThread.renderState().registerCanvasContext(this);
53}
54
55CanvasContext::~CanvasContext() {
56    destroy();
57    delete mAnimationContext;
58    mRenderThread.renderState().unregisterCanvasContext(this);
59}
60
61void CanvasContext::destroy() {
62    stopDrawing();
63    freePrefetechedLayers();
64    destroyHardwareResources();
65    mAnimationContext->destroy();
66    if (mCanvas) {
67        delete mCanvas;
68        mCanvas = 0;
69    }
70    setSurface(NULL);
71}
72
73void CanvasContext::setSurface(ANativeWindow* window) {
74    mNativeWindow = window;
75
76    if (mEglSurface != EGL_NO_SURFACE) {
77        mEglManager.destroySurface(mEglSurface);
78        mEglSurface = EGL_NO_SURFACE;
79    }
80
81    if (window) {
82        mEglSurface = mEglManager.createSurface(window);
83    }
84
85    if (mEglSurface != EGL_NO_SURFACE) {
86        const bool preserveBuffer = (mSwapBehavior != kSwap_discardBuffer);
87        mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer);
88        mHaveNewSurface = true;
89        makeCurrent();
90    } else {
91        mRenderThread.removeFrameCallback(this);
92    }
93}
94
95void CanvasContext::swapBuffers() {
96    if (CC_UNLIKELY(!mEglManager.swapBuffers(mEglSurface))) {
97        setSurface(NULL);
98    }
99    mHaveNewSurface = false;
100}
101
102void CanvasContext::requireSurface() {
103    LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE,
104            "requireSurface() called but no surface set!");
105    makeCurrent();
106}
107
108void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) {
109    mSwapBehavior = swapBehavior;
110}
111
112bool CanvasContext::initialize(ANativeWindow* window) {
113    setSurface(window);
114    if (mCanvas) return false;
115    mCanvas = new OpenGLRenderer(mRenderThread.renderState());
116    mCanvas->initProperties();
117    return true;
118}
119
120void CanvasContext::updateSurface(ANativeWindow* window) {
121    setSurface(window);
122}
123
124void CanvasContext::pauseSurface(ANativeWindow* window) {
125    stopDrawing();
126}
127
128// TODO: don't pass viewport size, it's automatic via EGL
129void CanvasContext::setup(int width, int height, const Vector3& lightCenter, float lightRadius,
130        uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
131    if (!mCanvas) return;
132    mCanvas->initLight(lightCenter, lightRadius, ambientShadowAlpha, spotShadowAlpha);
133}
134
135void CanvasContext::setOpaque(bool opaque) {
136    mOpaque = opaque;
137}
138
139void CanvasContext::makeCurrent() {
140    // TODO: Figure out why this workaround is needed, see b/13913604
141    // In the meantime this matches the behavior of GLRenderer, so it is not a regression
142    mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface);
143}
144
145void CanvasContext::processLayerUpdate(DeferredLayerUpdater* layerUpdater) {
146    bool success = layerUpdater->apply();
147    LOG_ALWAYS_FATAL_IF(!success, "Failed to update layer!");
148    if (layerUpdater->backingLayer()->deferredUpdateScheduled) {
149        mCanvas->pushLayerUpdate(layerUpdater->backingLayer());
150    }
151}
152
153void CanvasContext::prepareTree(TreeInfo& info) {
154    mRenderThread.removeFrameCallback(this);
155
156    info.damageAccumulator = &mDamageAccumulator;
157    info.renderer = mCanvas;
158    if (mPrefetechedLayers.size() && info.mode == TreeInfo::MODE_FULL) {
159        info.canvasContext = this;
160    }
161    mAnimationContext->startFrame(info.mode);
162    mRootRenderNode->prepareTree(info);
163    mAnimationContext->runRemainingAnimations(info);
164
165    if (info.canvasContext) {
166        freePrefetechedLayers();
167    }
168
169    if (CC_UNLIKELY(!mNativeWindow.get())) {
170        info.out.canDrawThisFrame = false;
171        return;
172    }
173
174    int runningBehind = 0;
175    // TODO: This query is moderately expensive, investigate adding some sort
176    // of fast-path based off when we last called eglSwapBuffers() as well as
177    // last vsync time. Or something.
178    mNativeWindow->query(mNativeWindow.get(),
179            NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &runningBehind);
180    info.out.canDrawThisFrame = !runningBehind;
181
182    if (info.out.hasAnimations || !info.out.canDrawThisFrame) {
183        if (!info.out.requiresUiRedraw) {
184            // If animationsNeedsRedraw is set don't bother posting for an RT anim
185            // as we will just end up fighting the UI thread.
186            mRenderThread.postFrameCallback(this);
187        }
188    }
189}
190
191void CanvasContext::stopDrawing() {
192    mRenderThread.removeFrameCallback(this);
193}
194
195void CanvasContext::notifyFramePending() {
196    ATRACE_CALL();
197    mRenderThread.pushBackFrameCallback(this);
198}
199
200void CanvasContext::draw() {
201    LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE,
202            "drawRenderNode called on a context with no canvas or surface!");
203
204    profiler().markPlaybackStart();
205
206    SkRect dirty;
207    mDamageAccumulator.finish(&dirty);
208
209    EGLint width, height;
210    mEglManager.beginFrame(mEglSurface, &width, &height);
211    if (width != mCanvas->getViewportWidth() || height != mCanvas->getViewportHeight()) {
212        mCanvas->setViewport(width, height);
213        dirty.setEmpty();
214    } else if (!mBufferPreserved || mHaveNewSurface) {
215        dirty.setEmpty();
216    } else {
217        if (!dirty.isEmpty() && !dirty.intersect(0, 0, width, height)) {
218            ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?",
219                    SK_RECT_ARGS(dirty), width, height);
220            dirty.setEmpty();
221        }
222        profiler().unionDirty(&dirty);
223    }
224
225    status_t status;
226    if (!dirty.isEmpty()) {
227        status = mCanvas->prepareDirty(dirty.fLeft, dirty.fTop,
228                dirty.fRight, dirty.fBottom, mOpaque);
229    } else {
230        status = mCanvas->prepare(mOpaque);
231    }
232
233    Rect outBounds;
234    status |= mCanvas->drawRenderNode(mRootRenderNode.get(), outBounds);
235
236    profiler().draw(mCanvas);
237
238    mCanvas->finish();
239
240    profiler().markPlaybackEnd();
241
242    if (status & DrawGlInfo::kStatusDrew) {
243        swapBuffers();
244    } else {
245        mEglManager.cancelFrame();
246    }
247
248    profiler().finishFrame();
249}
250
251// Called by choreographer to do an RT-driven animation
252void CanvasContext::doFrame() {
253    if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) {
254        return;
255    }
256
257    ATRACE_CALL();
258
259    profiler().startFrame();
260
261    TreeInfo info(TreeInfo::MODE_RT_ONLY, mRenderThread.renderState());
262    prepareTree(info);
263    if (info.out.canDrawThisFrame) {
264        draw();
265    }
266}
267
268void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) {
269    ATRACE_CALL();
270    DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
271    if (thread.eglManager().hasEglContext()) {
272        thread.eglManager().requireGlContext();
273        mode = DrawGlInfo::kModeProcess;
274    }
275
276    thread.renderState().invokeFunctor(functor, mode, NULL);
277}
278
279void CanvasContext::markLayerInUse(RenderNode* node) {
280    if (mPrefetechedLayers.erase(node)) {
281        node->decStrong(0);
282    }
283}
284
285static void destroyPrefetechedNode(RenderNode* node) {
286    ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...", node->getName());
287    node->destroyHardwareResources();
288    node->decStrong(0);
289}
290
291void CanvasContext::freePrefetechedLayers() {
292    if (mPrefetechedLayers.size()) {
293        requireGlContext();
294        std::for_each(mPrefetechedLayers.begin(), mPrefetechedLayers.end(), destroyPrefetechedNode);
295        mPrefetechedLayers.clear();
296    }
297}
298
299void CanvasContext::buildLayer(RenderNode* node) {
300    ATRACE_CALL();
301    if (!mEglManager.hasEglContext() || !mCanvas) {
302        return;
303    }
304    requireGlContext();
305    // buildLayer() will leave the tree in an unknown state, so we must stop drawing
306    stopDrawing();
307
308    TreeInfo info(TreeInfo::MODE_FULL, mRenderThread.renderState());
309    info.damageAccumulator = &mDamageAccumulator;
310    info.renderer = mCanvas;
311    info.runAnimations = false;
312    node->prepareTree(info);
313    SkRect ignore;
314    mDamageAccumulator.finish(&ignore);
315    // Tickle the GENERIC property on node to mark it as dirty for damaging
316    // purposes when the frame is actually drawn
317    node->setPropertyFieldsDirty(RenderNode::GENERIC);
318
319    mCanvas->markLayersAsBuildLayers();
320    mCanvas->flushLayerUpdates();
321
322    node->incStrong(0);
323    mPrefetechedLayers.insert(node);
324}
325
326bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) {
327    requireGlContext();
328    layer->apply();
329    return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap);
330}
331
332void CanvasContext::destroyHardwareResources() {
333    stopDrawing();
334    if (mEglManager.hasEglContext()) {
335        requireGlContext();
336        freePrefetechedLayers();
337        mRootRenderNode->destroyHardwareResources();
338        Caches::getInstance().flush(Caches::kFlushMode_Layers);
339    }
340}
341
342void CanvasContext::trimMemory(RenderThread& thread, int level) {
343    // No context means nothing to free
344    if (!thread.eglManager().hasEglContext()) return;
345
346    ATRACE_CALL();
347    thread.eglManager().requireGlContext();
348    if (level >= TRIM_MEMORY_COMPLETE) {
349        Caches::getInstance().flush(Caches::kFlushMode_Full);
350        thread.eglManager().destroy();
351    } else if (level >= TRIM_MEMORY_UI_HIDDEN) {
352        Caches::getInstance().flush(Caches::kFlushMode_Moderate);
353    }
354}
355
356void CanvasContext::runWithGlContext(RenderTask* task) {
357    requireGlContext();
358    task->run();
359}
360
361Layer* CanvasContext::createTextureLayer() {
362    requireSurface();
363    return LayerRenderer::createTextureLayer(mRenderThread.renderState());
364}
365
366void CanvasContext::requireGlContext() {
367    mEglManager.requireGlContext();
368}
369
370void CanvasContext::setTextureAtlas(RenderThread& thread,
371        const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) {
372    thread.eglManager().setTextureAtlas(buffer, map, mapSize);
373}
374
375} /* namespace renderthread */
376} /* namespace uirenderer */
377} /* namespace android */
378