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