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