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 // Make sure we have a valid device info
422 if (!DeviceInfo::get()->hasMaxTextureSize()) {
423 (void)mRenderThread.requireGrContext();
424 }
425
426 // If the previous frame was dropped we don't need to hold onto it, so
427 // just keep using the previous frame's structure instead
428 const auto reason = wasSkipped(mCurrentFrameInfo);
429 if (reason.has_value()) {
430 // Use the oldest skipped frame in case we skip more than a single frame
431 if (!mSkippedFrameInfo) {
432 switch (*reason) {
433 case SkippedFrameReason::AlreadyDrawn:
434 case SkippedFrameReason::NoBuffer:
435 case SkippedFrameReason::NoOutputTarget:
436 mSkippedFrameInfo.emplace();
437 mSkippedFrameInfo->vsyncId =
438 mCurrentFrameInfo->get(FrameInfoIndex::FrameTimelineVsyncId);
439 mSkippedFrameInfo->startTime =
440 mCurrentFrameInfo->get(FrameInfoIndex::FrameStartTime);
441 break;
442 case SkippedFrameReason::DrawingOff:
443 case SkippedFrameReason::ContextIsStopped:
444 case SkippedFrameReason::NothingToDraw:
445 // Do not report those as skipped frames as there was no frame expected to be
446 // drawn
447 break;
448 }
449 }
450 } else {
451 mCurrentFrameInfo = mJankTracker.startFrame();
452 mSkippedFrameInfo.reset();
453 }
454
455 mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo);
456 mCurrentFrameInfo->set(FrameInfoIndex::SyncQueued) = syncQueued;
457 mCurrentFrameInfo->markSyncStart();
458
459 info.damageAccumulator = &mDamageAccumulator;
460 info.layerUpdateQueue = &mLayerUpdateQueue;
461 info.damageGenerationId = mDamageId++;
462 info.out.skippedFrameReason = std::nullopt;
463
464 mAnimationContext->startFrame(info.mode);
465 for (const sp<RenderNode>& node : mRenderNodes) {
466 // Only the primary target node will be drawn full - all other nodes would get drawn in
467 // real time mode. In case of a window, the primary node is the window content and the other
468 // node(s) are non client / filler nodes.
469 info.mode = (node.get() == target ? TreeInfo::MODE_FULL : TreeInfo::MODE_RT_ONLY);
470 node->prepareTree(info);
471 GL_CHECKPOINT(MODERATE);
472 }
473 mAnimationContext->runRemainingAnimations(info);
474 GL_CHECKPOINT(MODERATE);
475
476 freePrefetchedLayers();
477 GL_CHECKPOINT(MODERATE);
478
479 mIsDirty = true;
480
481 if (CC_UNLIKELY(!hasOutputTarget())) {
482 info.out.skippedFrameReason = SkippedFrameReason::NoOutputTarget;
483 mCurrentFrameInfo->setSkippedFrameReason(*info.out.skippedFrameReason);
484 return;
485 }
486
487 if (CC_LIKELY(mSwapHistory.size() && !info.forceDrawFrame)) {
488 nsecs_t latestVsync = mRenderThread.timeLord().latestVsync();
489 SwapHistory& lastSwap = mSwapHistory.back();
490 nsecs_t vsyncDelta = std::abs(lastSwap.vsyncTime - latestVsync);
491 // The slight fudge-factor is to deal with cases where
492 // the vsync was estimated due to being slow handling the signal.
493 // See the logic in TimeLord#computeFrameTimeNanos or in
494 // Choreographer.java for details on when this happens
495 if (vsyncDelta < 2_ms) {
496 // Already drew for this vsync pulse, UI draw request missed
497 // the deadline for RT animations
498 info.out.skippedFrameReason = SkippedFrameReason::AlreadyDrawn;
499 }
500 } else {
501 info.out.skippedFrameReason = std::nullopt;
502 }
503
504 // TODO: Do we need to abort out if the backdrop is added but not ready? Should that even
505 // be an allowable combination?
506 if (mRenderNodes.size() > 2 && !mRenderNodes[1]->isRenderable()) {
507 info.out.skippedFrameReason = SkippedFrameReason::NothingToDraw;
508 }
509
510 if (!info.out.skippedFrameReason) {
511 int err = mNativeSurface->reserveNext();
512 if (err != OK) {
513 info.out.skippedFrameReason = SkippedFrameReason::NoBuffer;
514 mCurrentFrameInfo->setSkippedFrameReason(*info.out.skippedFrameReason);
515 ALOGW("reserveNext failed, error = %d (%s)", err, strerror(-err));
516 if (err != TIMED_OUT) {
517 // A timed out surface can still recover, but assume others are permanently dead.
518 setSurface(nullptr);
519 return;
520 }
521 }
522 } else {
523 mCurrentFrameInfo->setSkippedFrameReason(*info.out.skippedFrameReason);
524 }
525
526 bool postedFrameCallback = false;
527 if (info.out.hasAnimations || info.out.skippedFrameReason) {
528 if (CC_UNLIKELY(!Properties::enableRTAnimations)) {
529 info.out.requiresUiRedraw = true;
530 }
531 if (!info.out.requiresUiRedraw) {
532 // If animationsNeedsRedraw is set don't bother posting for an RT anim
533 // as we will just end up fighting the UI thread.
534 mRenderThread.postFrameCallback(this);
535 postedFrameCallback = true;
536 }
537 }
538
539 if (!postedFrameCallback &&
540 info.out.animatedImageDelay != TreeInfo::Out::kNoAnimatedImageDelay) {
541 // Subtract the time of one frame so it can be displayed on time.
542 const nsecs_t kFrameTime = mRenderThread.timeLord().frameIntervalNanos();
543 if (info.out.animatedImageDelay <= kFrameTime) {
544 mRenderThread.postFrameCallback(this);
545 } else {
546 const auto delay = info.out.animatedImageDelay - kFrameTime;
547 int genId = mGenerationID;
548 mRenderThread.queue().postDelayed(delay, [this, genId]() {
549 if (mGenerationID == genId) {
550 mRenderThread.postFrameCallback(this);
551 }
552 });
553 }
554 }
555 }
556
stopDrawing()557 void CanvasContext::stopDrawing() {
558 mRenderThread.removeFrameCallback(this);
559 mAnimationContext->pauseAnimators();
560 mGenerationID++;
561 }
562
notifyFramePending()563 void CanvasContext::notifyFramePending() {
564 ATRACE_CALL();
565 mRenderThread.pushBackFrameCallback(this);
566 sendLoadResetHint();
567 }
568
getFrame()569 Frame CanvasContext::getFrame() {
570 if (mHardwareBuffer != nullptr) {
571 return {mBufferParams.getLogicalWidth(), mBufferParams.getLogicalHeight(), 0};
572 } else {
573 return mRenderPipeline->getFrame();
574 }
575 }
576
draw(bool solelyTextureViewUpdates)577 void CanvasContext::draw(bool solelyTextureViewUpdates) {
578 #ifdef __ANDROID__
579 if (auto grContext = getGrContext()) {
580 if (grContext->abandoned()) {
581 if (grContext->isDeviceLost()) {
582 LOG_ALWAYS_FATAL("Lost GPU device unexpectedly");
583 return;
584 }
585 LOG_ALWAYS_FATAL("GrContext is abandoned at start of CanvasContext::draw");
586 return;
587 }
588 }
589 #endif
590 SkRect dirty;
591 mDamageAccumulator.finish(&dirty);
592
593 // reset syncDelayDuration each time we draw
594 nsecs_t syncDelayDuration = mSyncDelayDuration;
595 nsecs_t idleDuration = mIdleDuration;
596 mSyncDelayDuration = 0;
597 mIdleDuration = 0;
598
599 const auto skippedFrameReason = [&]() -> std::optional<SkippedFrameReason> {
600 if (!Properties::isDrawingEnabled()) {
601 return SkippedFrameReason::DrawingOff;
602 }
603
604 if (dirty.isEmpty() && Properties::skipEmptyFrames && !surfaceRequiresRedraw()) {
605 return SkippedFrameReason::NothingToDraw;
606 }
607
608 return std::nullopt;
609 }();
610 if (skippedFrameReason) {
611 mCurrentFrameInfo->setSkippedFrameReason(*skippedFrameReason);
612
613 #ifdef __ANDROID__
614 if (auto grContext = getGrContext()) {
615 // Submit to ensure that any texture uploads complete and Skia can
616 // free its staging buffers.
617 grContext->flushAndSubmit();
618 }
619 #endif
620
621 // Notify the callbacks, even if there's nothing to draw so they aren't waiting
622 // indefinitely
623 waitOnFences();
624 for (auto& func : mFrameCommitCallbacks) {
625 std::invoke(func, false /* didProduceBuffer */);
626 }
627 mFrameCommitCallbacks.clear();
628 return;
629 }
630
631 ScopedActiveContext activeContext(this);
632 mCurrentFrameInfo->set(FrameInfoIndex::FrameInterval) =
633 mRenderThread.timeLord().frameIntervalNanos();
634
635 mCurrentFrameInfo->markIssueDrawCommandsStart();
636
637 Frame frame = getFrame();
638
639 SkRect windowDirty = computeDirtyRect(frame, &dirty);
640
641 ATRACE_FORMAT("Drawing " RECT_STRING, SK_RECT_ARGS(dirty));
642
643 IRenderPipeline::DrawResult drawResult;
644 {
645 // FrameInfoVisualizer accesses the frame events, which cannot be mutated mid-draw
646 // or it can lead to memory corruption.
647 drawResult = mRenderPipeline->draw(
648 frame, windowDirty, dirty, mLightGeometry, &mLayerUpdateQueue, mContentDrawBounds,
649 mOpaque, mLightInfo, mRenderNodes, &(profiler()), mBufferParams, profilerLock());
650 }
651
652 uint64_t frameCompleteNr = getFrameNumber();
653
654 waitOnFences();
655
656 if (mNativeSurface) {
657 // TODO(b/165985262): measure performance impact
658 const auto vsyncId = mCurrentFrameInfo->get(FrameInfoIndex::FrameTimelineVsyncId);
659 if (vsyncId != UiFrameInfoBuilder::INVALID_VSYNC_ID) {
660 const auto inputEventId =
661 static_cast<int32_t>(mCurrentFrameInfo->get(FrameInfoIndex::InputEventId));
662 ATRACE_FORMAT(
663 "frameTimelineInfo(frameNumber=%llu, vsyncId=%lld, inputEventId=0x%" PRIx32 ")",
664 frameCompleteNr, vsyncId, inputEventId);
665 const ANativeWindowFrameTimelineInfo ftl = {
666 .frameNumber = frameCompleteNr,
667 .frameTimelineVsyncId = vsyncId,
668 .inputEventId = inputEventId,
669 .startTimeNanos = mCurrentFrameInfo->get(FrameInfoIndex::FrameStartTime),
670 .useForRefreshRateSelection = solelyTextureViewUpdates,
671 .skippedFrameVsyncId = mSkippedFrameInfo ? mSkippedFrameInfo->vsyncId
672 : UiFrameInfoBuilder::INVALID_VSYNC_ID,
673 .skippedFrameStartTimeNanos =
674 mSkippedFrameInfo ? mSkippedFrameInfo->startTime : 0,
675 };
676 native_window_set_frame_timeline_info(mNativeSurface->getNativeWindow(), ftl);
677 }
678 }
679
680 bool requireSwap = false;
681 bool didDraw = false;
682
683 int error = OK;
684 bool didSwap = mRenderPipeline->swapBuffers(frame, drawResult, windowDirty, mCurrentFrameInfo,
685 &requireSwap);
686
687 mCurrentFrameInfo->set(FrameInfoIndex::CommandSubmissionCompleted) = std::max(
688 drawResult.commandSubmissionTime, mCurrentFrameInfo->get(FrameInfoIndex::SwapBuffers));
689
690 mIsDirty = false;
691
692 if (requireSwap) {
693 didDraw = true;
694 // Handle any swapchain errors
695 error = mNativeSurface->getAndClearError();
696 if (error == TIMED_OUT) {
697 // Try again
698 mRenderThread.postFrameCallback(this);
699 // But since this frame didn't happen, we need to mark full damage in the swap
700 // history
701 didDraw = false;
702
703 } else if (error != OK || !didSwap) {
704 // Unknown error, abandon the surface
705 setSurface(nullptr);
706 didDraw = false;
707 }
708
709 SwapHistory& swap = mSwapHistory.next();
710 if (didDraw) {
711 swap.damage = windowDirty;
712 } else {
713 float max = static_cast<float>(INT_MAX);
714 swap.damage = SkRect::MakeWH(max, max);
715 }
716 swap.swapCompletedTime = systemTime(SYSTEM_TIME_MONOTONIC);
717 swap.vsyncTime = mRenderThread.timeLord().latestVsync();
718 if (didDraw) {
719 nsecs_t dequeueStart =
720 ANativeWindow_getLastDequeueStartTime(mNativeSurface->getNativeWindow());
721 if (dequeueStart < mCurrentFrameInfo->get(FrameInfoIndex::SyncStart)) {
722 // Ignoring dequeue duration as it happened prior to frame render start
723 // and thus is not part of the frame.
724 swap.dequeueDuration = 0;
725 } else {
726 swap.dequeueDuration =
727 ANativeWindow_getLastDequeueDuration(mNativeSurface->getNativeWindow());
728 }
729 swap.queueDuration =
730 ANativeWindow_getLastQueueDuration(mNativeSurface->getNativeWindow());
731 } else {
732 swap.dequeueDuration = 0;
733 swap.queueDuration = 0;
734 }
735 mCurrentFrameInfo->set(FrameInfoIndex::DequeueBufferDuration) = swap.dequeueDuration;
736 mCurrentFrameInfo->set(FrameInfoIndex::QueueBufferDuration) = swap.queueDuration;
737 mHaveNewSurface = false;
738 mFrameNumber = 0;
739 } else {
740 mCurrentFrameInfo->set(FrameInfoIndex::DequeueBufferDuration) = 0;
741 mCurrentFrameInfo->set(FrameInfoIndex::QueueBufferDuration) = 0;
742 }
743
744 mCurrentFrameInfo->markSwapBuffersCompleted();
745
746 #if LOG_FRAMETIME_MMA
747 float thisFrame = mCurrentFrameInfo->duration(FrameInfoIndex::IssueDrawCommandsStart,
748 FrameInfoIndex::FrameCompleted) /
749 NANOS_PER_MILLIS_F;
750 if (sFrameCount) {
751 sBenchMma = ((9 * sBenchMma) + thisFrame) / 10;
752 } else {
753 sBenchMma = thisFrame;
754 }
755 if (++sFrameCount == 10) {
756 sFrameCount = 1;
757 ALOGD("Average frame time: %.4f", sBenchMma);
758 }
759 #endif
760
761 if (didSwap) {
762 for (auto& func : mFrameCommitCallbacks) {
763 std::invoke(func, true /* didProduceBuffer */);
764 }
765 mFrameCommitCallbacks.clear();
766 }
767
768 if (requireSwap) {
769 if (mExpectSurfaceStats) {
770 reportMetricsWithPresentTime();
771 { // acquire lock
772 std::lock_guard lock(mLastFrameMetricsInfosMutex);
773 FrameMetricsInfo& next = mLastFrameMetricsInfos.next();
774 next.frameInfo = mCurrentFrameInfo;
775 next.frameNumber = frameCompleteNr;
776 next.surfaceId = mSurfaceControlGenerationId;
777 } // release lock
778 } else {
779 mCurrentFrameInfo->markFrameCompleted();
780 mCurrentFrameInfo->set(FrameInfoIndex::GpuCompleted)
781 = mCurrentFrameInfo->get(FrameInfoIndex::FrameCompleted);
782 std::scoped_lock lock(mFrameInfoMutex);
783 mJankTracker.finishFrame(*mCurrentFrameInfo, mFrameMetricsReporter, frameCompleteNr,
784 mSurfaceControlGenerationId);
785 }
786 }
787
788 int64_t intendedVsync = mCurrentFrameInfo->get(FrameInfoIndex::IntendedVsync);
789 int64_t frameDeadline = mCurrentFrameInfo->get(FrameInfoIndex::FrameDeadline);
790 int64_t dequeueBufferDuration = mCurrentFrameInfo->get(FrameInfoIndex::DequeueBufferDuration);
791
792 mHintSessionWrapper->updateTargetWorkDuration(frameDeadline - intendedVsync);
793
794 if (didDraw) {
795 int64_t frameStartTime = mCurrentFrameInfo->get(FrameInfoIndex::FrameStartTime);
796 int64_t frameDuration = systemTime(SYSTEM_TIME_MONOTONIC) - frameStartTime;
797 int64_t actualDuration = frameDuration -
798 (std::min(syncDelayDuration, mLastDequeueBufferDuration)) -
799 dequeueBufferDuration - idleDuration;
800 mHintSessionWrapper->reportActualWorkDuration(actualDuration);
801 mHintSessionWrapper->setActiveFunctorThreads(
802 WebViewFunctorManager::instance().getRenderingThreadsForActiveFunctors());
803 }
804
805 mLastDequeueBufferDuration = dequeueBufferDuration;
806
807 mRenderThread.cacheManager().onFrameCompleted();
808 return;
809 }
810
reportMetricsWithPresentTime()811 void CanvasContext::reportMetricsWithPresentTime() {
812 { // acquire lock
813 std::scoped_lock lock(mFrameInfoMutex);
814 if (mFrameMetricsReporter == nullptr) {
815 return;
816 }
817 } // release lock
818 if (mNativeSurface == nullptr) {
819 return;
820 }
821 ATRACE_CALL();
822 FrameInfo* forthBehind;
823 int64_t frameNumber;
824 int32_t surfaceControlId;
825
826 { // acquire lock
827 std::scoped_lock lock(mLastFrameMetricsInfosMutex);
828 if (mLastFrameMetricsInfos.size() != mLastFrameMetricsInfos.capacity()) {
829 // Not enough frames yet
830 return;
831 }
832 auto frameMetricsInfo = mLastFrameMetricsInfos.front();
833 forthBehind = frameMetricsInfo.frameInfo;
834 frameNumber = frameMetricsInfo.frameNumber;
835 surfaceControlId = frameMetricsInfo.surfaceId;
836 } // release lock
837
838 nsecs_t presentTime = 0;
839 native_window_get_frame_timestamps(
840 mNativeSurface->getNativeWindow(), frameNumber, nullptr /*outRequestedPresentTime*/,
841 nullptr /*outAcquireTime*/, nullptr /*outLatchTime*/,
842 nullptr /*outFirstRefreshStartTime*/, nullptr /*outLastRefreshStartTime*/,
843 nullptr /*outGpuCompositionDoneTime*/, &presentTime, nullptr /*outDequeueReadyTime*/,
844 nullptr /*outReleaseTime*/);
845
846 forthBehind->set(FrameInfoIndex::DisplayPresentTime) = presentTime;
847 { // acquire lock
848 std::scoped_lock lock(mFrameInfoMutex);
849 if (mFrameMetricsReporter != nullptr) {
850 mFrameMetricsReporter->reportFrameMetrics(forthBehind->data(), true /*hasPresentTime*/,
851 frameNumber, surfaceControlId);
852 }
853 } // release lock
854 }
855
addFrameMetricsObserver(FrameMetricsObserver * observer)856 void CanvasContext::addFrameMetricsObserver(FrameMetricsObserver* observer) {
857 std::scoped_lock lock(mFrameInfoMutex);
858 if (mFrameMetricsReporter.get() == nullptr) {
859 mFrameMetricsReporter.reset(new FrameMetricsReporter());
860 }
861
862 // We want to make sure we aren't reporting frames that have already been queued by the
863 // BufferQueueProducer on the rendner thread but are still pending the callback to report their
864 // their frame metrics.
865 uint64_t nextFrameNumber = getFrameNumber();
866 observer->reportMetricsFrom(nextFrameNumber, mSurfaceControlGenerationId);
867 mFrameMetricsReporter->addObserver(observer);
868 }
869
removeFrameMetricsObserver(FrameMetricsObserver * observer)870 void CanvasContext::removeFrameMetricsObserver(FrameMetricsObserver* observer) {
871 std::scoped_lock lock(mFrameInfoMutex);
872 if (mFrameMetricsReporter.get() != nullptr) {
873 mFrameMetricsReporter->removeObserver(observer);
874 if (!mFrameMetricsReporter->hasObservers()) {
875 mFrameMetricsReporter.reset(nullptr);
876 }
877 }
878 }
879
getFrameInfoFromLastFew(uint64_t frameNumber,uint32_t surfaceControlId)880 FrameInfo* CanvasContext::getFrameInfoFromLastFew(uint64_t frameNumber, uint32_t surfaceControlId) {
881 std::scoped_lock lock(mLastFrameMetricsInfosMutex);
882 for (size_t i = 0; i < mLastFrameMetricsInfos.size(); i++) {
883 if (mLastFrameMetricsInfos[i].frameNumber == frameNumber &&
884 mLastFrameMetricsInfos[i].surfaceId == surfaceControlId) {
885 return mLastFrameMetricsInfos[i].frameInfo;
886 }
887 }
888
889 return nullptr;
890 }
891
onSurfaceStatsAvailable(void * context,int32_t surfaceControlId,ASurfaceControlStats * stats)892 void CanvasContext::onSurfaceStatsAvailable(void* context, int32_t surfaceControlId,
893 ASurfaceControlStats* stats) {
894 auto* instance = static_cast<CanvasContext*>(context);
895
896 const ASurfaceControlFunctions& functions =
897 instance->mRenderThread.getASurfaceControlFunctions();
898
899 nsecs_t gpuCompleteTime = functions.getAcquireTimeFunc(stats);
900 if (gpuCompleteTime == Fence::SIGNAL_TIME_PENDING) {
901 gpuCompleteTime = -1;
902 }
903 uint64_t frameNumber = functions.getFrameNumberFunc(stats);
904
905 FrameInfo* frameInfo = instance->getFrameInfoFromLastFew(frameNumber, surfaceControlId);
906
907 if (frameInfo != nullptr) {
908 std::scoped_lock lock(instance->mFrameInfoMutex);
909 frameInfo->set(FrameInfoIndex::FrameCompleted) = std::max(gpuCompleteTime,
910 frameInfo->get(FrameInfoIndex::SwapBuffersCompleted));
911 frameInfo->set(FrameInfoIndex::GpuCompleted) = std::max(
912 gpuCompleteTime, frameInfo->get(FrameInfoIndex::CommandSubmissionCompleted));
913 instance->mJankTracker.finishFrame(*frameInfo, instance->mFrameMetricsReporter, frameNumber,
914 surfaceControlId);
915 }
916 }
917
918 // Called by choreographer to do an RT-driven animation
doFrame()919 void CanvasContext::doFrame() {
920 if (!mRenderPipeline->isSurfaceReady()) return;
921 mIdleDuration =
922 systemTime(SYSTEM_TIME_MONOTONIC) - mRenderThread.timeLord().computeFrameTimeNanos();
923 prepareAndDraw(nullptr);
924 }
925
getNextFrameSize() const926 SkISize CanvasContext::getNextFrameSize() const {
927 static constexpr SkISize defaultFrameSize = {INT32_MAX, INT32_MAX};
928 if (mNativeSurface == nullptr) {
929 return defaultFrameSize;
930 }
931 ANativeWindow* anw = mNativeSurface->getNativeWindow();
932
933 SkISize size;
934 size.fWidth = ANativeWindow_getWidth(anw);
935 size.fHeight = ANativeWindow_getHeight(anw);
936 mRenderThread.cacheManager().notifyNextFrameSize(size.fWidth, size.fHeight);
937 return size;
938 }
939
getPixelSnapMatrix() const940 const SkM44& CanvasContext::getPixelSnapMatrix() const {
941 return mRenderPipeline->getPixelSnapMatrix();
942 }
943
prepareAndDraw(RenderNode * node)944 void CanvasContext::prepareAndDraw(RenderNode* node) {
945 int64_t vsyncId = mRenderThread.timeLord().lastVsyncId();
946 ATRACE_FORMAT("%s %" PRId64, __func__, vsyncId);
947
948 nsecs_t vsync = mRenderThread.timeLord().computeFrameTimeNanos();
949 int64_t frameDeadline = mRenderThread.timeLord().lastFrameDeadline();
950 int64_t frameInterval = mRenderThread.timeLord().frameIntervalNanos();
951 int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE];
952 UiFrameInfoBuilder(frameInfo)
953 .addFlag(FrameInfoFlags::RTAnimation)
954 .setVsync(vsync, vsync, vsyncId, frameDeadline, frameInterval);
955
956 TreeInfo info(TreeInfo::MODE_RT_ONLY, *this);
957 prepareTree(info, frameInfo, systemTime(SYSTEM_TIME_MONOTONIC), node);
958 if (!info.out.skippedFrameReason) {
959 draw(info.out.solelyTextureViewUpdates);
960 } else {
961 // wait on fences so tasks don't overlap next frame
962 waitOnFences();
963 }
964 }
965
markLayerInUse(RenderNode * node)966 void CanvasContext::markLayerInUse(RenderNode* node) {
967 if (mPrefetchedLayers.erase(node)) {
968 node->decStrong(nullptr);
969 }
970 }
971
freePrefetchedLayers()972 void CanvasContext::freePrefetchedLayers() {
973 if (mPrefetchedLayers.size()) {
974 for (auto& node : mPrefetchedLayers) {
975 ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...",
976 node->getName());
977 node->destroyLayers();
978 node->decStrong(nullptr);
979 }
980 mPrefetchedLayers.clear();
981 }
982 }
983
buildLayer(RenderNode * node)984 void CanvasContext::buildLayer(RenderNode* node) {
985 ATRACE_CALL();
986 if (!mRenderPipeline->isContextReady()) return;
987
988 // buildLayer() will leave the tree in an unknown state, so we must stop drawing
989 stopDrawing();
990
991 ScopedActiveContext activeContext(this);
992 TreeInfo info(TreeInfo::MODE_FULL, *this);
993 info.damageAccumulator = &mDamageAccumulator;
994 info.layerUpdateQueue = &mLayerUpdateQueue;
995 info.runAnimations = false;
996 node->prepareTree(info);
997 SkRect ignore;
998 mDamageAccumulator.finish(&ignore);
999 // Tickle the GENERIC property on node to mark it as dirty for damaging
1000 // purposes when the frame is actually drawn
1001 node->setPropertyFieldsDirty(RenderNode::GENERIC);
1002
1003 mRenderPipeline->renderLayers(mLightGeometry, &mLayerUpdateQueue, mOpaque, mLightInfo);
1004
1005 node->incStrong(nullptr);
1006 mPrefetchedLayers.insert(node);
1007 }
1008
destroyHardwareResources()1009 void CanvasContext::destroyHardwareResources() {
1010 stopDrawing();
1011 if (mRenderPipeline->isContextReady()) {
1012 freePrefetchedLayers();
1013 for (const sp<RenderNode>& node : mRenderNodes) {
1014 node->destroyHardwareResources();
1015 }
1016 mRenderPipeline->onDestroyHardwareResources();
1017 }
1018 }
1019
onContextDestroyed()1020 void CanvasContext::onContextDestroyed() {
1021 // We don't want to destroyHardwareResources as that will invalidate display lists which
1022 // the client may not be expecting. Instead just purge all scratch resources
1023 if (mRenderPipeline->isContextReady()) {
1024 freePrefetchedLayers();
1025 for (const sp<RenderNode>& node : mRenderNodes) {
1026 node->destroyLayers();
1027 }
1028 mRenderPipeline->onDestroyHardwareResources();
1029 }
1030 }
1031
createTextureLayer()1032 DeferredLayerUpdater* CanvasContext::createTextureLayer() {
1033 return mRenderPipeline->createTextureLayer();
1034 }
1035
dumpFrames(int fd)1036 void CanvasContext::dumpFrames(int fd) {
1037 mJankTracker.dumpStats(fd);
1038 mJankTracker.dumpFrames(fd);
1039 }
1040
resetFrameStats()1041 void CanvasContext::resetFrameStats() {
1042 mJankTracker.reset();
1043 }
1044
setName(const std::string && name)1045 void CanvasContext::setName(const std::string&& name) {
1046 mJankTracker.setDescription(JankTrackerType::Window, std::move(name));
1047 }
1048
waitOnFences()1049 void CanvasContext::waitOnFences() {
1050 if (mFrameFences.size()) {
1051 ATRACE_CALL();
1052 for (auto& fence : mFrameFences) {
1053 fence.get();
1054 }
1055 mFrameFences.clear();
1056 }
1057 }
1058
enqueueFrameWork(std::function<void ()> && func)1059 void CanvasContext::enqueueFrameWork(std::function<void()>&& func) {
1060 mFrameFences.push_back(CommonPool::async(std::move(func)));
1061 }
1062
getFrameNumber()1063 uint64_t CanvasContext::getFrameNumber() {
1064 // mFrameNumber is reset to 0 when the surface changes or we swap buffers
1065 if (mFrameNumber == 0 && mNativeSurface.get()) {
1066 mFrameNumber = ANativeWindow_getNextFrameId(mNativeSurface->getNativeWindow());
1067 }
1068 return mFrameNumber;
1069 }
1070
surfaceRequiresRedraw()1071 bool CanvasContext::surfaceRequiresRedraw() {
1072 if (!mNativeSurface) return false;
1073 if (mHaveNewSurface) return true;
1074
1075 ANativeWindow* anw = mNativeSurface->getNativeWindow();
1076 const int width = ANativeWindow_getWidth(anw);
1077 const int height = ANativeWindow_getHeight(anw);
1078
1079 return width != mLastFrameWidth || height != mLastFrameHeight;
1080 }
1081
computeDirtyRect(const Frame & frame,SkRect * dirty)1082 SkRect CanvasContext::computeDirtyRect(const Frame& frame, SkRect* dirty) {
1083 if (frame.width() != mLastFrameWidth || frame.height() != mLastFrameHeight) {
1084 // can't rely on prior content of window if viewport size changes
1085 dirty->setEmpty();
1086 mLastFrameWidth = frame.width();
1087 mLastFrameHeight = frame.height();
1088 } else if (mHaveNewSurface || frame.bufferAge() == 0) {
1089 // New surface needs a full draw
1090 dirty->setEmpty();
1091 } else {
1092 if (!dirty->isEmpty() && !dirty->intersect(SkRect::MakeIWH(frame.width(), frame.height()))) {
1093 ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?", SK_RECT_ARGS(*dirty),
1094 frame.width(), frame.height());
1095 dirty->setEmpty();
1096 }
1097 profiler().unionDirty(dirty);
1098 }
1099
1100 if (dirty->isEmpty()) {
1101 dirty->setIWH(frame.width(), frame.height());
1102 return *dirty;
1103 }
1104
1105 // At this point dirty is the area of the window to update. However,
1106 // the area of the frame we need to repaint is potentially different, so
1107 // stash the screen area for later
1108 SkRect windowDirty(*dirty);
1109
1110 // If the buffer age is 0 we do a full-screen repaint (handled above)
1111 // If the buffer age is 1 the buffer contents are the same as they were
1112 // last frame so there's nothing to union() against
1113 // Therefore we only care about the > 1 case.
1114 if (frame.bufferAge() > 1) {
1115 if (frame.bufferAge() > (int)mSwapHistory.size()) {
1116 // We don't have enough history to handle this old of a buffer
1117 // Just do a full-draw
1118 dirty->setIWH(frame.width(), frame.height());
1119 } else {
1120 // At this point we haven't yet added the latest frame
1121 // to the damage history (happens below)
1122 // So we need to damage
1123 for (int i = mSwapHistory.size() - 1;
1124 i > ((int)mSwapHistory.size()) - frame.bufferAge(); i--) {
1125 dirty->join(mSwapHistory[i].damage);
1126 }
1127 }
1128 }
1129
1130 return windowDirty;
1131 }
1132
getActiveContext()1133 CanvasContext* CanvasContext::getActiveContext() {
1134 return ScopedActiveContext::getActiveContext();
1135 }
1136
mergeTransaction(ASurfaceTransaction * transaction,ASurfaceControl * control)1137 bool CanvasContext::mergeTransaction(ASurfaceTransaction* transaction, ASurfaceControl* control) {
1138 if (!mASurfaceTransactionCallback) return false;
1139 return std::invoke(mASurfaceTransactionCallback, reinterpret_cast<int64_t>(transaction),
1140 reinterpret_cast<int64_t>(control), getFrameNumber());
1141 }
1142
prepareSurfaceControlForWebview()1143 void CanvasContext::prepareSurfaceControlForWebview() {
1144 if (mPrepareSurfaceControlForWebviewCallback) {
1145 std::invoke(mPrepareSurfaceControlForWebviewCallback);
1146 }
1147 }
1148
sendLoadResetHint()1149 void CanvasContext::sendLoadResetHint() {
1150 mHintSessionWrapper->sendLoadResetHint();
1151 }
1152
sendLoadIncreaseHint()1153 void CanvasContext::sendLoadIncreaseHint() {
1154 mHintSessionWrapper->sendLoadIncreaseHint();
1155 }
1156
setSyncDelayDuration(nsecs_t duration)1157 void CanvasContext::setSyncDelayDuration(nsecs_t duration) {
1158 mSyncDelayDuration = duration;
1159 }
1160
startHintSession()1161 void CanvasContext::startHintSession() {
1162 mHintSessionWrapper->init();
1163 }
1164
shouldDither()1165 bool CanvasContext::shouldDither() {
1166 CanvasContext* self = getActiveContext();
1167 if (!self) return false;
1168 return self->mColorMode != ColorMode::Default;
1169 }
1170
visitAllRenderNodes(std::function<void (const RenderNode &)> func) const1171 void CanvasContext::visitAllRenderNodes(std::function<void(const RenderNode&)> func) const {
1172 for (auto node : mRenderNodes) {
1173 node->visit(func);
1174 }
1175 }
1176
1177 } /* namespace renderthread */
1178 } /* namespace uirenderer */
1179 } /* namespace android */
1180