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