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