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