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