CanvasContext.cpp revision cbc5bd57f0f528743fce5ec02b0739dc6368311f
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/TimeUtils.h"
33
34#if HWUI_NEW_OPS
35#include "FrameBuilder.h"
36#endif
37
38#include <cutils/properties.h>
39#include <google/protobuf/io/zero_copy_stream_impl.h>
40#include <private/hwui/DrawGlInfo.h>
41#include <strings.h>
42
43#include <algorithm>
44#include <fcntl.h>
45#include <sys/stat.h>
46
47#include <cstdlib>
48
49#define TRIM_MEMORY_COMPLETE 80
50#define TRIM_MEMORY_UI_HIDDEN 20
51
52#define ENABLE_RENDERNODE_SERIALIZATION false
53
54#define LOG_FRAMETIME_MMA 0
55
56#if LOG_FRAMETIME_MMA
57static float sBenchMma = 0;
58static int sFrameCount = 0;
59static const float NANOS_PER_MILLIS_F = 1000000.0f;
60#endif
61
62namespace android {
63namespace uirenderer {
64namespace renderthread {
65
66CanvasContext::CanvasContext(RenderThread& thread, bool translucent,
67        RenderNode* rootRenderNode, IContextFactory* contextFactory)
68        : mRenderThread(thread)
69        , mEglManager(thread.eglManager())
70        , mOpaque(!translucent)
71        , mAnimationContext(contextFactory->createAnimationContext(mRenderThread.timeLord()))
72        , mJankTracker(thread.timeLord().frameIntervalNanos())
73        , mProfiler(mFrames)
74        , mContentDrawBounds(0, 0, 0, 0) {
75    mRenderNodes.emplace_back(rootRenderNode);
76    mRenderThread.renderState().registerCanvasContext(this);
77    mProfiler.setDensity(mRenderThread.mainDisplayInfo().density);
78}
79
80CanvasContext::~CanvasContext() {
81    destroy();
82    mRenderThread.renderState().unregisterCanvasContext(this);
83}
84
85void CanvasContext::destroy() {
86    stopDrawing();
87    setSurface(nullptr);
88    freePrefetechedLayers();
89    destroyHardwareResources();
90    mAnimationContext->destroy();
91    if (mCanvas) {
92        delete mCanvas;
93        mCanvas = nullptr;
94    }
95}
96
97void CanvasContext::setSurface(ANativeWindow* window) {
98    ATRACE_CALL();
99
100    mNativeWindow = window;
101
102    if (mEglSurface != EGL_NO_SURFACE) {
103        mEglManager.destroySurface(mEglSurface);
104        mEglSurface = EGL_NO_SURFACE;
105    }
106
107    if (window) {
108        mEglSurface = mEglManager.createSurface(window);
109    }
110
111    if (mEglSurface != EGL_NO_SURFACE) {
112        const bool preserveBuffer = (mSwapBehavior != kSwap_discardBuffer);
113        mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer);
114        mHaveNewSurface = true;
115        mSwapHistory.clear();
116        makeCurrent();
117    } else {
118        mRenderThread.removeFrameCallback(this);
119    }
120}
121
122void CanvasContext::requireSurface() {
123    LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE,
124            "requireSurface() called but no surface set!");
125    makeCurrent();
126}
127
128void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) {
129    mSwapBehavior = swapBehavior;
130}
131
132void CanvasContext::initialize(ANativeWindow* window) {
133    setSurface(window);
134#if !HWUI_NEW_OPS
135    if (mCanvas) return;
136    mCanvas = new OpenGLRenderer(mRenderThread.renderState());
137    mCanvas->initProperties();
138#endif
139}
140
141void CanvasContext::updateSurface(ANativeWindow* window) {
142    setSurface(window);
143}
144
145bool CanvasContext::pauseSurface(ANativeWindow* window) {
146    return mRenderThread.removeFrameCallback(this);
147}
148
149// TODO: don't pass viewport size, it's automatic via EGL
150void CanvasContext::setup(int width, int height, float lightRadius,
151        uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
152#if HWUI_NEW_OPS
153    mLightInfo.lightRadius = lightRadius;
154    mLightInfo.ambientShadowAlpha = ambientShadowAlpha;
155    mLightInfo.spotShadowAlpha = spotShadowAlpha;
156#else
157    if (!mCanvas) return;
158    mCanvas->initLight(lightRadius, ambientShadowAlpha, spotShadowAlpha);
159#endif
160}
161
162void CanvasContext::setLightCenter(const Vector3& lightCenter) {
163#if HWUI_NEW_OPS
164    mLightCenter = lightCenter;
165#else
166    if (!mCanvas) return;
167    mCanvas->setLightCenter(lightCenter);
168#endif
169}
170
171void CanvasContext::setOpaque(bool opaque) {
172    mOpaque = opaque;
173}
174
175void CanvasContext::makeCurrent() {
176    // TODO: Figure out why this workaround is needed, see b/13913604
177    // In the meantime this matches the behavior of GLRenderer, so it is not a regression
178    EGLint error = 0;
179    mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface, &error);
180    if (error) {
181        setSurface(nullptr);
182    }
183}
184
185static bool wasSkipped(FrameInfo* info) {
186    return info && ((*info)[FrameInfoIndex::Flags] & FrameInfoFlags::SkippedFrame);
187}
188
189void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo,
190        int64_t syncQueued, RenderNode* target) {
191    mRenderThread.removeFrameCallback(this);
192
193    // If the previous frame was dropped we don't need to hold onto it, so
194    // just keep using the previous frame's structure instead
195    if (!wasSkipped(mCurrentFrameInfo)) {
196        mCurrentFrameInfo = &mFrames.next();
197    }
198    mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo);
199    mCurrentFrameInfo->set(FrameInfoIndex::SyncQueued) = syncQueued;
200    mCurrentFrameInfo->markSyncStart();
201
202    info.damageAccumulator = &mDamageAccumulator;
203#if HWUI_NEW_OPS
204    info.layerUpdateQueue = &mLayerUpdateQueue;
205#else
206    info.renderer = mCanvas;
207#endif
208
209    mAnimationContext->startFrame(info.mode);
210    for (const sp<RenderNode>& node : mRenderNodes) {
211        // Only the primary target node will be drawn full - all other nodes would get drawn in
212        // real time mode. In case of a window, the primary node is the window content and the other
213        // node(s) are non client / filler nodes.
214        info.mode = (node.get() == target ? TreeInfo::MODE_FULL : TreeInfo::MODE_RT_ONLY);
215        node->prepareTree(info);
216    }
217    mAnimationContext->runRemainingAnimations(info);
218
219    freePrefetechedLayers();
220
221    if (CC_UNLIKELY(!mNativeWindow.get())) {
222        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
223        info.out.canDrawThisFrame = false;
224        return;
225    }
226
227    if (CC_LIKELY(mSwapHistory.size())) {
228        nsecs_t latestVsync = mRenderThread.timeLord().latestVsync();
229        const SwapHistory& lastSwap = mSwapHistory.back();
230        nsecs_t vsyncDelta = std::abs(lastSwap.vsyncTime - latestVsync);
231        // The slight fudge-factor is to deal with cases where
232        // the vsync was estimated due to being slow handling the signal.
233        // See the logic in TimeLord#computeFrameTimeNanos or in
234        // Choreographer.java for details on when this happens
235        if (vsyncDelta < 2_ms) {
236            // Already drew for this vsync pulse, UI draw request missed
237            // the deadline for RT animations
238            info.out.canDrawThisFrame = false;
239        } else if (lastSwap.swapTime < latestVsync) {
240            info.out.canDrawThisFrame = true;
241        } else {
242            // We're maybe behind? Find out for sure
243            int runningBehind = 0;
244            mNativeWindow->query(mNativeWindow.get(),
245                    NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &runningBehind);
246            info.out.canDrawThisFrame = !runningBehind;
247        }
248    } else {
249        info.out.canDrawThisFrame = true;
250    }
251
252    if (!info.out.canDrawThisFrame) {
253        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
254    }
255
256    if (info.out.hasAnimations || !info.out.canDrawThisFrame) {
257        if (!info.out.requiresUiRedraw) {
258            // If animationsNeedsRedraw is set don't bother posting for an RT anim
259            // as we will just end up fighting the UI thread.
260            mRenderThread.postFrameCallback(this);
261        }
262    }
263}
264
265void CanvasContext::stopDrawing() {
266    mRenderThread.removeFrameCallback(this);
267}
268
269void CanvasContext::notifyFramePending() {
270    ATRACE_CALL();
271    mRenderThread.pushBackFrameCallback(this);
272}
273
274void CanvasContext::draw() {
275#if !HWUI_NEW_OPS
276    LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE,
277            "drawRenderNode called on a context with no canvas or surface!");
278#endif
279
280    SkRect dirty;
281    mDamageAccumulator.finish(&dirty);
282
283    // TODO: Re-enable after figuring out cause of b/22592975
284//    if (dirty.isEmpty() && Properties::skipEmptyFrames) {
285//        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
286//        return;
287//    }
288
289    mCurrentFrameInfo->markIssueDrawCommandsStart();
290
291    Frame frame = mEglManager.beginFrame(mEglSurface);
292
293    if (frame.width() != mLastFrameWidth || frame.height() != mLastFrameHeight) {
294        // can't rely on prior content of window if viewport size changes
295        dirty.setEmpty();
296        mLastFrameWidth = frame.width();
297        mLastFrameHeight = frame.height();
298    } else if (mHaveNewSurface || frame.bufferAge() == 0) {
299        // New surface needs a full draw
300        dirty.setEmpty();
301    } else {
302        if (!dirty.isEmpty() && !dirty.intersect(0, 0, frame.width(), frame.height())) {
303            ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?",
304                    SK_RECT_ARGS(dirty), frame.width(), frame.height());
305            dirty.setEmpty();
306        }
307        profiler().unionDirty(&dirty);
308    }
309
310    if (dirty.isEmpty()) {
311        dirty.set(0, 0, frame.width(), frame.height());
312    }
313
314    // At this point dirty is the area of the screen to update. However,
315    // the area of the frame we need to repaint is potentially different, so
316    // stash the screen area for later
317    SkRect screenDirty(dirty);
318
319    // If the buffer age is 0 we do a full-screen repaint (handled above)
320    // If the buffer age is 1 the buffer contents are the same as they were
321    // last frame so there's nothing to union() against
322    // Therefore we only care about the > 1 case.
323    if (frame.bufferAge() > 1) {
324        if (frame.bufferAge() > (int) mSwapHistory.size()) {
325            // We don't have enough history to handle this old of a buffer
326            // Just do a full-draw
327            dirty.set(0, 0, frame.width(), frame.height());
328        } else {
329            // At this point we haven't yet added the latest frame
330            // to the damage history (happens below)
331            // So we need to damage
332            for (int i = mSwapHistory.size() - 1;
333                    i > ((int) mSwapHistory.size()) - frame.bufferAge(); i--) {
334                dirty.join(mSwapHistory[i].damage);
335            }
336        }
337    }
338
339    mEglManager.damageFrame(frame, dirty);
340
341#if HWUI_NEW_OPS
342    FrameBuilder frameBuilder(mLayerUpdateQueue, dirty, frame.width(), frame.height(),
343            mRenderNodes, mLightCenter);
344    mLayerUpdateQueue.clear();
345    BakedOpRenderer renderer(Caches::getInstance(), mRenderThread.renderState(),
346            mOpaque, mLightInfo);
347    // TODO: profiler().draw(mCanvas);
348    frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer);
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    GpuMemoryTracker::onFrameCompleted();
503}
504
505// Called by choreographer to do an RT-driven animation
506void CanvasContext::doFrame() {
507#if HWUI_NEW_OPS
508    if (CC_UNLIKELY(mEglSurface == EGL_NO_SURFACE)) return;
509#else
510    if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) return;
511#endif
512    prepareAndDraw(nullptr);
513}
514
515void CanvasContext::prepareAndDraw(RenderNode* node) {
516    ATRACE_CALL();
517
518    nsecs_t vsync = mRenderThread.timeLord().computeFrameTimeNanos();
519    int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE];
520    UiFrameInfoBuilder(frameInfo)
521        .addFlag(FrameInfoFlags::RTAnimation)
522        .setVsync(vsync, vsync);
523
524    TreeInfo info(TreeInfo::MODE_RT_ONLY, *this);
525    prepareTree(info, frameInfo, systemTime(CLOCK_MONOTONIC), node);
526    if (info.out.canDrawThisFrame) {
527        draw();
528    }
529}
530
531void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) {
532    ATRACE_CALL();
533    DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
534    if (thread.eglManager().hasEglContext()) {
535        mode = DrawGlInfo::kModeProcess;
536    }
537
538    thread.renderState().invokeFunctor(functor, mode, nullptr);
539}
540
541void CanvasContext::markLayerInUse(RenderNode* node) {
542    if (mPrefetechedLayers.erase(node)) {
543        node->decStrong(nullptr);
544    }
545}
546
547static void destroyPrefetechedNode(RenderNode* node) {
548    ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...", node->getName());
549    node->destroyHardwareResources();
550    node->decStrong(nullptr);
551}
552
553void CanvasContext::freePrefetechedLayers() {
554    if (mPrefetechedLayers.size()) {
555        std::for_each(mPrefetechedLayers.begin(), mPrefetechedLayers.end(), destroyPrefetechedNode);
556        mPrefetechedLayers.clear();
557    }
558}
559
560void CanvasContext::buildLayer(RenderNode* node) {
561    ATRACE_CALL();
562    if (!mEglManager.hasEglContext() || !mCanvas) {
563        return;
564    }
565    // buildLayer() will leave the tree in an unknown state, so we must stop drawing
566    stopDrawing();
567
568    TreeInfo info(TreeInfo::MODE_FULL, *this);
569    info.damageAccumulator = &mDamageAccumulator;
570#if HWUI_NEW_OPS
571    info.layerUpdateQueue = &mLayerUpdateQueue;
572#else
573    info.renderer = mCanvas;
574#endif
575    info.runAnimations = false;
576    node->prepareTree(info);
577    SkRect ignore;
578    mDamageAccumulator.finish(&ignore);
579    // Tickle the GENERIC property on node to mark it as dirty for damaging
580    // purposes when the frame is actually drawn
581    node->setPropertyFieldsDirty(RenderNode::GENERIC);
582
583#if HWUI_NEW_OPS
584    // TODO: support buildLayer
585#else
586    mCanvas->markLayersAsBuildLayers();
587    mCanvas->flushLayerUpdates();
588#endif
589
590    node->incStrong(nullptr);
591    mPrefetechedLayers.insert(node);
592}
593
594bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) {
595    layer->apply();
596    return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap);
597}
598
599void CanvasContext::destroyHardwareResources() {
600    stopDrawing();
601    if (mEglManager.hasEglContext()) {
602        freePrefetechedLayers();
603        for (const sp<RenderNode>& node : mRenderNodes) {
604            node->destroyHardwareResources();
605        }
606        Caches& caches = Caches::getInstance();
607        // Make sure to release all the textures we were owning as there won't
608        // be another draw
609        caches.textureCache.resetMarkInUse(this);
610        mRenderThread.renderState().flush(Caches::FlushMode::Layers);
611    }
612}
613
614void CanvasContext::trimMemory(RenderThread& thread, int level) {
615    // No context means nothing to free
616    if (!thread.eglManager().hasEglContext()) return;
617
618    ATRACE_CALL();
619    if (level >= TRIM_MEMORY_COMPLETE) {
620        thread.renderState().flush(Caches::FlushMode::Full);
621        thread.eglManager().destroy();
622    } else if (level >= TRIM_MEMORY_UI_HIDDEN) {
623        thread.renderState().flush(Caches::FlushMode::Moderate);
624    }
625}
626
627void CanvasContext::runWithGlContext(RenderTask* task) {
628    LOG_ALWAYS_FATAL_IF(!mEglManager.hasEglContext(),
629            "GL context not initialized!");
630    task->run();
631}
632
633Layer* CanvasContext::createTextureLayer() {
634    requireSurface();
635    return LayerRenderer::createTextureLayer(mRenderThread.renderState());
636}
637
638void CanvasContext::setTextureAtlas(RenderThread& thread,
639        const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) {
640    thread.eglManager().setTextureAtlas(buffer, map, mapSize);
641}
642
643void CanvasContext::dumpFrames(int fd) {
644    FILE* file = fdopen(fd, "a");
645    fprintf(file, "\n\n---PROFILEDATA---\n");
646    for (size_t i = 0; i < static_cast<size_t>(FrameInfoIndex::NumIndexes); i++) {
647        fprintf(file, "%s", FrameInfoNames[i].c_str());
648        fprintf(file, ",");
649    }
650    for (size_t i = 0; i < mFrames.size(); i++) {
651        FrameInfo& frame = mFrames[i];
652        if (frame[FrameInfoIndex::SyncStart] == 0) {
653            continue;
654        }
655        fprintf(file, "\n");
656        for (int i = 0; i < static_cast<int>(FrameInfoIndex::NumIndexes); i++) {
657            fprintf(file, "%" PRId64 ",", frame[i]);
658        }
659    }
660    fprintf(file, "\n---PROFILEDATA---\n\n");
661    fflush(file);
662}
663
664void CanvasContext::resetFrameStats() {
665    mFrames.clear();
666    mRenderThread.jankTracker().reset();
667}
668
669void CanvasContext::serializeDisplayListTree() {
670#if ENABLE_RENDERNODE_SERIALIZATION
671    using namespace google::protobuf::io;
672    char package[128];
673    // Check whether tracing is enabled for this process.
674    FILE * file = fopen("/proc/self/cmdline", "r");
675    if (file) {
676        if (!fgets(package, 128, file)) {
677            ALOGE("Error reading cmdline: %s (%d)", strerror(errno), errno);
678            fclose(file);
679            return;
680        }
681        fclose(file);
682    } else {
683        ALOGE("Error opening /proc/self/cmdline: %s (%d)", strerror(errno),
684                errno);
685        return;
686    }
687    char path[1024];
688    snprintf(path, 1024, "/data/data/%s/cache/rendertree_dump", package);
689    int fd = open(path, O_CREAT | O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH);
690    if (fd == -1) {
691        ALOGD("Failed to open '%s'", path);
692        return;
693    }
694    proto::RenderNode tree;
695    // TODO: Streaming writes?
696    mRootRenderNode->copyTo(&tree);
697    std::string data = tree.SerializeAsString();
698    write(fd, data.c_str(), data.length());
699    close(fd);
700#endif
701}
702
703} /* namespace renderthread */
704} /* namespace uirenderer */
705} /* namespace android */
706