CanvasContext.cpp revision 98787e6c9b2c10b1ab7820bdac168686025b924a
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "CanvasContext.h"
18
19#include "AnimationContext.h"
20#include "Caches.h"
21#include "DeferredLayerUpdater.h"
22#include "EglManager.h"
23#include "LayerUpdateQueue.h"
24#include "LayerRenderer.h"
25#include "OpenGLRenderer.h"
26#include "Properties.h"
27#include "RenderThread.h"
28#include "renderstate/RenderState.h"
29#include "renderstate/Stencil.h"
30#include "protos/hwui.pb.h"
31#include "utils/TimeUtils.h"
32
33#if HWUI_NEW_OPS
34#include "OpReorderer.h"
35#endif
36
37#include <cutils/properties.h>
38#include <google/protobuf/io/zero_copy_stream_impl.h>
39#include <private/hwui/DrawGlInfo.h>
40#include <strings.h>
41
42#include <algorithm>
43#include <fcntl.h>
44#include <sys/stat.h>
45
46#include <cstdlib>
47
48#define TRIM_MEMORY_COMPLETE 80
49#define TRIM_MEMORY_UI_HIDDEN 20
50
51#define ENABLE_RENDERNODE_SERIALIZATION false
52
53#define LOG_FRAMETIME_MMA 0
54
55#if LOG_FRAMETIME_MMA
56static float sBenchMma = 0;
57static int sFrameCount = 0;
58static const float NANOS_PER_MILLIS_F = 1000000.0f;
59#endif
60
61namespace android {
62namespace uirenderer {
63namespace renderthread {
64
65CanvasContext::CanvasContext(RenderThread& thread, bool translucent,
66        RenderNode* rootRenderNode, IContextFactory* contextFactory)
67        : mRenderThread(thread)
68        , mEglManager(thread.eglManager())
69        , mOpaque(!translucent)
70        , mAnimationContext(contextFactory->createAnimationContext(mRenderThread.timeLord()))
71        , mJankTracker(thread.timeLord().frameIntervalNanos())
72        , mProfiler(mFrames)
73        , mContentDrawBounds(0, 0, 0, 0) {
74    mRenderNodes.emplace_back(rootRenderNode);
75    mRenderThread.renderState().registerCanvasContext(this);
76    mProfiler.setDensity(mRenderThread.mainDisplayInfo().density);
77}
78
79CanvasContext::~CanvasContext() {
80    destroy();
81    mRenderThread.renderState().unregisterCanvasContext(this);
82}
83
84void CanvasContext::destroy() {
85    stopDrawing();
86    setSurface(nullptr);
87    freePrefetechedLayers();
88    destroyHardwareResources();
89    mAnimationContext->destroy();
90    if (mCanvas) {
91        delete mCanvas;
92        mCanvas = nullptr;
93    }
94}
95
96void CanvasContext::setSurface(ANativeWindow* window) {
97    ATRACE_CALL();
98
99    mNativeWindow = window;
100
101    if (mEglSurface != EGL_NO_SURFACE) {
102        mEglManager.destroySurface(mEglSurface);
103        mEglSurface = EGL_NO_SURFACE;
104    }
105
106    if (window) {
107        mEglSurface = mEglManager.createSurface(window);
108    }
109
110    if (mEglSurface != EGL_NO_SURFACE) {
111        const bool preserveBuffer = (mSwapBehavior != kSwap_discardBuffer);
112        mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer);
113        mHaveNewSurface = true;
114        mSwapHistory.clear();
115        makeCurrent();
116    } else {
117        mRenderThread.removeFrameCallback(this);
118    }
119}
120
121void CanvasContext::requireSurface() {
122    LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE,
123            "requireSurface() called but no surface set!");
124    makeCurrent();
125}
126
127void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) {
128    mSwapBehavior = swapBehavior;
129}
130
131bool CanvasContext::initialize(ANativeWindow* window) {
132    setSurface(window);
133#if !HWUI_NEW_OPS
134    if (mCanvas) return false;
135    mCanvas = new OpenGLRenderer(mRenderThread.renderState());
136    mCanvas->initProperties();
137#endif
138    return true;
139}
140
141void CanvasContext::updateSurface(ANativeWindow* window) {
142    setSurface(window);
143}
144
145bool CanvasContext::pauseSurface(ANativeWindow* window) {
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    mLightInfo.lightRadius = 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    mLightCenter = 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
185void CanvasContext::processLayerUpdate(DeferredLayerUpdater* layerUpdater) {
186#if !HWUI_NEW_OPS
187    bool success = layerUpdater->apply();
188    LOG_ALWAYS_FATAL_IF(!success, "Failed to update layer!");
189    if (layerUpdater->backingLayer()->deferredUpdateScheduled) {
190        mCanvas->pushLayerUpdate(layerUpdater->backingLayer());
191    }
192#endif
193}
194
195static bool wasSkipped(FrameInfo* info) {
196    return info && ((*info)[FrameInfoIndex::Flags] & FrameInfoFlags::SkippedFrame);
197}
198
199void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo,
200        int64_t syncQueued, RenderNode* target) {
201    mRenderThread.removeFrameCallback(this);
202
203    // If the previous frame was dropped we don't need to hold onto it, so
204    // just keep using the previous frame's structure instead
205    if (!wasSkipped(mCurrentFrameInfo)) {
206        mCurrentFrameInfo = &mFrames.next();
207    }
208    mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo);
209    mCurrentFrameInfo->set(FrameInfoIndex::SyncQueued) = syncQueued;
210    mCurrentFrameInfo->markSyncStart();
211
212    info.damageAccumulator = &mDamageAccumulator;
213#if HWUI_NEW_OPS
214    info.layerUpdateQueue = &mLayerUpdateQueue;
215#else
216    info.renderer = mCanvas;
217#endif
218
219    mAnimationContext->startFrame(info.mode);
220    for (const sp<RenderNode>& node : mRenderNodes) {
221        // Only the primary target node will be drawn full - all other nodes would get drawn in
222        // real time mode. In case of a window, the primary node is the window content and the other
223        // node(s) are non client / filler nodes.
224        info.mode = (node.get() == target ? TreeInfo::MODE_FULL : TreeInfo::MODE_RT_ONLY);
225        node->prepareTree(info);
226    }
227    mAnimationContext->runRemainingAnimations(info);
228
229    freePrefetechedLayers();
230
231    if (CC_UNLIKELY(!mNativeWindow.get())) {
232        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
233        info.out.canDrawThisFrame = false;
234        return;
235    }
236
237    if (CC_LIKELY(mSwapHistory.size())) {
238        nsecs_t latestVsync = mRenderThread.timeLord().latestVsync();
239        const SwapHistory& lastSwap = mSwapHistory.back();
240        int vsyncDelta = std::abs(lastSwap.vsyncTime - latestVsync);
241        // The slight fudge-factor is to deal with cases where
242        // the vsync was estimated due to being slow handling the signal.
243        // See the logic in TimeLord#computeFrameTimeNanos or in
244        // Choreographer.java for details on when this happens
245        if (vsyncDelta < 2_ms) {
246            // Already drew for this vsync pulse, UI draw request missed
247            // the deadline for RT animations
248            info.out.canDrawThisFrame = false;
249        } else if (lastSwap.swapTime < latestVsync) {
250            info.out.canDrawThisFrame = true;
251        } else {
252            // We're maybe behind? Find out for sure
253            int runningBehind = 0;
254            mNativeWindow->query(mNativeWindow.get(),
255                    NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &runningBehind);
256            info.out.canDrawThisFrame = !runningBehind;
257        }
258    } else {
259        info.out.canDrawThisFrame = true;
260    }
261
262    if (!info.out.canDrawThisFrame) {
263        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
264    }
265
266    if (info.out.hasAnimations || !info.out.canDrawThisFrame) {
267        if (!info.out.requiresUiRedraw) {
268            // If animationsNeedsRedraw is set don't bother posting for an RT anim
269            // as we will just end up fighting the UI thread.
270            mRenderThread.postFrameCallback(this);
271        }
272    }
273}
274
275void CanvasContext::stopDrawing() {
276    mRenderThread.removeFrameCallback(this);
277}
278
279void CanvasContext::notifyFramePending() {
280    ATRACE_CALL();
281    mRenderThread.pushBackFrameCallback(this);
282}
283
284void CanvasContext::draw() {
285#if !HWUI_NEW_OPS
286    LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE,
287            "drawRenderNode called on a context with no canvas or surface!");
288#endif
289
290    SkRect dirty;
291    mDamageAccumulator.finish(&dirty);
292
293    // TODO: Re-enable after figuring out cause of b/22592975
294//    if (dirty.isEmpty() && Properties::skipEmptyFrames) {
295//        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
296//        return;
297//    }
298
299    mCurrentFrameInfo->markIssueDrawCommandsStart();
300
301    Frame frame = mEglManager.beginFrame(mEglSurface);
302
303    if (frame.width() != mLastFrameWidth || frame.height() != mLastFrameHeight) {
304        // can't rely on prior content of window if viewport size changes
305        dirty.setEmpty();
306        mLastFrameWidth = frame.width();
307        mLastFrameHeight = frame.height();
308    } else if (mHaveNewSurface || frame.bufferAge() == 0) {
309        // New surface needs a full draw
310        dirty.setEmpty();
311    } else {
312        if (!dirty.isEmpty() && !dirty.intersect(0, 0, frame.width(), frame.height())) {
313            ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?",
314                    SK_RECT_ARGS(dirty), frame.width(), frame.height());
315            dirty.setEmpty();
316        }
317        profiler().unionDirty(&dirty);
318    }
319
320    if (dirty.isEmpty()) {
321        dirty.set(0, 0, frame.width(), frame.height());
322    }
323
324    // At this point dirty is the area of the screen to update. However,
325    // the area of the frame we need to repaint is potentially different, so
326    // stash the screen area for later
327    SkRect screenDirty(dirty);
328
329    // If the buffer age is 0 we do a full-screen repaint (handled above)
330    // If the buffer age is 1 the buffer contents are the same as they were
331    // last frame so there's nothing to union() against
332    // Therefore we only care about the > 1 case.
333    if (frame.bufferAge() > 1) {
334        if (frame.bufferAge() > (int) mSwapHistory.size()) {
335            // We don't have enough history to handle this old of a buffer
336            // Just do a full-draw
337            dirty.set(0, 0, frame.width(), frame.height());
338        } else {
339            // At this point we haven't yet added the latest frame
340            // to the damage history (happens below)
341            // So we need to damage
342            for (int i = mSwapHistory.size() - 1;
343                    i > ((int) mSwapHistory.size()) - frame.bufferAge(); i--) {
344                dirty.join(mSwapHistory[i].damage);
345            }
346        }
347    }
348
349    mEglManager.damageFrame(frame, dirty);
350
351#if HWUI_NEW_OPS
352    OpReorderer reorderer(mLayerUpdateQueue, dirty, frame.width(), frame.height(),
353            mRenderNodes, mLightCenter);
354    mLayerUpdateQueue.clear();
355    BakedOpRenderer renderer(Caches::getInstance(), mRenderThread.renderState(),
356            mOpaque, mLightInfo);
357    // TODO: profiler().draw(mCanvas);
358    reorderer.replayBakedOps<BakedOpDispatcher>(renderer);
359
360    bool drew = renderer.didDraw();
361
362#else
363    mCanvas->prepareDirty(frame.width(), frame.height(),
364            dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom, mOpaque);
365
366    Rect outBounds;
367    // It there are multiple render nodes, they are laid out as follows:
368    // #0 - backdrop (content + caption)
369    // #1 - content (positioned at (0,0) and clipped to - its bounds mContentDrawBounds)
370    // #2 - additional overlay nodes
371    // Usually the backdrop cannot be seen since it will be entirely covered by the content. While
372    // resizing however it might become partially visible. The following render loop will crop the
373    // backdrop against the content and draw the remaining part of it. It will then draw the content
374    // cropped to the backdrop (since that indicates a shrinking of the window).
375    //
376    // Additional nodes will be drawn on top with no particular clipping semantics.
377
378    // The bounds of the backdrop against which the content should be clipped.
379    Rect backdropBounds = mContentDrawBounds;
380    // Usually the contents bounds should be mContentDrawBounds - however - we will
381    // move it towards the fixed edge to give it a more stable appearance (for the moment).
382    Rect contentBounds;
383    // If there is no content bounds we ignore the layering as stated above and start with 2.
384    int layer = (mContentDrawBounds.isEmpty() || mRenderNodes.size() == 1) ? 2 : 0;
385    // Draw all render nodes. Note that
386    for (const sp<RenderNode>& node : mRenderNodes) {
387        if (layer == 0) { // Backdrop.
388            // Draw the backdrop clipped to the inverse content bounds, but assume that the content
389            // was moved to the upper left corner.
390            const RenderProperties& properties = node->properties();
391            Rect targetBounds(properties.getLeft(), properties.getTop(),
392                              properties.getRight(), properties.getBottom());
393            // Move the content bounds towards the fixed corner of the backdrop.
394            const int x = targetBounds.left;
395            const int y = targetBounds.top;
396            contentBounds.set(x, y, x + mContentDrawBounds.getWidth(),
397                                    y + mContentDrawBounds.getHeight());
398            // Remember the intersection of the target bounds and the intersection bounds against
399            // which we have to crop the content.
400            backdropBounds.set(x, y, x + backdropBounds.getWidth(), y + backdropBounds.getHeight());
401            backdropBounds.doIntersect(targetBounds);
402            // Check if we have to draw something on the left side ...
403            if (targetBounds.left < contentBounds.left) {
404                mCanvas->save(SkCanvas::kClip_SaveFlag);
405                if (mCanvas->clipRect(targetBounds.left, targetBounds.top,
406                                      contentBounds.left, targetBounds.bottom,
407                                      SkRegion::kIntersect_Op)) {
408                    mCanvas->drawRenderNode(node.get(), outBounds);
409                }
410                // Reduce the target area by the area we have just painted.
411                targetBounds.left = std::min(contentBounds.left, targetBounds.right);
412                mCanvas->restore();
413            }
414            // ... or on the right side ...
415            if (targetBounds.right > contentBounds.right &&
416                !targetBounds.isEmpty()) {
417                mCanvas->save(SkCanvas::kClip_SaveFlag);
418                if (mCanvas->clipRect(contentBounds.right, targetBounds.top,
419                                      targetBounds.right, targetBounds.bottom,
420                                      SkRegion::kIntersect_Op)) {
421                    mCanvas->drawRenderNode(node.get(), outBounds);
422                }
423                // Reduce the target area by the area we have just painted.
424                targetBounds.right = std::max(targetBounds.left, contentBounds.right);
425                mCanvas->restore();
426            }
427            // ... or at the top ...
428            if (targetBounds.top < contentBounds.top &&
429                !targetBounds.isEmpty()) {
430                mCanvas->save(SkCanvas::kClip_SaveFlag);
431                if (mCanvas->clipRect(targetBounds.left, targetBounds.top, targetBounds.right,
432                                      contentBounds.top,
433                                      SkRegion::kIntersect_Op)) {
434                    mCanvas->drawRenderNode(node.get(), outBounds);
435                }
436                // Reduce the target area by the area we have just painted.
437                targetBounds.top = std::min(contentBounds.top, targetBounds.bottom);
438                mCanvas->restore();
439            }
440            // ... or at the bottom.
441            if (targetBounds.bottom > contentBounds.bottom &&
442                !targetBounds.isEmpty()) {
443                mCanvas->save(SkCanvas::kClip_SaveFlag);
444                if (mCanvas->clipRect(targetBounds.left, contentBounds.bottom, targetBounds.right,
445                                      targetBounds.bottom, SkRegion::kIntersect_Op)) {
446                    mCanvas->drawRenderNode(node.get(), outBounds);
447                }
448                mCanvas->restore();
449            }
450        } else if (layer == 1) { // Content
451            // It gets cropped against the bounds of the backdrop to stay inside.
452            mCanvas->save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag);
453
454            // We shift and clip the content to match its final location in the window.
455            const float left = mContentDrawBounds.left;
456            const float top = mContentDrawBounds.top;
457            const float dx = backdropBounds.left - left;
458            const float dy = backdropBounds.top - top;
459            const float width = backdropBounds.getWidth();
460            const float height = backdropBounds.getHeight();
461
462            mCanvas->translate(dx, dy);
463            if (mCanvas->clipRect(left, top, left + width, top + height, SkRegion::kIntersect_Op)) {
464                mCanvas->drawRenderNode(node.get(), outBounds);
465            }
466            mCanvas->restore();
467        } else { // draw the rest on top at will!
468            mCanvas->drawRenderNode(node.get(), outBounds);
469        }
470        layer++;
471    }
472
473    profiler().draw(mCanvas);
474
475    bool drew = mCanvas->finish();
476#endif
477    // Even if we decided to cancel the frame, from the perspective of jank
478    // metrics the frame was swapped at this point
479    mCurrentFrameInfo->markSwapBuffers();
480
481    if (drew) {
482        if (CC_UNLIKELY(!mEglManager.swapBuffers(frame, screenDirty))) {
483            setSurface(nullptr);
484        }
485        SwapHistory& swap = mSwapHistory.next();
486        swap.damage = screenDirty;
487        swap.swapTime = systemTime(CLOCK_MONOTONIC);
488        swap.vsyncTime = mRenderThread.timeLord().latestVsync();
489        mHaveNewSurface = false;
490    }
491
492    // TODO: Use a fence for real completion?
493    mCurrentFrameInfo->markFrameCompleted();
494
495#if LOG_FRAMETIME_MMA
496    float thisFrame = mCurrentFrameInfo->duration(
497            FrameInfoIndex::IssueDrawCommandsStart,
498            FrameInfoIndex::FrameCompleted) / NANOS_PER_MILLIS_F;
499    if (sFrameCount) {
500        sBenchMma = ((9 * sBenchMma) + thisFrame) / 10;
501    } else {
502        sBenchMma = thisFrame;
503    }
504    if (++sFrameCount == 10) {
505        sFrameCount = 1;
506        ALOGD("Average frame time: %.4f", sBenchMma);
507    }
508#endif
509
510    mJankTracker.addFrame(*mCurrentFrameInfo);
511    mRenderThread.jankTracker().addFrame(*mCurrentFrameInfo);
512}
513
514// Called by choreographer to do an RT-driven animation
515void CanvasContext::doFrame() {
516    if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) {
517        return;
518    }
519    prepareAndDraw(nullptr);
520}
521
522void CanvasContext::prepareAndDraw(RenderNode* node) {
523    ATRACE_CALL();
524
525    int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE];
526    UiFrameInfoBuilder(frameInfo)
527        .addFlag(FrameInfoFlags::RTAnimation)
528        .setVsync(mRenderThread.timeLord().computeFrameTimeNanos(),
529                mRenderThread.timeLord().latestVsync());
530
531    TreeInfo info(TreeInfo::MODE_RT_ONLY, *this);
532    prepareTree(info, frameInfo, systemTime(CLOCK_MONOTONIC), node);
533    if (info.out.canDrawThisFrame) {
534        draw();
535    }
536}
537
538void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) {
539    ATRACE_CALL();
540    DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
541    if (thread.eglManager().hasEglContext()) {
542        mode = DrawGlInfo::kModeProcess;
543    }
544
545    thread.renderState().invokeFunctor(functor, mode, nullptr);
546}
547
548void CanvasContext::markLayerInUse(RenderNode* node) {
549    if (mPrefetechedLayers.erase(node)) {
550        node->decStrong(nullptr);
551    }
552}
553
554static void destroyPrefetechedNode(RenderNode* node) {
555    ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...", node->getName());
556    node->destroyHardwareResources();
557    node->decStrong(nullptr);
558}
559
560void CanvasContext::freePrefetechedLayers() {
561    if (mPrefetechedLayers.size()) {
562        std::for_each(mPrefetechedLayers.begin(), mPrefetechedLayers.end(), destroyPrefetechedNode);
563        mPrefetechedLayers.clear();
564    }
565}
566
567void CanvasContext::buildLayer(RenderNode* node) {
568    ATRACE_CALL();
569    if (!mEglManager.hasEglContext() || !mCanvas) {
570        return;
571    }
572    // buildLayer() will leave the tree in an unknown state, so we must stop drawing
573    stopDrawing();
574
575    TreeInfo info(TreeInfo::MODE_FULL, *this);
576    info.damageAccumulator = &mDamageAccumulator;
577#if HWUI_NEW_OPS
578    info.layerUpdateQueue = &mLayerUpdateQueue;
579#else
580    info.renderer = mCanvas;
581#endif
582    info.runAnimations = false;
583    node->prepareTree(info);
584    SkRect ignore;
585    mDamageAccumulator.finish(&ignore);
586    // Tickle the GENERIC property on node to mark it as dirty for damaging
587    // purposes when the frame is actually drawn
588    node->setPropertyFieldsDirty(RenderNode::GENERIC);
589
590#if HWUI_NEW_OPS
591    LOG_ALWAYS_FATAL("unsupported");
592#else
593    mCanvas->markLayersAsBuildLayers();
594    mCanvas->flushLayerUpdates();
595#endif
596
597    node->incStrong(nullptr);
598    mPrefetechedLayers.insert(node);
599}
600
601bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) {
602    layer->apply();
603    return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap);
604}
605
606void CanvasContext::destroyHardwareResources() {
607    stopDrawing();
608    if (mEglManager.hasEglContext()) {
609        freePrefetechedLayers();
610        for (const sp<RenderNode>& node : mRenderNodes) {
611            node->destroyHardwareResources();
612        }
613        Caches& caches = Caches::getInstance();
614        // Make sure to release all the textures we were owning as there won't
615        // be another draw
616        caches.textureCache.resetMarkInUse(this);
617        mRenderThread.renderState().flush(Caches::FlushMode::Layers);
618    }
619}
620
621void CanvasContext::trimMemory(RenderThread& thread, int level) {
622    // No context means nothing to free
623    if (!thread.eglManager().hasEglContext()) return;
624
625    ATRACE_CALL();
626    if (level >= TRIM_MEMORY_COMPLETE) {
627        thread.renderState().flush(Caches::FlushMode::Full);
628        thread.eglManager().destroy();
629    } else if (level >= TRIM_MEMORY_UI_HIDDEN) {
630        thread.renderState().flush(Caches::FlushMode::Moderate);
631    }
632}
633
634void CanvasContext::runWithGlContext(RenderTask* task) {
635    LOG_ALWAYS_FATAL_IF(!mEglManager.hasEglContext(),
636            "GL context not initialized!");
637    task->run();
638}
639
640Layer* CanvasContext::createTextureLayer() {
641    requireSurface();
642    return LayerRenderer::createTextureLayer(mRenderThread.renderState());
643}
644
645void CanvasContext::setTextureAtlas(RenderThread& thread,
646        const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) {
647    thread.eglManager().setTextureAtlas(buffer, map, mapSize);
648}
649
650void CanvasContext::dumpFrames(int fd) {
651    FILE* file = fdopen(fd, "a");
652    fprintf(file, "\n\n---PROFILEDATA---\n");
653    for (size_t i = 0; i < static_cast<size_t>(FrameInfoIndex::NumIndexes); i++) {
654        fprintf(file, "%s", FrameInfoNames[i].c_str());
655        fprintf(file, ",");
656    }
657    for (size_t i = 0; i < mFrames.size(); i++) {
658        FrameInfo& frame = mFrames[i];
659        if (frame[FrameInfoIndex::SyncStart] == 0) {
660            continue;
661        }
662        fprintf(file, "\n");
663        for (int i = 0; i < static_cast<int>(FrameInfoIndex::NumIndexes); i++) {
664            fprintf(file, "%" PRId64 ",", frame[i]);
665        }
666    }
667    fprintf(file, "\n---PROFILEDATA---\n\n");
668    fflush(file);
669}
670
671void CanvasContext::resetFrameStats() {
672    mFrames.clear();
673    mRenderThread.jankTracker().reset();
674}
675
676void CanvasContext::serializeDisplayListTree() {
677#if ENABLE_RENDERNODE_SERIALIZATION
678    using namespace google::protobuf::io;
679    char package[128];
680    // Check whether tracing is enabled for this process.
681    FILE * file = fopen("/proc/self/cmdline", "r");
682    if (file) {
683        if (!fgets(package, 128, file)) {
684            ALOGE("Error reading cmdline: %s (%d)", strerror(errno), errno);
685            fclose(file);
686            return;
687        }
688        fclose(file);
689    } else {
690        ALOGE("Error opening /proc/self/cmdline: %s (%d)", strerror(errno),
691                errno);
692        return;
693    }
694    char path[1024];
695    snprintf(path, 1024, "/data/data/%s/cache/rendertree_dump", package);
696    int fd = open(path, O_CREAT | O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH);
697    if (fd == -1) {
698        ALOGD("Failed to open '%s'", path);
699        return;
700    }
701    proto::RenderNode tree;
702    // TODO: Streaming writes?
703    mRootRenderNode->copyTo(&tree);
704    std::string data = tree.SerializeAsString();
705    write(fd, data.c_str(), data.length());
706    close(fd);
707#endif
708}
709
710} /* namespace renderthread */
711} /* namespace uirenderer */
712} /* namespace android */
713