• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "CanvasContext.h"
18 
19 #include <apex/window.h>
20 #include <fcntl.h>
21 #include <gui/TraceUtils.h>
22 #include <strings.h>
23 #include <sys/stat.h>
24 #include <ui/Fence.h>
25 
26 #include <algorithm>
27 #include <cstdint>
28 #include <cstdlib>
29 #include <functional>
30 
31 #include "../Properties.h"
32 #include "AnimationContext.h"
33 #include "Frame.h"
34 #include "LayerUpdateQueue.h"
35 #include "Properties.h"
36 #include "RenderThread.h"
37 #include "hwui/Canvas.h"
38 #include "pipeline/skia/SkiaCpuPipeline.h"
39 #include "pipeline/skia/SkiaGpuPipeline.h"
40 #include "pipeline/skia/SkiaOpenGLPipeline.h"
41 #include "pipeline/skia/SkiaVulkanPipeline.h"
42 #include "thread/CommonPool.h"
43 #include "utils/GLUtils.h"
44 #include "utils/TimeUtils.h"
45 
46 #define LOG_FRAMETIME_MMA 0
47 
48 #if LOG_FRAMETIME_MMA
49 static float sBenchMma = 0;
50 static int sFrameCount = 0;
51 static const float NANOS_PER_MILLIS_F = 1000000.0f;
52 #endif
53 
54 namespace android {
55 namespace uirenderer {
56 namespace renderthread {
57 
58 namespace {
59 class ScopedActiveContext {
60 public:
ScopedActiveContext(CanvasContext * context)61     ScopedActiveContext(CanvasContext* context) { sActiveContext = context; }
62 
~ScopedActiveContext()63     ~ScopedActiveContext() { sActiveContext = nullptr; }
64 
getActiveContext()65     static CanvasContext* getActiveContext() { return sActiveContext; }
66 
67 private:
68     static CanvasContext* sActiveContext;
69 };
70 
71 CanvasContext* ScopedActiveContext::sActiveContext = nullptr;
72 } /* namespace */
73 
create(RenderThread & thread,bool translucent,RenderNode * rootRenderNode,IContextFactory * contextFactory,pid_t uiThreadId,pid_t renderThreadId)74 CanvasContext* CanvasContext::create(RenderThread& thread, bool translucent,
75                                      RenderNode* rootRenderNode, IContextFactory* contextFactory,
76                                      pid_t uiThreadId, pid_t renderThreadId) {
77     auto renderType = Properties::getRenderPipelineType();
78 
79     switch (renderType) {
80         case RenderPipelineType::SkiaGL:
81             return new CanvasContext(thread, translucent, rootRenderNode, contextFactory,
82                                      std::make_unique<skiapipeline::SkiaOpenGLPipeline>(thread),
83                                      uiThreadId, renderThreadId);
84         case RenderPipelineType::SkiaVulkan:
85             return new CanvasContext(thread, translucent, rootRenderNode, contextFactory,
86                                      std::make_unique<skiapipeline::SkiaVulkanPipeline>(thread),
87                                      uiThreadId, renderThreadId);
88 #ifndef __ANDROID__
89         case RenderPipelineType::SkiaCpu:
90             return new CanvasContext(thread, translucent, rootRenderNode, contextFactory,
91                                      std::make_unique<skiapipeline::SkiaCpuPipeline>(thread),
92                                      uiThreadId, renderThreadId);
93 #endif
94         default:
95             LOG_ALWAYS_FATAL("canvas context type %d not supported", (int32_t)renderType);
96             break;
97     }
98     return nullptr;
99 }
100 
invokeFunctor(const RenderThread & thread,Functor * functor)101 void CanvasContext::invokeFunctor(const RenderThread& thread, Functor* functor) {
102     ATRACE_CALL();
103     auto renderType = Properties::getRenderPipelineType();
104     switch (renderType) {
105         case RenderPipelineType::SkiaGL:
106             skiapipeline::SkiaOpenGLPipeline::invokeFunctor(thread, functor);
107             break;
108         case RenderPipelineType::SkiaVulkan:
109             skiapipeline::SkiaVulkanPipeline::invokeFunctor(thread, functor);
110             break;
111         default:
112             LOG_ALWAYS_FATAL("canvas context type %d not supported", (int32_t)renderType);
113             break;
114     }
115 }
116 
prepareToDraw(const RenderThread & thread,Bitmap * bitmap)117 void CanvasContext::prepareToDraw(const RenderThread& thread, Bitmap* bitmap) {
118     skiapipeline::SkiaGpuPipeline::prepareToDraw(thread, bitmap);
119 }
120 
CanvasContext(RenderThread & thread,bool translucent,RenderNode * rootRenderNode,IContextFactory * contextFactory,std::unique_ptr<IRenderPipeline> renderPipeline,pid_t uiThreadId,pid_t renderThreadId)121 CanvasContext::CanvasContext(RenderThread& thread, bool translucent, RenderNode* rootRenderNode,
122                              IContextFactory* contextFactory,
123                              std::unique_ptr<IRenderPipeline> renderPipeline, pid_t uiThreadId,
124                              pid_t renderThreadId)
125         : mRenderThread(thread)
126         , mGenerationID(0)
127         , mOpaque(!translucent)
128         , mAnimationContext(contextFactory->createAnimationContext(mRenderThread.timeLord()))
129         , mJankTracker(&thread.globalProfileData())
130         , mProfiler(mJankTracker.frames(), thread.timeLord().frameIntervalNanos())
131         , mContentDrawBounds(0, 0, 0, 0)
132         , mRenderPipeline(std::move(renderPipeline))
133         , mHintSessionWrapper(std::make_shared<HintSessionWrapper>(uiThreadId, renderThreadId)) {
134     mRenderThread.cacheManager().registerCanvasContext(this);
135     mRenderThread.renderState().registerContextCallback(this);
136     rootRenderNode->makeRoot();
137     mRenderNodes.emplace_back(rootRenderNode);
138     mProfiler.setDensity(DeviceInfo::getDensity());
139 }
140 
~CanvasContext()141 CanvasContext::~CanvasContext() {
142     destroy();
143     for (auto& node : mRenderNodes) {
144         node->clearRoot();
145     }
146     mRenderNodes.clear();
147     mRenderThread.cacheManager().unregisterCanvasContext(this);
148     mRenderThread.renderState().removeContextCallback(this);
149     mHintSessionWrapper->destroy();
150 }
151 
addRenderNode(RenderNode * node,bool placeFront)152 void CanvasContext::addRenderNode(RenderNode* node, bool placeFront) {
153     int pos = placeFront ? 0 : static_cast<int>(mRenderNodes.size());
154     node->makeRoot();
155     mRenderNodes.emplace(mRenderNodes.begin() + pos, node);
156 }
157 
removeRenderNode(RenderNode * node)158 void CanvasContext::removeRenderNode(RenderNode* node) {
159     node->clearRoot();
160     mRenderNodes.erase(std::remove(mRenderNodes.begin(), mRenderNodes.end(), node),
161                        mRenderNodes.end());
162 }
163 
destroy()164 void CanvasContext::destroy() {
165     stopDrawing();
166     setHardwareBuffer(nullptr);
167     setSurface(nullptr);
168     setSurfaceControl(nullptr);
169     freePrefetchedLayers();
170     destroyHardwareResources();
171     mAnimationContext->destroy();
172     mRenderThread.cacheManager().onContextStopped(this);
173     mHintSessionWrapper->delayedDestroy(mRenderThread, 2_s, mHintSessionWrapper);
174 }
175 
setBufferCount(ANativeWindow * window)176 static void setBufferCount(ANativeWindow* window) {
177     int query_value;
178     int err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &query_value);
179     if (err != 0 || query_value < 0) {
180         ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err, query_value);
181         return;
182     }
183     auto min_undequeued_buffers = static_cast<uint32_t>(query_value);
184 
185     // We only need to set min_undequeued + 2 because the renderahead amount was already factored into the
186     // query for min_undequeued
187     int bufferCount = min_undequeued_buffers + 2;
188     native_window_set_buffer_count(window, bufferCount);
189 }
190 
setHardwareBuffer(AHardwareBuffer * buffer)191 void CanvasContext::setHardwareBuffer(AHardwareBuffer* buffer) {
192 #ifdef __ANDROID__
193     if (mHardwareBuffer) {
194         AHardwareBuffer_release(mHardwareBuffer);
195         mHardwareBuffer = nullptr;
196     }
197 
198     if (buffer) {
199         AHardwareBuffer_acquire(buffer);
200         mHardwareBuffer = buffer;
201     }
202     mRenderPipeline->setHardwareBuffer(mHardwareBuffer);
203 #endif
204 }
205 
setSurface(ANativeWindow * window,bool enableTimeout)206 void CanvasContext::setSurface(ANativeWindow* window, bool enableTimeout) {
207     ATRACE_CALL();
208 
209     startHintSession();
210     if (window) {
211         mNativeSurface = std::make_unique<ReliableSurface>(window);
212         mNativeSurface->init();
213         if (enableTimeout) {
214             // TODO: Fix error handling & re-shorten timeout
215             ANativeWindow_setDequeueTimeout(window, 4000_ms);
216         }
217     } else {
218         mNativeSurface = nullptr;
219     }
220     setupPipelineSurface();
221 }
222 
setSurfaceControl(ASurfaceControl * surfaceControl)223 void CanvasContext::setSurfaceControl(ASurfaceControl* surfaceControl) {
224     if (surfaceControl == mSurfaceControl) return;
225 
226     auto funcs = mRenderThread.getASurfaceControlFunctions();
227 
228     if (surfaceControl == nullptr) {
229         setASurfaceTransactionCallback(nullptr);
230         setPrepareSurfaceControlForWebviewCallback(nullptr);
231     }
232 
233     if (mSurfaceControl != nullptr) {
234         funcs.unregisterListenerFunc(this, &onSurfaceStatsAvailable);
235         funcs.releaseFunc(mSurfaceControl);
236     }
237     mSurfaceControl = surfaceControl;
238     mSurfaceControlGenerationId++;
239     mExpectSurfaceStats = surfaceControl != nullptr;
240     if (mExpectSurfaceStats) {
241         funcs.acquireFunc(mSurfaceControl);
242         funcs.registerListenerFunc(surfaceControl, mSurfaceControlGenerationId, this,
243                                    &onSurfaceStatsAvailable);
244     }
245 }
246 
setupPipelineSurface()247 void CanvasContext::setupPipelineSurface() {
248     bool hasSurface = mRenderPipeline->setSurface(
249             mNativeSurface ? mNativeSurface->getNativeWindow() : nullptr, mSwapBehavior);
250 
251     if (mNativeSurface && !mNativeSurface->didSetExtraBuffers()) {
252         setBufferCount(mNativeSurface->getNativeWindow());
253     }
254 
255     mFrameNumber = 0;
256 
257     if (mNativeSurface != nullptr && hasSurface) {
258         mHaveNewSurface = true;
259         mSwapHistory.clear();
260         // Enable frame stats after the surface has been bound to the appropriate graphics API.
261         // Order is important when new and old surfaces are the same, because old surface has
262         // its frame stats disabled automatically.
263         native_window_enable_frame_timestamps(mNativeSurface->getNativeWindow(), true);
264         native_window_set_scaling_mode(mNativeSurface->getNativeWindow(),
265                                        NATIVE_WINDOW_SCALING_MODE_FREEZE);
266     } else {
267         mRenderThread.removeFrameCallback(this);
268         mGenerationID++;
269     }
270 }
271 
setSwapBehavior(SwapBehavior swapBehavior)272 void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) {
273     mSwapBehavior = swapBehavior;
274 }
275 
pauseSurface()276 bool CanvasContext::pauseSurface() {
277     mGenerationID++;
278     return mRenderThread.removeFrameCallback(this);
279 }
280 
setStopped(bool stopped)281 void CanvasContext::setStopped(bool stopped) {
282     if (mStopped != stopped) {
283         mStopped = stopped;
284         if (mStopped) {
285             mGenerationID++;
286             mRenderThread.removeFrameCallback(this);
287             mRenderPipeline->onStop();
288             mRenderThread.cacheManager().onContextStopped(this);
289         } else if (mIsDirty && hasOutputTarget()) {
290             mRenderThread.postFrameCallback(this);
291         }
292     }
293 }
294 
allocateBuffers()295 void CanvasContext::allocateBuffers() {
296     if (mNativeSurface && Properties::isDrawingEnabled()) {
297         ANativeWindow_tryAllocateBuffers(mNativeSurface->getNativeWindow());
298     }
299 }
300 
setLightAlpha(uint8_t ambientShadowAlpha,uint8_t spotShadowAlpha)301 void CanvasContext::setLightAlpha(uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
302     mLightInfo.ambientShadowAlpha = ambientShadowAlpha;
303     mLightInfo.spotShadowAlpha = spotShadowAlpha;
304 }
305 
setLightGeometry(const Vector3 & lightCenter,float lightRadius)306 void CanvasContext::setLightGeometry(const Vector3& lightCenter, float lightRadius) {
307     mLightGeometry.center = lightCenter;
308     mLightGeometry.radius = lightRadius;
309 }
310 
setOpaque(bool opaque)311 void CanvasContext::setOpaque(bool opaque) {
312     mOpaque = opaque;
313 }
314 
setColorMode(ColorMode mode)315 float CanvasContext::setColorMode(ColorMode mode) {
316     if (mode != mColorMode) {
317         mColorMode = mode;
318         mRenderPipeline->setSurfaceColorProperties(mode);
319         setupPipelineSurface();
320     }
321     switch (mColorMode) {
322         case ColorMode::Hdr:
323             return Properties::maxHdrHeadroomOn8bit;
324         case ColorMode::Hdr10:
325             return 10.f;
326         default:
327             return 1.f;
328     }
329 }
330 
targetSdrHdrRatio() const331 float CanvasContext::targetSdrHdrRatio() const {
332     if (mColorMode == ColorMode::Hdr || mColorMode == ColorMode::Hdr10) {
333         return mTargetSdrHdrRatio;
334     } else {
335         return 1.f;
336     }
337 }
338 
setTargetSdrHdrRatio(float ratio)339 void CanvasContext::setTargetSdrHdrRatio(float ratio) {
340     if (mTargetSdrHdrRatio == ratio) return;
341 
342     mTargetSdrHdrRatio = ratio;
343     mRenderPipeline->setTargetSdrHdrRatio(ratio);
344     // We don't actually but we need to behave as if we do. Specifically we need to ensure
345     // all buffers in the swapchain are fully re-rendered as any partial updates to them will
346     // result in mixed target white points which looks really bad & flickery
347     mHaveNewSurface = true;
348 }
349 
makeCurrent()350 bool CanvasContext::makeCurrent() {
351     if (mStopped) return false;
352 
353     auto result = mRenderPipeline->makeCurrent();
354     switch (result) {
355         case MakeCurrentResult::AlreadyCurrent:
356             return true;
357         case MakeCurrentResult::Failed:
358             mHaveNewSurface = true;
359             setSurface(nullptr);
360             return false;
361         case MakeCurrentResult::Succeeded:
362             mHaveNewSurface = true;
363             return true;
364         default:
365             LOG_ALWAYS_FATAL("unexpected result %d from IRenderPipeline::makeCurrent",
366                              (int32_t)result);
367     }
368 
369     return true;
370 }
371 
wasSkipped(FrameInfo * info)372 static std::optional<SkippedFrameReason> wasSkipped(FrameInfo* info) {
373     if (info) return info->getSkippedFrameReason();
374     return std::nullopt;
375 }
376 
isSwapChainStuffed()377 bool CanvasContext::isSwapChainStuffed() {
378     static const auto SLOW_THRESHOLD = 6_ms;
379 
380     if (mSwapHistory.size() != mSwapHistory.capacity()) {
381         // We want at least 3 frames of history before attempting to
382         // guess if the queue is stuffed
383         return false;
384     }
385     nsecs_t frameInterval = mRenderThread.timeLord().frameIntervalNanos();
386     auto& swapA = mSwapHistory[0];
387 
388     // Was there a happy queue & dequeue time? If so, don't
389     // consider it stuffed
390     if (swapA.dequeueDuration < SLOW_THRESHOLD && swapA.queueDuration < SLOW_THRESHOLD) {
391         return false;
392     }
393 
394     for (size_t i = 1; i < mSwapHistory.size(); i++) {
395         auto& swapB = mSwapHistory[i];
396 
397         // If there's a multi-frameInterval gap we effectively already dropped a frame,
398         // so consider the queue healthy.
399         if (std::abs(swapA.swapCompletedTime - swapB.swapCompletedTime) > frameInterval * 3) {
400             return false;
401         }
402 
403         // Was there a happy queue & dequeue time? If so, don't
404         // consider it stuffed
405         if (swapB.dequeueDuration < SLOW_THRESHOLD && swapB.queueDuration < SLOW_THRESHOLD) {
406             return false;
407         }
408 
409         swapA = swapB;
410     }
411 
412     // All signs point to a stuffed swap chain
413     ATRACE_NAME("swap chain stuffed");
414     return true;
415 }
416 
prepareTree(TreeInfo & info,int64_t * uiFrameInfo,int64_t syncQueued,RenderNode * target)417 void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo, int64_t syncQueued,
418                                 RenderNode* target) {
419     mRenderThread.removeFrameCallback(this);
420 
421     // If the previous frame was dropped we don't need to hold onto it, so
422     // just keep using the previous frame's structure instead
423     const auto reason = wasSkipped(mCurrentFrameInfo);
424     if (reason.has_value()) {
425         // Use the oldest skipped frame in case we skip more than a single frame
426         if (!mSkippedFrameInfo) {
427             switch (*reason) {
428                 case SkippedFrameReason::AlreadyDrawn:
429                 case SkippedFrameReason::NoBuffer:
430                 case SkippedFrameReason::NoOutputTarget:
431                     mSkippedFrameInfo.emplace();
432                     mSkippedFrameInfo->vsyncId =
433                             mCurrentFrameInfo->get(FrameInfoIndex::FrameTimelineVsyncId);
434                     mSkippedFrameInfo->startTime =
435                             mCurrentFrameInfo->get(FrameInfoIndex::FrameStartTime);
436                     break;
437                 case SkippedFrameReason::DrawingOff:
438                 case SkippedFrameReason::ContextIsStopped:
439                 case SkippedFrameReason::NothingToDraw:
440                     // Do not report those as skipped frames as there was no frame expected to be
441                     // drawn
442                     break;
443             }
444         }
445     } else {
446         mCurrentFrameInfo = mJankTracker.startFrame();
447         mSkippedFrameInfo.reset();
448     }
449 
450     mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo);
451     mCurrentFrameInfo->set(FrameInfoIndex::SyncQueued) = syncQueued;
452     mCurrentFrameInfo->markSyncStart();
453 
454     info.damageAccumulator = &mDamageAccumulator;
455     info.layerUpdateQueue = &mLayerUpdateQueue;
456     info.damageGenerationId = mDamageId++;
457     info.out.skippedFrameReason = std::nullopt;
458 
459     mAnimationContext->startFrame(info.mode);
460     for (const sp<RenderNode>& node : mRenderNodes) {
461         // Only the primary target node will be drawn full - all other nodes would get drawn in
462         // real time mode. In case of a window, the primary node is the window content and the other
463         // node(s) are non client / filler nodes.
464         info.mode = (node.get() == target ? TreeInfo::MODE_FULL : TreeInfo::MODE_RT_ONLY);
465         node->prepareTree(info);
466         GL_CHECKPOINT(MODERATE);
467     }
468     mAnimationContext->runRemainingAnimations(info);
469     GL_CHECKPOINT(MODERATE);
470 
471     freePrefetchedLayers();
472     GL_CHECKPOINT(MODERATE);
473 
474     mIsDirty = true;
475 
476     if (CC_UNLIKELY(!hasOutputTarget())) {
477         info.out.skippedFrameReason = SkippedFrameReason::NoOutputTarget;
478         mCurrentFrameInfo->setSkippedFrameReason(*info.out.skippedFrameReason);
479         return;
480     }
481 
482     if (CC_LIKELY(mSwapHistory.size() && !info.forceDrawFrame)) {
483         nsecs_t latestVsync = mRenderThread.timeLord().latestVsync();
484         SwapHistory& lastSwap = mSwapHistory.back();
485         nsecs_t vsyncDelta = std::abs(lastSwap.vsyncTime - latestVsync);
486         // The slight fudge-factor is to deal with cases where
487         // the vsync was estimated due to being slow handling the signal.
488         // See the logic in TimeLord#computeFrameTimeNanos or in
489         // Choreographer.java for details on when this happens
490         if (vsyncDelta < 2_ms) {
491             // Already drew for this vsync pulse, UI draw request missed
492             // the deadline for RT animations
493             info.out.skippedFrameReason = SkippedFrameReason::AlreadyDrawn;
494         }
495     } else {
496         info.out.skippedFrameReason = std::nullopt;
497     }
498 
499     // TODO: Do we need to abort out if the backdrop is added but not ready? Should that even
500     // be an allowable combination?
501     if (mRenderNodes.size() > 2 && !mRenderNodes[1]->isRenderable()) {
502         info.out.skippedFrameReason = SkippedFrameReason::NothingToDraw;
503     }
504 
505     if (!info.out.skippedFrameReason) {
506         int err = mNativeSurface->reserveNext();
507         if (err != OK) {
508             info.out.skippedFrameReason = SkippedFrameReason::NoBuffer;
509             mCurrentFrameInfo->setSkippedFrameReason(*info.out.skippedFrameReason);
510             ALOGW("reserveNext failed, error = %d (%s)", err, strerror(-err));
511             if (err != TIMED_OUT) {
512                 // A timed out surface can still recover, but assume others are permanently dead.
513                 setSurface(nullptr);
514                 return;
515             }
516         }
517     } else {
518         mCurrentFrameInfo->setSkippedFrameReason(*info.out.skippedFrameReason);
519     }
520 
521     bool postedFrameCallback = false;
522     if (info.out.hasAnimations || info.out.skippedFrameReason) {
523         if (CC_UNLIKELY(!Properties::enableRTAnimations)) {
524             info.out.requiresUiRedraw = true;
525         }
526         if (!info.out.requiresUiRedraw) {
527             // If animationsNeedsRedraw is set don't bother posting for an RT anim
528             // as we will just end up fighting the UI thread.
529             mRenderThread.postFrameCallback(this);
530             postedFrameCallback = true;
531         }
532     }
533 
534     if (!postedFrameCallback &&
535         info.out.animatedImageDelay != TreeInfo::Out::kNoAnimatedImageDelay) {
536         // Subtract the time of one frame so it can be displayed on time.
537         const nsecs_t kFrameTime = mRenderThread.timeLord().frameIntervalNanos();
538         if (info.out.animatedImageDelay <= kFrameTime) {
539             mRenderThread.postFrameCallback(this);
540         } else {
541             const auto delay = info.out.animatedImageDelay - kFrameTime;
542             int genId = mGenerationID;
543             mRenderThread.queue().postDelayed(delay, [this, genId]() {
544                 if (mGenerationID == genId) {
545                     mRenderThread.postFrameCallback(this);
546                 }
547             });
548         }
549     }
550 }
551 
stopDrawing()552 void CanvasContext::stopDrawing() {
553     mRenderThread.removeFrameCallback(this);
554     mAnimationContext->pauseAnimators();
555     mGenerationID++;
556 }
557 
notifyFramePending()558 void CanvasContext::notifyFramePending() {
559     ATRACE_CALL();
560     mRenderThread.pushBackFrameCallback(this);
561     sendLoadResetHint();
562 }
563 
getFrame()564 Frame CanvasContext::getFrame() {
565     if (mHardwareBuffer != nullptr) {
566         return {mBufferParams.getLogicalWidth(), mBufferParams.getLogicalHeight(), 0};
567     } else {
568         return mRenderPipeline->getFrame();
569     }
570 }
571 
draw(bool solelyTextureViewUpdates)572 void CanvasContext::draw(bool solelyTextureViewUpdates) {
573 #ifdef __ANDROID__
574     if (auto grContext = getGrContext()) {
575         if (grContext->abandoned()) {
576             if (grContext->isDeviceLost()) {
577                 LOG_ALWAYS_FATAL("Lost GPU device unexpectedly");
578                 return;
579             }
580             LOG_ALWAYS_FATAL("GrContext is abandoned at start of CanvasContext::draw");
581             return;
582         }
583     }
584 #endif
585     SkRect dirty;
586     mDamageAccumulator.finish(&dirty);
587 
588     // reset syncDelayDuration each time we draw
589     nsecs_t syncDelayDuration = mSyncDelayDuration;
590     nsecs_t idleDuration = mIdleDuration;
591     mSyncDelayDuration = 0;
592     mIdleDuration = 0;
593 
594     const auto skippedFrameReason = [&]() -> std::optional<SkippedFrameReason> {
595         if (!Properties::isDrawingEnabled()) {
596             return SkippedFrameReason::DrawingOff;
597         }
598 
599         if (dirty.isEmpty() && Properties::skipEmptyFrames && !surfaceRequiresRedraw()) {
600             return SkippedFrameReason::NothingToDraw;
601         }
602 
603         return std::nullopt;
604     }();
605     if (skippedFrameReason) {
606         mCurrentFrameInfo->setSkippedFrameReason(*skippedFrameReason);
607 
608 #ifdef __ANDROID__
609         if (auto grContext = getGrContext()) {
610             // Submit to ensure that any texture uploads complete and Skia can
611             // free its staging buffers.
612             grContext->flushAndSubmit();
613         }
614 #endif
615 
616         // Notify the callbacks, even if there's nothing to draw so they aren't waiting
617         // indefinitely
618         waitOnFences();
619         for (auto& func : mFrameCommitCallbacks) {
620             std::invoke(func, false /* didProduceBuffer */);
621         }
622         mFrameCommitCallbacks.clear();
623         return;
624     }
625 
626     ScopedActiveContext activeContext(this);
627     mCurrentFrameInfo->set(FrameInfoIndex::FrameInterval) =
628             mRenderThread.timeLord().frameIntervalNanos();
629 
630     mCurrentFrameInfo->markIssueDrawCommandsStart();
631 
632     Frame frame = getFrame();
633 
634     SkRect windowDirty = computeDirtyRect(frame, &dirty);
635 
636     ATRACE_FORMAT("Drawing " RECT_STRING, SK_RECT_ARGS(dirty));
637 
638     IRenderPipeline::DrawResult drawResult;
639     {
640         // FrameInfoVisualizer accesses the frame events, which cannot be mutated mid-draw
641         // or it can lead to memory corruption.
642         drawResult = mRenderPipeline->draw(
643                 frame, windowDirty, dirty, mLightGeometry, &mLayerUpdateQueue, mContentDrawBounds,
644                 mOpaque, mLightInfo, mRenderNodes, &(profiler()), mBufferParams, profilerLock());
645     }
646 
647     uint64_t frameCompleteNr = getFrameNumber();
648 
649     waitOnFences();
650 
651     if (mNativeSurface) {
652         // TODO(b/165985262): measure performance impact
653         const auto vsyncId = mCurrentFrameInfo->get(FrameInfoIndex::FrameTimelineVsyncId);
654         if (vsyncId != UiFrameInfoBuilder::INVALID_VSYNC_ID) {
655             const auto inputEventId =
656                     static_cast<int32_t>(mCurrentFrameInfo->get(FrameInfoIndex::InputEventId));
657             const ANativeWindowFrameTimelineInfo ftl = {
658                     .frameNumber = frameCompleteNr,
659                     .frameTimelineVsyncId = vsyncId,
660                     .inputEventId = inputEventId,
661                     .startTimeNanos = mCurrentFrameInfo->get(FrameInfoIndex::FrameStartTime),
662                     .useForRefreshRateSelection = solelyTextureViewUpdates,
663                     .skippedFrameVsyncId = mSkippedFrameInfo ? mSkippedFrameInfo->vsyncId
664                                                              : UiFrameInfoBuilder::INVALID_VSYNC_ID,
665                     .skippedFrameStartTimeNanos =
666                             mSkippedFrameInfo ? mSkippedFrameInfo->startTime : 0,
667             };
668             native_window_set_frame_timeline_info(mNativeSurface->getNativeWindow(), ftl);
669         }
670     }
671 
672     bool requireSwap = false;
673     bool didDraw = false;
674 
675     int error = OK;
676     bool didSwap = mRenderPipeline->swapBuffers(frame, drawResult, windowDirty, mCurrentFrameInfo,
677                                                 &requireSwap);
678 
679     mCurrentFrameInfo->set(FrameInfoIndex::CommandSubmissionCompleted) = std::max(
680             drawResult.commandSubmissionTime, mCurrentFrameInfo->get(FrameInfoIndex::SwapBuffers));
681 
682     mIsDirty = false;
683 
684     if (requireSwap) {
685         didDraw = true;
686         // Handle any swapchain errors
687         error = mNativeSurface->getAndClearError();
688         if (error == TIMED_OUT) {
689             // Try again
690             mRenderThread.postFrameCallback(this);
691             // But since this frame didn't happen, we need to mark full damage in the swap
692             // history
693             didDraw = false;
694 
695         } else if (error != OK || !didSwap) {
696             // Unknown error, abandon the surface
697             setSurface(nullptr);
698             didDraw = false;
699         }
700 
701         SwapHistory& swap = mSwapHistory.next();
702         if (didDraw) {
703             swap.damage = windowDirty;
704         } else {
705             float max = static_cast<float>(INT_MAX);
706             swap.damage = SkRect::MakeWH(max, max);
707         }
708         swap.swapCompletedTime = systemTime(SYSTEM_TIME_MONOTONIC);
709         swap.vsyncTime = mRenderThread.timeLord().latestVsync();
710         if (didDraw) {
711             nsecs_t dequeueStart =
712                     ANativeWindow_getLastDequeueStartTime(mNativeSurface->getNativeWindow());
713             if (dequeueStart < mCurrentFrameInfo->get(FrameInfoIndex::SyncStart)) {
714                 // Ignoring dequeue duration as it happened prior to frame render start
715                 // and thus is not part of the frame.
716                 swap.dequeueDuration = 0;
717             } else {
718                 swap.dequeueDuration =
719                         ANativeWindow_getLastDequeueDuration(mNativeSurface->getNativeWindow());
720             }
721             swap.queueDuration =
722                     ANativeWindow_getLastQueueDuration(mNativeSurface->getNativeWindow());
723         } else {
724             swap.dequeueDuration = 0;
725             swap.queueDuration = 0;
726         }
727         mCurrentFrameInfo->set(FrameInfoIndex::DequeueBufferDuration) = swap.dequeueDuration;
728         mCurrentFrameInfo->set(FrameInfoIndex::QueueBufferDuration) = swap.queueDuration;
729         mHaveNewSurface = false;
730         mFrameNumber = 0;
731     } else {
732         mCurrentFrameInfo->set(FrameInfoIndex::DequeueBufferDuration) = 0;
733         mCurrentFrameInfo->set(FrameInfoIndex::QueueBufferDuration) = 0;
734     }
735 
736     mCurrentFrameInfo->markSwapBuffersCompleted();
737 
738 #if LOG_FRAMETIME_MMA
739     float thisFrame = mCurrentFrameInfo->duration(FrameInfoIndex::IssueDrawCommandsStart,
740                                                   FrameInfoIndex::FrameCompleted) /
741                       NANOS_PER_MILLIS_F;
742     if (sFrameCount) {
743         sBenchMma = ((9 * sBenchMma) + thisFrame) / 10;
744     } else {
745         sBenchMma = thisFrame;
746     }
747     if (++sFrameCount == 10) {
748         sFrameCount = 1;
749         ALOGD("Average frame time: %.4f", sBenchMma);
750     }
751 #endif
752 
753     if (didSwap) {
754         for (auto& func : mFrameCommitCallbacks) {
755             std::invoke(func, true /* didProduceBuffer */);
756         }
757         mFrameCommitCallbacks.clear();
758     }
759 
760     if (requireSwap) {
761         if (mExpectSurfaceStats) {
762             reportMetricsWithPresentTime();
763             {  // acquire lock
764                 std::lock_guard lock(mLast4FrameMetricsInfosMutex);
765                 FrameMetricsInfo& next = mLast4FrameMetricsInfos.next();
766                 next.frameInfo = mCurrentFrameInfo;
767                 next.frameNumber = frameCompleteNr;
768                 next.surfaceId = mSurfaceControlGenerationId;
769             }  // release lock
770         } else {
771             mCurrentFrameInfo->markFrameCompleted();
772             mCurrentFrameInfo->set(FrameInfoIndex::GpuCompleted)
773                     = mCurrentFrameInfo->get(FrameInfoIndex::FrameCompleted);
774             std::scoped_lock lock(mFrameInfoMutex);
775             mJankTracker.finishFrame(*mCurrentFrameInfo, mFrameMetricsReporter, frameCompleteNr,
776                                      mSurfaceControlGenerationId);
777         }
778     }
779 
780     int64_t intendedVsync = mCurrentFrameInfo->get(FrameInfoIndex::IntendedVsync);
781     int64_t frameDeadline = mCurrentFrameInfo->get(FrameInfoIndex::FrameDeadline);
782     int64_t dequeueBufferDuration = mCurrentFrameInfo->get(FrameInfoIndex::DequeueBufferDuration);
783 
784     mHintSessionWrapper->updateTargetWorkDuration(frameDeadline - intendedVsync);
785 
786     if (didDraw) {
787         int64_t frameStartTime = mCurrentFrameInfo->get(FrameInfoIndex::FrameStartTime);
788         int64_t frameDuration = systemTime(SYSTEM_TIME_MONOTONIC) - frameStartTime;
789         int64_t actualDuration = frameDuration -
790                                  (std::min(syncDelayDuration, mLastDequeueBufferDuration)) -
791                                  dequeueBufferDuration - idleDuration;
792         mHintSessionWrapper->reportActualWorkDuration(actualDuration);
793         mHintSessionWrapper->setActiveFunctorThreads(
794                 WebViewFunctorManager::instance().getRenderingThreadsForActiveFunctors());
795     }
796 
797     mLastDequeueBufferDuration = dequeueBufferDuration;
798 
799     mRenderThread.cacheManager().onFrameCompleted();
800     return;
801 }
802 
reportMetricsWithPresentTime()803 void CanvasContext::reportMetricsWithPresentTime() {
804     {  // acquire lock
805         std::scoped_lock lock(mFrameInfoMutex);
806         if (mFrameMetricsReporter == nullptr) {
807             return;
808         }
809     }  // release lock
810     if (mNativeSurface == nullptr) {
811         return;
812     }
813     ATRACE_CALL();
814     FrameInfo* forthBehind;
815     int64_t frameNumber;
816     int32_t surfaceControlId;
817 
818     {  // acquire lock
819         std::scoped_lock lock(mLast4FrameMetricsInfosMutex);
820         if (mLast4FrameMetricsInfos.size() != mLast4FrameMetricsInfos.capacity()) {
821             // Not enough frames yet
822             return;
823         }
824         auto frameMetricsInfo = mLast4FrameMetricsInfos.front();
825         forthBehind = frameMetricsInfo.frameInfo;
826         frameNumber = frameMetricsInfo.frameNumber;
827         surfaceControlId = frameMetricsInfo.surfaceId;
828     }  // release lock
829 
830     nsecs_t presentTime = 0;
831     native_window_get_frame_timestamps(
832             mNativeSurface->getNativeWindow(), frameNumber, nullptr /*outRequestedPresentTime*/,
833             nullptr /*outAcquireTime*/, nullptr /*outLatchTime*/,
834             nullptr /*outFirstRefreshStartTime*/, nullptr /*outLastRefreshStartTime*/,
835             nullptr /*outGpuCompositionDoneTime*/, &presentTime, nullptr /*outDequeueReadyTime*/,
836             nullptr /*outReleaseTime*/);
837 
838     forthBehind->set(FrameInfoIndex::DisplayPresentTime) = presentTime;
839     {  // acquire lock
840         std::scoped_lock lock(mFrameInfoMutex);
841         if (mFrameMetricsReporter != nullptr) {
842             mFrameMetricsReporter->reportFrameMetrics(forthBehind->data(), true /*hasPresentTime*/,
843                                                       frameNumber, surfaceControlId);
844         }
845     }  // release lock
846 }
847 
addFrameMetricsObserver(FrameMetricsObserver * observer)848 void CanvasContext::addFrameMetricsObserver(FrameMetricsObserver* observer) {
849     std::scoped_lock lock(mFrameInfoMutex);
850     if (mFrameMetricsReporter.get() == nullptr) {
851         mFrameMetricsReporter.reset(new FrameMetricsReporter());
852     }
853 
854     // We want to make sure we aren't reporting frames that have already been queued by the
855     // BufferQueueProducer on the rendner thread but are still pending the callback to report their
856     // their frame metrics.
857     uint64_t nextFrameNumber = getFrameNumber();
858     observer->reportMetricsFrom(nextFrameNumber, mSurfaceControlGenerationId);
859     mFrameMetricsReporter->addObserver(observer);
860 }
861 
removeFrameMetricsObserver(FrameMetricsObserver * observer)862 void CanvasContext::removeFrameMetricsObserver(FrameMetricsObserver* observer) {
863     std::scoped_lock lock(mFrameInfoMutex);
864     if (mFrameMetricsReporter.get() != nullptr) {
865         mFrameMetricsReporter->removeObserver(observer);
866         if (!mFrameMetricsReporter->hasObservers()) {
867             mFrameMetricsReporter.reset(nullptr);
868         }
869     }
870 }
871 
getFrameInfoFromLast4(uint64_t frameNumber,uint32_t surfaceControlId)872 FrameInfo* CanvasContext::getFrameInfoFromLast4(uint64_t frameNumber, uint32_t surfaceControlId) {
873     std::scoped_lock lock(mLast4FrameMetricsInfosMutex);
874     for (size_t i = 0; i < mLast4FrameMetricsInfos.size(); i++) {
875         if (mLast4FrameMetricsInfos[i].frameNumber == frameNumber &&
876             mLast4FrameMetricsInfos[i].surfaceId == surfaceControlId) {
877             return mLast4FrameMetricsInfos[i].frameInfo;
878         }
879     }
880 
881     return nullptr;
882 }
883 
onSurfaceStatsAvailable(void * context,int32_t surfaceControlId,ASurfaceControlStats * stats)884 void CanvasContext::onSurfaceStatsAvailable(void* context, int32_t surfaceControlId,
885                                             ASurfaceControlStats* stats) {
886     auto* instance = static_cast<CanvasContext*>(context);
887 
888     const ASurfaceControlFunctions& functions =
889             instance->mRenderThread.getASurfaceControlFunctions();
890 
891     nsecs_t gpuCompleteTime = functions.getAcquireTimeFunc(stats);
892     if (gpuCompleteTime == Fence::SIGNAL_TIME_PENDING) {
893         gpuCompleteTime = -1;
894     }
895     uint64_t frameNumber = functions.getFrameNumberFunc(stats);
896 
897     FrameInfo* frameInfo = instance->getFrameInfoFromLast4(frameNumber, surfaceControlId);
898 
899     if (frameInfo != nullptr) {
900         std::scoped_lock lock(instance->mFrameInfoMutex);
901         frameInfo->set(FrameInfoIndex::FrameCompleted) = std::max(gpuCompleteTime,
902                 frameInfo->get(FrameInfoIndex::SwapBuffersCompleted));
903         frameInfo->set(FrameInfoIndex::GpuCompleted) = std::max(
904                 gpuCompleteTime, frameInfo->get(FrameInfoIndex::CommandSubmissionCompleted));
905         instance->mJankTracker.finishFrame(*frameInfo, instance->mFrameMetricsReporter, frameNumber,
906                                            surfaceControlId);
907     }
908 }
909 
910 // Called by choreographer to do an RT-driven animation
doFrame()911 void CanvasContext::doFrame() {
912     if (!mRenderPipeline->isSurfaceReady()) return;
913     mIdleDuration =
914             systemTime(SYSTEM_TIME_MONOTONIC) - mRenderThread.timeLord().computeFrameTimeNanos();
915     prepareAndDraw(nullptr);
916 }
917 
getNextFrameSize() const918 SkISize CanvasContext::getNextFrameSize() const {
919     static constexpr SkISize defaultFrameSize = {INT32_MAX, INT32_MAX};
920     if (mNativeSurface == nullptr) {
921         return defaultFrameSize;
922     }
923     ANativeWindow* anw = mNativeSurface->getNativeWindow();
924 
925     SkISize size;
926     size.fWidth = ANativeWindow_getWidth(anw);
927     size.fHeight = ANativeWindow_getHeight(anw);
928     mRenderThread.cacheManager().notifyNextFrameSize(size.fWidth, size.fHeight);
929     return size;
930 }
931 
getPixelSnapMatrix() const932 const SkM44& CanvasContext::getPixelSnapMatrix() const {
933     return mRenderPipeline->getPixelSnapMatrix();
934 }
935 
prepareAndDraw(RenderNode * node)936 void CanvasContext::prepareAndDraw(RenderNode* node) {
937     int64_t vsyncId = mRenderThread.timeLord().lastVsyncId();
938     ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
939 
940     nsecs_t vsync = mRenderThread.timeLord().computeFrameTimeNanos();
941     int64_t frameDeadline = mRenderThread.timeLord().lastFrameDeadline();
942     int64_t frameInterval = mRenderThread.timeLord().frameIntervalNanos();
943     int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE];
944     UiFrameInfoBuilder(frameInfo)
945         .addFlag(FrameInfoFlags::RTAnimation)
946         .setVsync(vsync, vsync, vsyncId, frameDeadline, frameInterval);
947 
948     TreeInfo info(TreeInfo::MODE_RT_ONLY, *this);
949     prepareTree(info, frameInfo, systemTime(SYSTEM_TIME_MONOTONIC), node);
950     if (!info.out.skippedFrameReason) {
951         draw(info.out.solelyTextureViewUpdates);
952     } else {
953         // wait on fences so tasks don't overlap next frame
954         waitOnFences();
955     }
956 }
957 
markLayerInUse(RenderNode * node)958 void CanvasContext::markLayerInUse(RenderNode* node) {
959     if (mPrefetchedLayers.erase(node)) {
960         node->decStrong(nullptr);
961     }
962 }
963 
freePrefetchedLayers()964 void CanvasContext::freePrefetchedLayers() {
965     if (mPrefetchedLayers.size()) {
966         for (auto& node : mPrefetchedLayers) {
967             ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...",
968                   node->getName());
969             node->destroyLayers();
970             node->decStrong(nullptr);
971         }
972         mPrefetchedLayers.clear();
973     }
974 }
975 
buildLayer(RenderNode * node)976 void CanvasContext::buildLayer(RenderNode* node) {
977     ATRACE_CALL();
978     if (!mRenderPipeline->isContextReady()) return;
979 
980     // buildLayer() will leave the tree in an unknown state, so we must stop drawing
981     stopDrawing();
982 
983     ScopedActiveContext activeContext(this);
984     TreeInfo info(TreeInfo::MODE_FULL, *this);
985     info.damageAccumulator = &mDamageAccumulator;
986     info.layerUpdateQueue = &mLayerUpdateQueue;
987     info.runAnimations = false;
988     node->prepareTree(info);
989     SkRect ignore;
990     mDamageAccumulator.finish(&ignore);
991     // Tickle the GENERIC property on node to mark it as dirty for damaging
992     // purposes when the frame is actually drawn
993     node->setPropertyFieldsDirty(RenderNode::GENERIC);
994 
995     mRenderPipeline->renderLayers(mLightGeometry, &mLayerUpdateQueue, mOpaque, mLightInfo);
996 
997     node->incStrong(nullptr);
998     mPrefetchedLayers.insert(node);
999 }
1000 
destroyHardwareResources()1001 void CanvasContext::destroyHardwareResources() {
1002     stopDrawing();
1003     if (mRenderPipeline->isContextReady()) {
1004         freePrefetchedLayers();
1005         for (const sp<RenderNode>& node : mRenderNodes) {
1006             node->destroyHardwareResources();
1007         }
1008         mRenderPipeline->onDestroyHardwareResources();
1009     }
1010 }
1011 
onContextDestroyed()1012 void CanvasContext::onContextDestroyed() {
1013     // We don't want to destroyHardwareResources as that will invalidate display lists which
1014     // the client may not be expecting. Instead just purge all scratch resources
1015     if (mRenderPipeline->isContextReady()) {
1016         freePrefetchedLayers();
1017         for (const sp<RenderNode>& node : mRenderNodes) {
1018             node->destroyLayers();
1019         }
1020         mRenderPipeline->onDestroyHardwareResources();
1021     }
1022 }
1023 
createTextureLayer()1024 DeferredLayerUpdater* CanvasContext::createTextureLayer() {
1025     return mRenderPipeline->createTextureLayer();
1026 }
1027 
dumpFrames(int fd)1028 void CanvasContext::dumpFrames(int fd) {
1029     mJankTracker.dumpStats(fd);
1030     mJankTracker.dumpFrames(fd);
1031 }
1032 
resetFrameStats()1033 void CanvasContext::resetFrameStats() {
1034     mJankTracker.reset();
1035 }
1036 
setName(const std::string && name)1037 void CanvasContext::setName(const std::string&& name) {
1038     mJankTracker.setDescription(JankTrackerType::Window, std::move(name));
1039 }
1040 
waitOnFences()1041 void CanvasContext::waitOnFences() {
1042     if (mFrameFences.size()) {
1043         ATRACE_CALL();
1044         for (auto& fence : mFrameFences) {
1045             fence.get();
1046         }
1047         mFrameFences.clear();
1048     }
1049 }
1050 
enqueueFrameWork(std::function<void ()> && func)1051 void CanvasContext::enqueueFrameWork(std::function<void()>&& func) {
1052     mFrameFences.push_back(CommonPool::async(std::move(func)));
1053 }
1054 
getFrameNumber()1055 uint64_t CanvasContext::getFrameNumber() {
1056     // mFrameNumber is reset to 0 when the surface changes or we swap buffers
1057     if (mFrameNumber == 0 && mNativeSurface.get()) {
1058         mFrameNumber = ANativeWindow_getNextFrameId(mNativeSurface->getNativeWindow());
1059     }
1060     return mFrameNumber;
1061 }
1062 
surfaceRequiresRedraw()1063 bool CanvasContext::surfaceRequiresRedraw() {
1064     if (!mNativeSurface) return false;
1065     if (mHaveNewSurface) return true;
1066 
1067     ANativeWindow* anw = mNativeSurface->getNativeWindow();
1068     const int width = ANativeWindow_getWidth(anw);
1069     const int height = ANativeWindow_getHeight(anw);
1070 
1071     return width != mLastFrameWidth || height != mLastFrameHeight;
1072 }
1073 
computeDirtyRect(const Frame & frame,SkRect * dirty)1074 SkRect CanvasContext::computeDirtyRect(const Frame& frame, SkRect* dirty) {
1075     if (frame.width() != mLastFrameWidth || frame.height() != mLastFrameHeight) {
1076         // can't rely on prior content of window if viewport size changes
1077         dirty->setEmpty();
1078         mLastFrameWidth = frame.width();
1079         mLastFrameHeight = frame.height();
1080     } else if (mHaveNewSurface || frame.bufferAge() == 0) {
1081         // New surface needs a full draw
1082         dirty->setEmpty();
1083     } else {
1084         if (!dirty->isEmpty() && !dirty->intersect(SkRect::MakeIWH(frame.width(), frame.height()))) {
1085             ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?", SK_RECT_ARGS(*dirty),
1086                   frame.width(), frame.height());
1087             dirty->setEmpty();
1088         }
1089         profiler().unionDirty(dirty);
1090     }
1091 
1092     if (dirty->isEmpty()) {
1093         dirty->setIWH(frame.width(), frame.height());
1094         return *dirty;
1095     }
1096 
1097     // At this point dirty is the area of the window to update. However,
1098     // the area of the frame we need to repaint is potentially different, so
1099     // stash the screen area for later
1100     SkRect windowDirty(*dirty);
1101 
1102     // If the buffer age is 0 we do a full-screen repaint (handled above)
1103     // If the buffer age is 1 the buffer contents are the same as they were
1104     // last frame so there's nothing to union() against
1105     // Therefore we only care about the > 1 case.
1106     if (frame.bufferAge() > 1) {
1107         if (frame.bufferAge() > (int)mSwapHistory.size()) {
1108             // We don't have enough history to handle this old of a buffer
1109             // Just do a full-draw
1110             dirty->setIWH(frame.width(), frame.height());
1111         } else {
1112             // At this point we haven't yet added the latest frame
1113             // to the damage history (happens below)
1114             // So we need to damage
1115             for (int i = mSwapHistory.size() - 1;
1116                  i > ((int)mSwapHistory.size()) - frame.bufferAge(); i--) {
1117                 dirty->join(mSwapHistory[i].damage);
1118             }
1119         }
1120     }
1121 
1122     return windowDirty;
1123 }
1124 
getActiveContext()1125 CanvasContext* CanvasContext::getActiveContext() {
1126     return ScopedActiveContext::getActiveContext();
1127 }
1128 
mergeTransaction(ASurfaceTransaction * transaction,ASurfaceControl * control)1129 bool CanvasContext::mergeTransaction(ASurfaceTransaction* transaction, ASurfaceControl* control) {
1130     if (!mASurfaceTransactionCallback) return false;
1131     return std::invoke(mASurfaceTransactionCallback, reinterpret_cast<int64_t>(transaction),
1132                        reinterpret_cast<int64_t>(control), getFrameNumber());
1133 }
1134 
prepareSurfaceControlForWebview()1135 void CanvasContext::prepareSurfaceControlForWebview() {
1136     if (mPrepareSurfaceControlForWebviewCallback) {
1137         std::invoke(mPrepareSurfaceControlForWebviewCallback);
1138     }
1139 }
1140 
sendLoadResetHint()1141 void CanvasContext::sendLoadResetHint() {
1142     mHintSessionWrapper->sendLoadResetHint();
1143 }
1144 
sendLoadIncreaseHint()1145 void CanvasContext::sendLoadIncreaseHint() {
1146     mHintSessionWrapper->sendLoadIncreaseHint();
1147 }
1148 
setSyncDelayDuration(nsecs_t duration)1149 void CanvasContext::setSyncDelayDuration(nsecs_t duration) {
1150     mSyncDelayDuration = duration;
1151 }
1152 
startHintSession()1153 void CanvasContext::startHintSession() {
1154     mHintSessionWrapper->init();
1155 }
1156 
shouldDither()1157 bool CanvasContext::shouldDither() {
1158     CanvasContext* self = getActiveContext();
1159     if (!self) return false;
1160     return self->mColorMode != ColorMode::Default;
1161 }
1162 
visitAllRenderNodes(std::function<void (const RenderNode &)> func) const1163 void CanvasContext::visitAllRenderNodes(std::function<void(const RenderNode&)> func) const {
1164     for (auto node : mRenderNodes) {
1165         node->visit(func);
1166     }
1167 }
1168 
1169 } /* namespace renderthread */
1170 } /* namespace uirenderer */
1171 } /* namespace android */
1172