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