CanvasContext.cpp revision 031eaedef8047c8054064ab12d05c3edca07a933
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
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    OpReorderer reorderer(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    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 HWUI_NEW_OPS
506    if (CC_UNLIKELY(mEglSurface == EGL_NO_SURFACE)) return;
507#else
508    if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) return;
509#endif
510    prepareAndDraw(nullptr);
511}
512
513void CanvasContext::prepareAndDraw(RenderNode* node) {
514    ATRACE_CALL();
515
516    int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE];
517    UiFrameInfoBuilder(frameInfo)
518        .addFlag(FrameInfoFlags::RTAnimation)
519        .setVsync(mRenderThread.timeLord().computeFrameTimeNanos(),
520                mRenderThread.timeLord().latestVsync());
521
522    TreeInfo info(TreeInfo::MODE_RT_ONLY, *this);
523    prepareTree(info, frameInfo, systemTime(CLOCK_MONOTONIC), node);
524    if (info.out.canDrawThisFrame) {
525        draw();
526    }
527}
528
529void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) {
530    ATRACE_CALL();
531    DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
532    if (thread.eglManager().hasEglContext()) {
533        mode = DrawGlInfo::kModeProcess;
534    }
535
536    thread.renderState().invokeFunctor(functor, mode, nullptr);
537}
538
539void CanvasContext::markLayerInUse(RenderNode* node) {
540    if (mPrefetechedLayers.erase(node)) {
541        node->decStrong(nullptr);
542    }
543}
544
545static void destroyPrefetechedNode(RenderNode* node) {
546    ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...", node->getName());
547    node->destroyHardwareResources();
548    node->decStrong(nullptr);
549}
550
551void CanvasContext::freePrefetechedLayers() {
552    if (mPrefetechedLayers.size()) {
553        std::for_each(mPrefetechedLayers.begin(), mPrefetechedLayers.end(), destroyPrefetechedNode);
554        mPrefetechedLayers.clear();
555    }
556}
557
558void CanvasContext::buildLayer(RenderNode* node) {
559    ATRACE_CALL();
560    if (!mEglManager.hasEglContext() || !mCanvas) {
561        return;
562    }
563    // buildLayer() will leave the tree in an unknown state, so we must stop drawing
564    stopDrawing();
565
566    TreeInfo info(TreeInfo::MODE_FULL, *this);
567    info.damageAccumulator = &mDamageAccumulator;
568#if HWUI_NEW_OPS
569    info.layerUpdateQueue = &mLayerUpdateQueue;
570#else
571    info.renderer = mCanvas;
572#endif
573    info.runAnimations = false;
574    node->prepareTree(info);
575    SkRect ignore;
576    mDamageAccumulator.finish(&ignore);
577    // Tickle the GENERIC property on node to mark it as dirty for damaging
578    // purposes when the frame is actually drawn
579    node->setPropertyFieldsDirty(RenderNode::GENERIC);
580
581#if HWUI_NEW_OPS
582    LOG_ALWAYS_FATAL("unsupported");
583#else
584    mCanvas->markLayersAsBuildLayers();
585    mCanvas->flushLayerUpdates();
586#endif
587
588    node->incStrong(nullptr);
589    mPrefetechedLayers.insert(node);
590}
591
592bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) {
593    layer->apply();
594    return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap);
595}
596
597void CanvasContext::destroyHardwareResources() {
598    stopDrawing();
599    if (mEglManager.hasEglContext()) {
600        freePrefetechedLayers();
601        for (const sp<RenderNode>& node : mRenderNodes) {
602            node->destroyHardwareResources();
603        }
604        Caches& caches = Caches::getInstance();
605        // Make sure to release all the textures we were owning as there won't
606        // be another draw
607        caches.textureCache.resetMarkInUse(this);
608        mRenderThread.renderState().flush(Caches::FlushMode::Layers);
609    }
610}
611
612void CanvasContext::trimMemory(RenderThread& thread, int level) {
613    // No context means nothing to free
614    if (!thread.eglManager().hasEglContext()) return;
615
616    ATRACE_CALL();
617    if (level >= TRIM_MEMORY_COMPLETE) {
618        thread.renderState().flush(Caches::FlushMode::Full);
619        thread.eglManager().destroy();
620    } else if (level >= TRIM_MEMORY_UI_HIDDEN) {
621        thread.renderState().flush(Caches::FlushMode::Moderate);
622    }
623}
624
625void CanvasContext::runWithGlContext(RenderTask* task) {
626    LOG_ALWAYS_FATAL_IF(!mEglManager.hasEglContext(),
627            "GL context not initialized!");
628    task->run();
629}
630
631Layer* CanvasContext::createTextureLayer() {
632    requireSurface();
633    return LayerRenderer::createTextureLayer(mRenderThread.renderState());
634}
635
636void CanvasContext::setTextureAtlas(RenderThread& thread,
637        const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) {
638    thread.eglManager().setTextureAtlas(buffer, map, mapSize);
639}
640
641void CanvasContext::dumpFrames(int fd) {
642    FILE* file = fdopen(fd, "a");
643    fprintf(file, "\n\n---PROFILEDATA---\n");
644    for (size_t i = 0; i < static_cast<size_t>(FrameInfoIndex::NumIndexes); i++) {
645        fprintf(file, "%s", FrameInfoNames[i].c_str());
646        fprintf(file, ",");
647    }
648    for (size_t i = 0; i < mFrames.size(); i++) {
649        FrameInfo& frame = mFrames[i];
650        if (frame[FrameInfoIndex::SyncStart] == 0) {
651            continue;
652        }
653        fprintf(file, "\n");
654        for (int i = 0; i < static_cast<int>(FrameInfoIndex::NumIndexes); i++) {
655            fprintf(file, "%" PRId64 ",", frame[i]);
656        }
657    }
658    fprintf(file, "\n---PROFILEDATA---\n\n");
659    fflush(file);
660}
661
662void CanvasContext::resetFrameStats() {
663    mFrames.clear();
664    mRenderThread.jankTracker().reset();
665}
666
667void CanvasContext::serializeDisplayListTree() {
668#if ENABLE_RENDERNODE_SERIALIZATION
669    using namespace google::protobuf::io;
670    char package[128];
671    // Check whether tracing is enabled for this process.
672    FILE * file = fopen("/proc/self/cmdline", "r");
673    if (file) {
674        if (!fgets(package, 128, file)) {
675            ALOGE("Error reading cmdline: %s (%d)", strerror(errno), errno);
676            fclose(file);
677            return;
678        }
679        fclose(file);
680    } else {
681        ALOGE("Error opening /proc/self/cmdline: %s (%d)", strerror(errno),
682                errno);
683        return;
684    }
685    char path[1024];
686    snprintf(path, 1024, "/data/data/%s/cache/rendertree_dump", package);
687    int fd = open(path, O_CREAT | O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH);
688    if (fd == -1) {
689        ALOGD("Failed to open '%s'", path);
690        return;
691    }
692    proto::RenderNode tree;
693    // TODO: Streaming writes?
694    mRootRenderNode->copyTo(&tree);
695    std::string data = tree.SerializeAsString();
696    write(fd, data.c_str(), data.length());
697    close(fd);
698#endif
699}
700
701} /* namespace renderthread */
702} /* namespace uirenderer */
703} /* namespace android */
704