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