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