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