CanvasContext.cpp revision a3d795a34a786bbe8b5027f70df36b81328109c2
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 <GpuMemoryTracker.h>
18#include "CanvasContext.h"
19
20#include "AnimationContext.h"
21#include "Caches.h"
22#include "DeferredLayerUpdater.h"
23#include "EglManager.h"
24#include "LayerUpdateQueue.h"
25#include "LayerRenderer.h"
26#include "OpenGLRenderer.h"
27#include "Properties.h"
28#include "RenderThread.h"
29#include "hwui/Canvas.h"
30#include "renderstate/RenderState.h"
31#include "renderstate/Stencil.h"
32#include "protos/hwui.pb.h"
33#include "utils/GLUtils.h"
34#include "utils/TimeUtils.h"
35
36#include <cutils/properties.h>
37#include <google/protobuf/io/zero_copy_stream_impl.h>
38#include <private/hwui/DrawGlInfo.h>
39#include <strings.h>
40
41#include <algorithm>
42#include <fcntl.h>
43#include <sys/stat.h>
44
45#include <cstdlib>
46
47#define TRIM_MEMORY_COMPLETE 80
48#define TRIM_MEMORY_UI_HIDDEN 20
49
50#define ENABLE_RENDERNODE_SERIALIZATION false
51
52#define LOG_FRAMETIME_MMA 0
53
54#if LOG_FRAMETIME_MMA
55static float sBenchMma = 0;
56static int sFrameCount = 0;
57static const float NANOS_PER_MILLIS_F = 1000000.0f;
58#endif
59
60namespace android {
61namespace uirenderer {
62namespace renderthread {
63
64CanvasContext::CanvasContext(RenderThread& thread, bool translucent,
65        RenderNode* rootRenderNode, IContextFactory* contextFactory)
66        : mRenderThread(thread)
67        , mEglManager(thread.eglManager())
68        , mOpaque(!translucent)
69        , mAnimationContext(contextFactory->createAnimationContext(mRenderThread.timeLord()))
70        , mJankTracker(thread.timeLord().frameIntervalNanos())
71        , mProfiler(mFrames)
72        , mContentDrawBounds(0, 0, 0, 0) {
73    mRenderNodes.emplace_back(rootRenderNode);
74    mRenderThread.renderState().registerCanvasContext(this);
75    mProfiler.setDensity(mRenderThread.mainDisplayInfo().density);
76}
77
78CanvasContext::~CanvasContext() {
79    destroy(nullptr);
80    mRenderThread.renderState().unregisterCanvasContext(this);
81}
82
83void CanvasContext::destroy(TreeObserver* observer) {
84    stopDrawing();
85    setSurface(nullptr);
86    freePrefetchedLayers(observer);
87    destroyHardwareResources(observer);
88    mAnimationContext->destroy();
89#if !HWUI_NEW_OPS
90    if (mCanvas) {
91        delete mCanvas;
92        mCanvas = nullptr;
93    }
94#endif
95}
96
97void CanvasContext::setSurface(Surface* surface) {
98    ATRACE_CALL();
99
100    mNativeSurface = surface;
101
102    if (mEglSurface != EGL_NO_SURFACE) {
103        mEglManager.destroySurface(mEglSurface);
104        mEglSurface = EGL_NO_SURFACE;
105    }
106
107    if (surface) {
108        mEglSurface = mEglManager.createSurface(surface);
109    }
110
111    mFrameNumber = -1;
112
113    if (mEglSurface != EGL_NO_SURFACE) {
114        const bool preserveBuffer = (mSwapBehavior != kSwap_discardBuffer);
115        mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer);
116        mHaveNewSurface = true;
117        mSwapHistory.clear();
118    } else {
119        mRenderThread.removeFrameCallback(this);
120    }
121}
122
123void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) {
124    mSwapBehavior = swapBehavior;
125}
126
127void CanvasContext::initialize(Surface* surface) {
128    setSurface(surface);
129#if !HWUI_NEW_OPS
130    if (mCanvas) return;
131    mCanvas = new OpenGLRenderer(mRenderThread.renderState());
132    mCanvas->initProperties();
133#endif
134}
135
136void CanvasContext::updateSurface(Surface* surface) {
137    setSurface(surface);
138}
139
140bool CanvasContext::pauseSurface(Surface* surface) {
141    return mRenderThread.removeFrameCallback(this);
142}
143
144void CanvasContext::setStopped(bool stopped) {
145    if (mStopped != stopped) {
146        mStopped = stopped;
147        if (mStopped) {
148            mRenderThread.removeFrameCallback(this);
149            if (mEglManager.isCurrent(mEglSurface)) {
150                mEglManager.makeCurrent(EGL_NO_SURFACE);
151            }
152        } else if (mIsDirty && hasSurface()) {
153            mRenderThread.postFrameCallback(this);
154        }
155    }
156}
157
158// TODO: don't pass viewport size, it's automatic via EGL
159void CanvasContext::setup(int width, int height, float lightRadius,
160        uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
161#if HWUI_NEW_OPS
162    mLightGeometry.radius = lightRadius;
163    mLightInfo.ambientShadowAlpha = ambientShadowAlpha;
164    mLightInfo.spotShadowAlpha = spotShadowAlpha;
165#else
166    if (!mCanvas) return;
167    mCanvas->initLight(lightRadius, ambientShadowAlpha, spotShadowAlpha);
168#endif
169}
170
171void CanvasContext::setLightCenter(const Vector3& lightCenter) {
172#if HWUI_NEW_OPS
173    mLightGeometry.center = lightCenter;
174#else
175    if (!mCanvas) return;
176    mCanvas->setLightCenter(lightCenter);
177#endif
178}
179
180void CanvasContext::setOpaque(bool opaque) {
181    mOpaque = opaque;
182}
183
184bool CanvasContext::makeCurrent() {
185    if (mStopped) return false;
186
187    // TODO: Figure out why this workaround is needed, see b/13913604
188    // In the meantime this matches the behavior of GLRenderer, so it is not a regression
189    EGLint error = 0;
190    mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface, &error);
191    if (error) {
192        setSurface(nullptr);
193    }
194    return !error;
195}
196
197static bool wasSkipped(FrameInfo* info) {
198    return info && ((*info)[FrameInfoIndex::Flags] & FrameInfoFlags::SkippedFrame);
199}
200
201bool CanvasContext::isSwapChainStuffed() {
202    static const auto SLOW_THRESHOLD = 6_ms;
203
204    if (mSwapHistory.size() != mSwapHistory.capacity()) {
205        // We want at least 3 frames of history before attempting to
206        // guess if the queue is stuffed
207        return false;
208    }
209    nsecs_t frameInterval = mRenderThread.timeLord().frameIntervalNanos();
210    auto& swapA = mSwapHistory[0];
211
212    // Was there a happy queue & dequeue time? If so, don't
213    // consider it stuffed
214    if (swapA.dequeueDuration < SLOW_THRESHOLD
215            && swapA.queueDuration < SLOW_THRESHOLD) {
216        return false;
217    }
218
219    for (size_t i = 1; i < mSwapHistory.size(); i++) {
220        auto& swapB = mSwapHistory[i];
221
222        // If there's a multi-frameInterval gap we effectively already dropped a frame,
223        // so consider the queue healthy.
224        if (swapA.swapCompletedTime - swapB.swapCompletedTime > frameInterval * 3) {
225            return false;
226        }
227
228        // Was there a happy queue & dequeue time? If so, don't
229        // consider it stuffed
230        if (swapB.dequeueDuration < SLOW_THRESHOLD
231                && swapB.queueDuration < SLOW_THRESHOLD) {
232            return false;
233        }
234
235        swapA = swapB;
236    }
237
238    // All signs point to a stuffed swap chain
239    ATRACE_NAME("swap chain stuffed");
240    return true;
241}
242
243void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo,
244        int64_t syncQueued, RenderNode* target) {
245    mRenderThread.removeFrameCallback(this);
246
247    // If the previous frame was dropped we don't need to hold onto it, so
248    // just keep using the previous frame's structure instead
249    if (!wasSkipped(mCurrentFrameInfo)) {
250        mCurrentFrameInfo = &mFrames.next();
251    }
252    mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo);
253    mCurrentFrameInfo->set(FrameInfoIndex::SyncQueued) = syncQueued;
254    mCurrentFrameInfo->markSyncStart();
255
256    info.damageAccumulator = &mDamageAccumulator;
257#if HWUI_NEW_OPS
258    info.layerUpdateQueue = &mLayerUpdateQueue;
259#else
260    info.renderer = mCanvas;
261#endif
262
263    mAnimationContext->startFrame(info.mode);
264    for (const sp<RenderNode>& node : mRenderNodes) {
265        // Only the primary target node will be drawn full - all other nodes would get drawn in
266        // real time mode. In case of a window, the primary node is the window content and the other
267        // node(s) are non client / filler nodes.
268        info.mode = (node.get() == target ? TreeInfo::MODE_FULL : TreeInfo::MODE_RT_ONLY);
269        node->prepareTree(info);
270        GL_CHECKPOINT(MODERATE);
271    }
272    mAnimationContext->runRemainingAnimations(info);
273    GL_CHECKPOINT(MODERATE);
274
275    freePrefetchedLayers(info.observer);
276    GL_CHECKPOINT(MODERATE);
277
278    mIsDirty = true;
279
280    if (CC_UNLIKELY(!mNativeSurface.get())) {
281        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
282        info.out.canDrawThisFrame = false;
283        return;
284    }
285
286    if (CC_LIKELY(mSwapHistory.size())) {
287        nsecs_t latestVsync = mRenderThread.timeLord().latestVsync();
288        SwapHistory& lastSwap = mSwapHistory.back();
289        int durationUs;
290        mNativeSurface->query(NATIVE_WINDOW_LAST_DEQUEUE_DURATION, &durationUs);
291        lastSwap.dequeueDuration = us2ns(durationUs);
292        mNativeSurface->query(NATIVE_WINDOW_LAST_QUEUE_DURATION, &durationUs);
293        lastSwap.queueDuration = us2ns(durationUs);
294        nsecs_t vsyncDelta = std::abs(lastSwap.vsyncTime - latestVsync);
295        // The slight fudge-factor is to deal with cases where
296        // the vsync was estimated due to being slow handling the signal.
297        // See the logic in TimeLord#computeFrameTimeNanos or in
298        // Choreographer.java for details on when this happens
299        if (vsyncDelta < 2_ms) {
300            // Already drew for this vsync pulse, UI draw request missed
301            // the deadline for RT animations
302            info.out.canDrawThisFrame = false;
303        } else if (vsyncDelta >= mRenderThread.timeLord().frameIntervalNanos() * 3
304                || (latestVsync - mLastDropVsync) < 500_ms) {
305            // It's been several frame intervals, assume the buffer queue is fine
306            // or the last drop was too recent
307            info.out.canDrawThisFrame = true;
308        } else {
309            info.out.canDrawThisFrame = !isSwapChainStuffed();
310            if (!info.out.canDrawThisFrame) {
311                // dropping frame
312                mLastDropVsync = mRenderThread.timeLord().latestVsync();
313            }
314        }
315    } else {
316        info.out.canDrawThisFrame = true;
317    }
318
319    if (!info.out.canDrawThisFrame) {
320        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
321    }
322
323    if (info.out.hasAnimations || !info.out.canDrawThisFrame) {
324        if (!info.out.requiresUiRedraw) {
325            // If animationsNeedsRedraw is set don't bother posting for an RT anim
326            // as we will just end up fighting the UI thread.
327            mRenderThread.postFrameCallback(this);
328        }
329    }
330}
331
332void CanvasContext::stopDrawing() {
333    mRenderThread.removeFrameCallback(this);
334    mAnimationContext->detachAnimators();
335}
336
337void CanvasContext::notifyFramePending() {
338    ATRACE_CALL();
339    mRenderThread.pushBackFrameCallback(this);
340}
341
342void CanvasContext::draw() {
343#if !HWUI_NEW_OPS
344    LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE,
345            "drawRenderNode called on a context with no canvas or surface!");
346#endif
347
348    SkRect dirty;
349    mDamageAccumulator.finish(&dirty);
350
351    // TODO: Re-enable after figuring out cause of b/22592975
352//    if (dirty.isEmpty() && Properties::skipEmptyFrames) {
353//        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
354//        return;
355//    }
356
357    mCurrentFrameInfo->markIssueDrawCommandsStart();
358
359    Frame frame = mEglManager.beginFrame(mEglSurface);
360
361    if (frame.width() != mLastFrameWidth || frame.height() != mLastFrameHeight) {
362        // can't rely on prior content of window if viewport size changes
363        dirty.setEmpty();
364        mLastFrameWidth = frame.width();
365        mLastFrameHeight = frame.height();
366    } else if (mHaveNewSurface || frame.bufferAge() == 0) {
367        // New surface needs a full draw
368        dirty.setEmpty();
369    } else {
370        if (!dirty.isEmpty() && !dirty.intersect(0, 0, frame.width(), frame.height())) {
371            ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?",
372                    SK_RECT_ARGS(dirty), frame.width(), frame.height());
373            dirty.setEmpty();
374        }
375        profiler().unionDirty(&dirty);
376    }
377
378    if (dirty.isEmpty()) {
379        dirty.set(0, 0, frame.width(), frame.height());
380    }
381
382    // At this point dirty is the area of the screen to update. However,
383    // the area of the frame we need to repaint is potentially different, so
384    // stash the screen area for later
385    SkRect screenDirty(dirty);
386
387    // If the buffer age is 0 we do a full-screen repaint (handled above)
388    // If the buffer age is 1 the buffer contents are the same as they were
389    // last frame so there's nothing to union() against
390    // Therefore we only care about the > 1 case.
391    if (frame.bufferAge() > 1) {
392        if (frame.bufferAge() > (int) mSwapHistory.size()) {
393            // We don't have enough history to handle this old of a buffer
394            // Just do a full-draw
395            dirty.set(0, 0, frame.width(), frame.height());
396        } else {
397            // At this point we haven't yet added the latest frame
398            // to the damage history (happens below)
399            // So we need to damage
400            for (int i = mSwapHistory.size() - 1;
401                    i > ((int) mSwapHistory.size()) - frame.bufferAge(); i--) {
402                dirty.join(mSwapHistory[i].damage);
403            }
404        }
405    }
406
407    mEglManager.damageFrame(frame, dirty);
408
409#if HWUI_NEW_OPS
410    auto& caches = Caches::getInstance();
411    FrameBuilder frameBuilder(dirty, frame.width(), frame.height(), mLightGeometry, caches);
412
413    frameBuilder.deferLayers(mLayerUpdateQueue);
414    mLayerUpdateQueue.clear();
415
416    frameBuilder.deferRenderNodeScene(mRenderNodes, mContentDrawBounds);
417
418    BakedOpRenderer renderer(caches, mRenderThread.renderState(),
419            mOpaque, mLightInfo);
420    frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer);
421    profiler().draw(&renderer);
422    bool drew = renderer.didDraw();
423
424    // post frame cleanup
425    caches.clearGarbage();
426    caches.pathCache.trim();
427    caches.tessellationCache.trim();
428
429#if DEBUG_MEMORY_USAGE
430    mCaches.dumpMemoryUsage();
431#else
432    if (CC_UNLIKELY(Properties::debugLevel & kDebugMemory)) {
433        caches.dumpMemoryUsage();
434    }
435#endif
436
437#else
438    mCanvas->prepareDirty(frame.width(), frame.height(),
439            dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom, mOpaque);
440
441    Rect outBounds;
442    // It there are multiple render nodes, they are laid out as follows:
443    // #0 - backdrop (content + caption)
444    // #1 - content (positioned at (0,0) and clipped to - its bounds mContentDrawBounds)
445    // #2 - additional overlay nodes
446    // Usually the backdrop cannot be seen since it will be entirely covered by the content. While
447    // resizing however it might become partially visible. The following render loop will crop the
448    // backdrop against the content and draw the remaining part of it. It will then draw the content
449    // cropped to the backdrop (since that indicates a shrinking of the window).
450    //
451    // Additional nodes will be drawn on top with no particular clipping semantics.
452
453    // The bounds of the backdrop against which the content should be clipped.
454    Rect backdropBounds = mContentDrawBounds;
455    // Usually the contents bounds should be mContentDrawBounds - however - we will
456    // move it towards the fixed edge to give it a more stable appearance (for the moment).
457    Rect contentBounds;
458    // If there is no content bounds we ignore the layering as stated above and start with 2.
459    int layer = (mContentDrawBounds.isEmpty() || mRenderNodes.size() == 1) ? 2 : 0;
460    // Draw all render nodes. Note that
461    for (const sp<RenderNode>& node : mRenderNodes) {
462        if (layer == 0) { // Backdrop.
463            // Draw the backdrop clipped to the inverse content bounds, but assume that the content
464            // was moved to the upper left corner.
465            const RenderProperties& properties = node->properties();
466            Rect targetBounds(properties.getLeft(), properties.getTop(),
467                              properties.getRight(), properties.getBottom());
468            // Move the content bounds towards the fixed corner of the backdrop.
469            const int x = targetBounds.left;
470            const int y = targetBounds.top;
471            contentBounds.set(x, y, x + mContentDrawBounds.getWidth(),
472                                    y + mContentDrawBounds.getHeight());
473            // Remember the intersection of the target bounds and the intersection bounds against
474            // which we have to crop the content.
475            backdropBounds.set(x, y, x + backdropBounds.getWidth(), y + backdropBounds.getHeight());
476            backdropBounds.doIntersect(targetBounds);
477            // Check if we have to draw something on the left side ...
478            if (targetBounds.left < contentBounds.left) {
479                mCanvas->save(SaveFlags::Clip);
480                if (mCanvas->clipRect(targetBounds.left, targetBounds.top,
481                                      contentBounds.left, targetBounds.bottom,
482                                      SkRegion::kIntersect_Op)) {
483                    mCanvas->drawRenderNode(node.get(), outBounds);
484                }
485                // Reduce the target area by the area we have just painted.
486                targetBounds.left = std::min(contentBounds.left, targetBounds.right);
487                mCanvas->restore();
488            }
489            // ... or on the right side ...
490            if (targetBounds.right > contentBounds.right &&
491                !targetBounds.isEmpty()) {
492                mCanvas->save(SaveFlags::Clip);
493                if (mCanvas->clipRect(contentBounds.right, targetBounds.top,
494                                      targetBounds.right, targetBounds.bottom,
495                                      SkRegion::kIntersect_Op)) {
496                    mCanvas->drawRenderNode(node.get(), outBounds);
497                }
498                // Reduce the target area by the area we have just painted.
499                targetBounds.right = std::max(targetBounds.left, contentBounds.right);
500                mCanvas->restore();
501            }
502            // ... or at the top ...
503            if (targetBounds.top < contentBounds.top &&
504                !targetBounds.isEmpty()) {
505                mCanvas->save(SaveFlags::Clip);
506                if (mCanvas->clipRect(targetBounds.left, targetBounds.top, targetBounds.right,
507                                      contentBounds.top,
508                                      SkRegion::kIntersect_Op)) {
509                    mCanvas->drawRenderNode(node.get(), outBounds);
510                }
511                // Reduce the target area by the area we have just painted.
512                targetBounds.top = std::min(contentBounds.top, targetBounds.bottom);
513                mCanvas->restore();
514            }
515            // ... or at the bottom.
516            if (targetBounds.bottom > contentBounds.bottom &&
517                !targetBounds.isEmpty()) {
518                mCanvas->save(SaveFlags::Clip);
519                if (mCanvas->clipRect(targetBounds.left, contentBounds.bottom, targetBounds.right,
520                                      targetBounds.bottom, SkRegion::kIntersect_Op)) {
521                    mCanvas->drawRenderNode(node.get(), outBounds);
522                }
523                mCanvas->restore();
524            }
525        } else if (layer == 1) { // Content
526            // It gets cropped against the bounds of the backdrop to stay inside.
527            mCanvas->save(SaveFlags::MatrixClip);
528
529            // We shift and clip the content to match its final location in the window.
530            const float left = mContentDrawBounds.left;
531            const float top = mContentDrawBounds.top;
532            const float dx = backdropBounds.left - left;
533            const float dy = backdropBounds.top - top;
534            const float width = backdropBounds.getWidth();
535            const float height = backdropBounds.getHeight();
536
537            mCanvas->translate(dx, dy);
538            if (mCanvas->clipRect(left, top, left + width, top + height, SkRegion::kIntersect_Op)) {
539                mCanvas->drawRenderNode(node.get(), outBounds);
540            }
541            mCanvas->restore();
542        } else { // draw the rest on top at will!
543            mCanvas->drawRenderNode(node.get(), outBounds);
544        }
545        layer++;
546    }
547
548    profiler().draw(mCanvas);
549
550    bool drew = mCanvas->finish();
551#endif
552
553    waitOnFences();
554
555    GL_CHECKPOINT(LOW);
556
557    // Even if we decided to cancel the frame, from the perspective of jank
558    // metrics the frame was swapped at this point
559    mCurrentFrameInfo->markSwapBuffers();
560    mIsDirty = false;
561
562    if (drew || mEglManager.damageRequiresSwap()) {
563        if (CC_UNLIKELY(!mEglManager.swapBuffers(frame, screenDirty))) {
564            setSurface(nullptr);
565        }
566        SwapHistory& swap = mSwapHistory.next();
567        swap.damage = screenDirty;
568        swap.swapCompletedTime = systemTime(CLOCK_MONOTONIC);
569        swap.vsyncTime = mRenderThread.timeLord().latestVsync();
570        mHaveNewSurface = false;
571        mFrameNumber = -1;
572    }
573
574    // TODO: Use a fence for real completion?
575    mCurrentFrameInfo->markFrameCompleted();
576
577#if LOG_FRAMETIME_MMA
578    float thisFrame = mCurrentFrameInfo->duration(
579            FrameInfoIndex::IssueDrawCommandsStart,
580            FrameInfoIndex::FrameCompleted) / NANOS_PER_MILLIS_F;
581    if (sFrameCount) {
582        sBenchMma = ((9 * sBenchMma) + thisFrame) / 10;
583    } else {
584        sBenchMma = thisFrame;
585    }
586    if (++sFrameCount == 10) {
587        sFrameCount = 1;
588        ALOGD("Average frame time: %.4f", sBenchMma);
589    }
590#endif
591
592    mJankTracker.addFrame(*mCurrentFrameInfo);
593    mRenderThread.jankTracker().addFrame(*mCurrentFrameInfo);
594    if (CC_UNLIKELY(mFrameMetricsReporter.get() != nullptr)) {
595        mFrameMetricsReporter->reportFrameMetrics(mCurrentFrameInfo->data());
596    }
597
598    GpuMemoryTracker::onFrameCompleted();
599}
600
601// Called by choreographer to do an RT-driven animation
602void CanvasContext::doFrame() {
603#if HWUI_NEW_OPS
604    if (CC_UNLIKELY(mEglSurface == EGL_NO_SURFACE)) return;
605#else
606    if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) return;
607#endif
608    prepareAndDraw(nullptr);
609}
610
611void CanvasContext::prepareAndDraw(RenderNode* node) {
612    ATRACE_CALL();
613
614    nsecs_t vsync = mRenderThread.timeLord().computeFrameTimeNanos();
615    int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE];
616    UiFrameInfoBuilder(frameInfo)
617        .addFlag(FrameInfoFlags::RTAnimation)
618        .setVsync(vsync, vsync);
619
620    TreeInfo info(TreeInfo::MODE_RT_ONLY, *this);
621    prepareTree(info, frameInfo, systemTime(CLOCK_MONOTONIC), node);
622    if (info.out.canDrawThisFrame) {
623        draw();
624    }
625}
626
627void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) {
628    ATRACE_CALL();
629    DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
630    if (thread.eglManager().hasEglContext()) {
631        mode = DrawGlInfo::kModeProcess;
632    }
633
634    thread.renderState().invokeFunctor(functor, mode, nullptr);
635}
636
637void CanvasContext::markLayerInUse(RenderNode* node) {
638    if (mPrefetchedLayers.erase(node)) {
639        node->decStrong(nullptr);
640    }
641}
642
643void CanvasContext::freePrefetchedLayers(TreeObserver* observer) {
644    if (mPrefetchedLayers.size()) {
645        for (auto& node : mPrefetchedLayers) {
646            ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...",
647                    node->getName());
648            node->destroyHardwareResources(observer);
649            node->decStrong(observer);
650        }
651        mPrefetchedLayers.clear();
652    }
653}
654
655void CanvasContext::buildLayer(RenderNode* node, TreeObserver* observer) {
656    ATRACE_CALL();
657    if (!mEglManager.hasEglContext()) return;
658#if !HWUI_NEW_OPS
659    if (!mCanvas) return;
660#endif
661
662    // buildLayer() will leave the tree in an unknown state, so we must stop drawing
663    stopDrawing();
664
665    TreeInfo info(TreeInfo::MODE_FULL, *this);
666    info.damageAccumulator = &mDamageAccumulator;
667    info.observer = observer;
668#if HWUI_NEW_OPS
669    info.layerUpdateQueue = &mLayerUpdateQueue;
670#else
671    info.renderer = mCanvas;
672#endif
673    info.runAnimations = false;
674    node->prepareTree(info);
675    SkRect ignore;
676    mDamageAccumulator.finish(&ignore);
677    // Tickle the GENERIC property on node to mark it as dirty for damaging
678    // purposes when the frame is actually drawn
679    node->setPropertyFieldsDirty(RenderNode::GENERIC);
680
681#if HWUI_NEW_OPS
682    static const std::vector< sp<RenderNode> > emptyNodeList;
683    auto& caches = Caches::getInstance();
684    FrameBuilder frameBuilder(mLayerUpdateQueue, mLightGeometry, caches);
685    mLayerUpdateQueue.clear();
686    BakedOpRenderer renderer(caches, mRenderThread.renderState(),
687            mOpaque, mLightInfo);
688    LOG_ALWAYS_FATAL_IF(renderer.didDraw(), "shouldn't draw in buildlayer case");
689    frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer);
690#else
691    mCanvas->markLayersAsBuildLayers();
692    mCanvas->flushLayerUpdates();
693#endif
694
695    node->incStrong(nullptr);
696    mPrefetchedLayers.insert(node);
697}
698
699bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) {
700    layer->apply();
701    return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap);
702}
703
704void CanvasContext::destroyHardwareResources(TreeObserver* observer) {
705    stopDrawing();
706    if (mEglManager.hasEglContext()) {
707        freePrefetchedLayers(observer);
708        for (const sp<RenderNode>& node : mRenderNodes) {
709            node->destroyHardwareResources(observer);
710        }
711        Caches& caches = Caches::getInstance();
712        // Make sure to release all the textures we were owning as there won't
713        // be another draw
714        caches.textureCache.resetMarkInUse(this);
715        mRenderThread.renderState().flush(Caches::FlushMode::Layers);
716    }
717}
718
719void CanvasContext::trimMemory(RenderThread& thread, int level) {
720    // No context means nothing to free
721    if (!thread.eglManager().hasEglContext()) return;
722
723    ATRACE_CALL();
724    if (level >= TRIM_MEMORY_COMPLETE) {
725        thread.renderState().flush(Caches::FlushMode::Full);
726        thread.eglManager().destroy();
727    } else if (level >= TRIM_MEMORY_UI_HIDDEN) {
728        thread.renderState().flush(Caches::FlushMode::Moderate);
729    }
730}
731
732void CanvasContext::runWithGlContext(RenderTask* task) {
733    LOG_ALWAYS_FATAL_IF(!mEglManager.hasEglContext(),
734            "GL context not initialized!");
735    task->run();
736}
737
738Layer* CanvasContext::createTextureLayer() {
739    mEglManager.initialize();
740    return LayerRenderer::createTextureLayer(mRenderThread.renderState());
741}
742
743void CanvasContext::setTextureAtlas(RenderThread& thread,
744        const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) {
745    thread.eglManager().setTextureAtlas(buffer, map, mapSize);
746}
747
748void CanvasContext::dumpFrames(int fd) {
749    FILE* file = fdopen(fd, "a");
750    fprintf(file, "\n\n---PROFILEDATA---\n");
751    for (size_t i = 0; i < static_cast<size_t>(FrameInfoIndex::NumIndexes); i++) {
752        fprintf(file, "%s", FrameInfoNames[i].c_str());
753        fprintf(file, ",");
754    }
755    for (size_t i = 0; i < mFrames.size(); i++) {
756        FrameInfo& frame = mFrames[i];
757        if (frame[FrameInfoIndex::SyncStart] == 0) {
758            continue;
759        }
760        fprintf(file, "\n");
761        for (int i = 0; i < static_cast<int>(FrameInfoIndex::NumIndexes); i++) {
762            fprintf(file, "%" PRId64 ",", frame[i]);
763        }
764    }
765    fprintf(file, "\n---PROFILEDATA---\n\n");
766    fflush(file);
767}
768
769void CanvasContext::resetFrameStats() {
770    mFrames.clear();
771    mRenderThread.jankTracker().reset();
772}
773
774void CanvasContext::serializeDisplayListTree() {
775#if ENABLE_RENDERNODE_SERIALIZATION
776    using namespace google::protobuf::io;
777    char package[128];
778    // Check whether tracing is enabled for this process.
779    FILE * file = fopen("/proc/self/cmdline", "r");
780    if (file) {
781        if (!fgets(package, 128, file)) {
782            ALOGE("Error reading cmdline: %s (%d)", strerror(errno), errno);
783            fclose(file);
784            return;
785        }
786        fclose(file);
787    } else {
788        ALOGE("Error opening /proc/self/cmdline: %s (%d)", strerror(errno),
789                errno);
790        return;
791    }
792    char path[1024];
793    snprintf(path, 1024, "/data/data/%s/cache/rendertree_dump", package);
794    int fd = open(path, O_CREAT | O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH);
795    if (fd == -1) {
796        ALOGD("Failed to open '%s'", path);
797        return;
798    }
799    proto::RenderNode tree;
800    // TODO: Streaming writes?
801    mRootRenderNode->copyTo(&tree);
802    std::string data = tree.SerializeAsString();
803    write(fd, data.c_str(), data.length());
804    close(fd);
805#endif
806}
807
808void CanvasContext::waitOnFences() {
809    if (mFrameFences.size()) {
810        ATRACE_CALL();
811        for (auto& fence : mFrameFences) {
812            fence->getResult();
813        }
814        mFrameFences.clear();
815    }
816}
817
818class CanvasContext::FuncTaskProcessor : public TaskProcessor<bool> {
819public:
820    FuncTaskProcessor(Caches& caches)
821            : TaskProcessor<bool>(&caches.tasks) {}
822
823    virtual void onProcess(const sp<Task<bool> >& task) override {
824        FuncTask* t = static_cast<FuncTask*>(task.get());
825        t->func();
826        task->setResult(true);
827    }
828};
829
830void CanvasContext::enqueueFrameWork(std::function<void()>&& func) {
831    if (!mFrameWorkProcessor.get()) {
832        mFrameWorkProcessor = new FuncTaskProcessor(Caches::getInstance());
833    }
834    sp<FuncTask> task(new FuncTask());
835    task->func = func;
836    mFrameFences.push_back(task);
837    mFrameWorkProcessor->add(task);
838}
839
840int64_t CanvasContext::getFrameNumber() {
841    // mFrameNumber is reset to -1 when the surface changes or we swap buffers
842    if (mFrameNumber == -1 && mNativeSurface.get()) {
843        mFrameNumber = static_cast<int64_t>(mNativeSurface->getNextFrameNumber());
844    }
845    return mFrameNumber;
846}
847
848} /* namespace renderthread */
849} /* namespace uirenderer */
850} /* namespace android */
851