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