1 /*
2  * Copyright (C) 2007 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 // TODO(b/129481165): remove the #pragma below and fix conversion issues
18 
19 #pragma clang diagnostic push
20 #pragma clang diagnostic ignored "-Wconversion"
21 
22 //#define LOG_NDEBUG 0
23 #undef LOG_TAG
24 #define LOG_TAG "Layer"
25 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
26 
27 #include <android-base/properties.h>
28 #include <android-base/stringprintf.h>
29 #include <binder/IPCThreadState.h>
30 #include <compositionengine/CompositionEngine.h>
31 #include <compositionengine/Display.h>
32 #include <compositionengine/LayerFECompositionState.h>
33 #include <compositionengine/OutputLayer.h>
34 #include <compositionengine/impl/OutputLayerCompositionState.h>
35 #include <cutils/compiler.h>
36 #include <cutils/native_handle.h>
37 #include <cutils/properties.h>
38 #include <ftl/enum.h>
39 #include <ftl/fake_guard.h>
40 #include <gui/BufferItem.h>
41 #include <gui/Surface.h>
42 #include <gui/TraceUtils.h>
43 #include <math.h>
44 #include <private/android_filesystem_config.h>
45 #include <renderengine/RenderEngine.h>
46 #include <stdint.h>
47 #include <stdlib.h>
48 #include <sys/types.h>
49 #include <system/graphics-base-v1.0.h>
50 #include <ui/DebugUtils.h>
51 #include <ui/FloatRect.h>
52 #include <ui/GraphicBuffer.h>
53 #include <ui/HdrRenderTypeUtils.h>
54 #include <ui/PixelFormat.h>
55 #include <ui/Rect.h>
56 #include <ui/Transform.h>
57 #include <utils/Errors.h>
58 #include <utils/Log.h>
59 #include <utils/NativeHandle.h>
60 #include <utils/StopWatch.h>
61 #include <utils/Trace.h>
62 
63 #include <algorithm>
64 #include <mutex>
65 #include <optional>
66 #include <sstream>
67 
68 #include "DisplayDevice.h"
69 #include "DisplayHardware/HWComposer.h"
70 #include "FrameTimeline.h"
71 #include "FrameTracer/FrameTracer.h"
72 #include "FrontEnd/LayerCreationArgs.h"
73 #include "FrontEnd/LayerHandle.h"
74 #include "Layer.h"
75 #include "LayerProtoHelper.h"
76 #include "MutexUtils.h"
77 #include "SurfaceFlinger.h"
78 #include "TimeStats/TimeStats.h"
79 #include "TransactionCallbackInvoker.h"
80 #include "TunnelModeEnabledReporter.h"
81 #include "Utils/FenceUtils.h"
82 
83 #define DEBUG_RESIZE 0
84 #define EARLY_RELEASE_ENABLED false
85 
86 namespace android {
87 using namespace std::chrono_literals;
88 namespace {
89 constexpr int kDumpTableRowLength = 159;
90 
91 const ui::Transform kIdentityTransform;
92 
toLogicalDisplayId(const ui::LayerStack & layerStack)93 ui::LogicalDisplayId toLogicalDisplayId(const ui::LayerStack& layerStack) {
94     return ui::LogicalDisplayId{static_cast<int32_t>(layerStack.id)};
95 }
96 
assignTransform(ui::Transform * dst,ui::Transform & from)97 bool assignTransform(ui::Transform* dst, ui::Transform& from) {
98     if (*dst == from) {
99         return false;
100     }
101     *dst = from;
102     return true;
103 }
104 
frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate)105 TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
106     using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
107     using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
108     const auto frameRateCompatibility = [frameRate] {
109         switch (frameRate.vote.type) {
110             case Layer::FrameRateCompatibility::Default:
111                 return FrameRateCompatibility::Default;
112             case Layer::FrameRateCompatibility::ExactOrMultiple:
113                 return FrameRateCompatibility::ExactOrMultiple;
114             default:
115                 return FrameRateCompatibility::Undefined;
116         }
117     }();
118 
119     const auto seamlessness = [frameRate] {
120         switch (frameRate.vote.seamlessness) {
121             case scheduler::Seamlessness::OnlySeamless:
122                 return Seamlessness::ShouldBeSeamless;
123             case scheduler::Seamlessness::SeamedAndSeamless:
124                 return Seamlessness::NotRequired;
125             default:
126                 return Seamlessness::Undefined;
127         }
128     }();
129 
130     return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
131                                        .frameRateCompatibility = frameRateCompatibility,
132                                        .seamlessness = seamlessness};
133 }
134 
135 } // namespace
136 
137 using namespace ftl::flag_operators;
138 
139 using base::StringAppendF;
140 using frontend::LayerSnapshot;
141 using frontend::RoundedCornerState;
142 using gui::GameMode;
143 using gui::LayerMetadata;
144 using gui::WindowInfo;
145 using ui::Size;
146 
147 using PresentState = frametimeline::SurfaceFrame::PresentState;
148 
Layer(const surfaceflinger::LayerCreationArgs & args)149 Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
150       : sequence(args.sequence),
151         mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
152         mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
153         mClientRef(args.client),
154         mWindowType(static_cast<WindowInfo::Type>(
155                 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
156         mLayerCreationFlags(args.flags),
157         mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName, this)) {
158     ALOGV("Creating Layer %s", getDebugName());
159 
160     uint32_t layerFlags = 0;
161     if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
162     if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
163     if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
164     if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
165         layerFlags |= layer_state_t::eLayerSkipScreenshot;
166     mDrawingState.flags = layerFlags;
167     mDrawingState.crop.makeInvalid();
168     mDrawingState.z = 0;
169     mDrawingState.color.a = 1.0f;
170     mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
171     mDrawingState.sequence = 0;
172     mDrawingState.transform.set(0, 0);
173     mDrawingState.frameNumber = 0;
174     mDrawingState.previousFrameNumber = 0;
175     mDrawingState.barrierFrameNumber = 0;
176     mDrawingState.producerId = 0;
177     mDrawingState.barrierProducerId = 0;
178     mDrawingState.bufferTransform = 0;
179     mDrawingState.transformToDisplayInverse = false;
180     mDrawingState.acquireFence = sp<Fence>::make(-1);
181     mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
182     mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
183     mDrawingState.hdrMetadata.validTypes = 0;
184     mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
185     mDrawingState.cornerRadius = 0.0f;
186     mDrawingState.backgroundBlurRadius = 0;
187     mDrawingState.api = -1;
188     mDrawingState.hasColorTransform = false;
189     mDrawingState.colorSpaceAgnostic = false;
190     mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
191     mDrawingState.metadata = args.metadata;
192     mDrawingState.shadowRadius = 0.f;
193     mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
194     mDrawingState.frameTimelineInfo = {};
195     mDrawingState.postTime = -1;
196     mDrawingState.destinationFrame.makeInvalid();
197     mDrawingState.isTrustedOverlay = false;
198     mDrawingState.dropInputMode = gui::DropInputMode::NONE;
199     mDrawingState.dimmingEnabled = true;
200     mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
201     mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Propagate;
202 
203     if (args.flags & ISurfaceComposerClient::eNoColorFill) {
204         // Set an invalid color so there is no color fill.
205         mDrawingState.color.r = -1.0_hf;
206         mDrawingState.color.g = -1.0_hf;
207         mDrawingState.color.b = -1.0_hf;
208     }
209 
210     mFrameTracker.setDisplayRefreshPeriod(
211             args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
212 
213     mOwnerUid = args.ownerUid;
214     mOwnerPid = args.ownerPid;
215     mOwnerAppId = mOwnerUid % PER_USER_RANGE;
216 
217     mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
218     mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
219     mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
220 
221     mSnapshot->sequence = sequence;
222     mSnapshot->name = getDebugName();
223     mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
224     mSnapshot->parentTransform = {};
225 }
226 
onFirstRef()227 void Layer::onFirstRef() {
228     mFlinger->onLayerFirstRef(this);
229 }
230 
~Layer()231 Layer::~Layer() {
232     LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
233                         "Layer destructor called off the main thread.");
234 
235     // The original layer and the clone layer share the same texture and buffer. Therefore, only
236     // one of the layers, in this case the original layer, needs to handle the deletion. The
237     // original layer and the clone should be removed at the same time so there shouldn't be any
238     // issue with the clone layer trying to use the texture.
239     if (mBufferInfo.mBuffer != nullptr) {
240         callReleaseBufferCallback(mDrawingState.releaseBufferListener,
241                                   mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
242                                   mBufferInfo.mFence);
243     }
244     const int32_t layerId = getSequence();
245     mFlinger->mTimeStats->onDestroy(layerId);
246     mFlinger->mFrameTracer->onDestroy(layerId);
247 
248     mFrameTracker.logAndResetStats(mName);
249     mFlinger->onLayerDestroyed(this);
250 
251     if (mDrawingState.sidebandStream != nullptr) {
252         mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
253     }
254     if (mHadClonedChild) {
255         auto& roots = mFlinger->mLayerMirrorRoots;
256         roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
257     }
258     if (hasTrustedPresentationListener()) {
259         mFlinger->mNumTrustedPresentationListeners--;
260         updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
261     }
262 }
263 
264 // ---------------------------------------------------------------------------
265 // callbacks
266 // ---------------------------------------------------------------------------
267 
removeRelativeZ(const std::vector<Layer * > & layersInTree)268 void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
269     if (mDrawingState.zOrderRelativeOf == nullptr) {
270         return;
271     }
272 
273     sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
274     if (strongRelative == nullptr) {
275         setZOrderRelativeOf(nullptr);
276         return;
277     }
278 
279     if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
280         strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
281         mFlinger->setTransactionFlags(eTraversalNeeded);
282         setZOrderRelativeOf(nullptr);
283     }
284 }
285 
removeFromCurrentState()286 void Layer::removeFromCurrentState() {
287     if (!mRemovedFromDrawingState) {
288         mRemovedFromDrawingState = true;
289         mFlinger->mScheduler->deregisterLayer(this);
290     }
291     updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
292 
293     mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
294 }
295 
getRootLayer()296 sp<Layer> Layer::getRootLayer() {
297     sp<Layer> parent = getParent();
298     if (parent == nullptr) {
299         return sp<Layer>::fromExisting(this);
300     }
301     return parent->getRootLayer();
302 }
303 
onRemovedFromCurrentState()304 void Layer::onRemovedFromCurrentState() {
305     // Use the root layer since we want to maintain the hierarchy for the entire subtree.
306     auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
307     std::sort(layersInTree.begin(), layersInTree.end());
308 
309     REQUIRE_MUTEX(mFlinger->mStateLock);
310     traverse(LayerVector::StateSet::Current,
311              [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
312                  layer->removeFromCurrentState();
313                  layer->removeRelativeZ(layersInTree);
314              });
315 }
316 
addToCurrentState()317 void Layer::addToCurrentState() {
318     if (mRemovedFromDrawingState) {
319         mRemovedFromDrawingState = false;
320         mFlinger->mScheduler->registerLayer(this);
321         mFlinger->removeFromOffscreenLayers(this);
322     }
323 
324     for (const auto& child : mCurrentChildren) {
325         child->addToCurrentState();
326     }
327 }
328 
329 // ---------------------------------------------------------------------------
330 // set-up
331 // ---------------------------------------------------------------------------
332 
getPremultipledAlpha() const333 bool Layer::getPremultipledAlpha() const {
334     return mPremultipliedAlpha;
335 }
336 
getHandle()337 sp<IBinder> Layer::getHandle() {
338     Mutex::Autolock _l(mLock);
339     if (mGetHandleCalled) {
340         ALOGE("Get handle called twice" );
341         return nullptr;
342     }
343     mGetHandleCalled = true;
344     mHandleAlive = true;
345     return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
346 }
347 
348 // ---------------------------------------------------------------------------
349 // h/w composer set-up
350 // ---------------------------------------------------------------------------
351 
reduce(const Rect & win,const Region & exclude)352 static Rect reduce(const Rect& win, const Region& exclude) {
353     if (CC_LIKELY(exclude.isEmpty())) {
354         return win;
355     }
356     if (exclude.isRect()) {
357         return win.reduce(exclude.getBounds());
358     }
359     return Region(win).subtract(exclude).getBounds();
360 }
361 
reduce(const FloatRect & win,const Region & exclude)362 static FloatRect reduce(const FloatRect& win, const Region& exclude) {
363     if (CC_LIKELY(exclude.isEmpty())) {
364         return win;
365     }
366     // Convert through Rect (by rounding) for lack of FloatRegion
367     return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
368 }
369 
getScreenBounds(bool reduceTransparentRegion) const370 Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
371     if (!reduceTransparentRegion) {
372         return Rect{mScreenBounds};
373     }
374 
375     FloatRect bounds = getBounds();
376     ui::Transform t = getTransform();
377     // Transform to screen space.
378     bounds = t.transform(bounds);
379     return Rect{bounds};
380 }
381 
getBounds() const382 FloatRect Layer::getBounds() const {
383     const State& s(getDrawingState());
384     return getBounds(getActiveTransparentRegion(s));
385 }
386 
getBounds(const Region & activeTransparentRegion) const387 FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
388     // Subtract the transparent region and snap to the bounds.
389     return reduce(mBounds, activeTransparentRegion);
390 }
391 
392 // No early returns.
updateTrustedPresentationState(const DisplayDevice * display,const frontend::LayerSnapshot * snapshot,int64_t time_in_ms,bool leaveState)393 void Layer::updateTrustedPresentationState(const DisplayDevice* display,
394                                            const frontend::LayerSnapshot* snapshot,
395                                            int64_t time_in_ms, bool leaveState) {
396     if (!hasTrustedPresentationListener()) {
397         return;
398     }
399     const bool lastState = mLastComputedTrustedPresentationState;
400     mLastComputedTrustedPresentationState = false;
401 
402     if (!leaveState) {
403         const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
404         if (outputLayer != nullptr) {
405             if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
406                 Region coveredRegion =
407                         *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
408                 mLastComputedTrustedPresentationState =
409                         computeTrustedPresentationState(snapshot->geomLayerBounds,
410                                                         snapshot->sourceBounds(), coveredRegion,
411                                                         snapshot->transformedBounds,
412                                                         snapshot->alpha,
413                                                         snapshot->geomLayerTransform,
414                                                         mTrustedPresentationThresholds);
415             } else {
416                 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
417                       "TrustedPresentationState",
418                       getDebugName());
419             }
420         }
421     }
422     const bool newState = mLastComputedTrustedPresentationState;
423     if (lastState && !newState) {
424         // We were in the trusted presentation state, but now we left it,
425         // emit the callback if needed
426         if (mLastReportedTrustedPresentationState) {
427             mLastReportedTrustedPresentationState = false;
428             mTrustedPresentationListener.invoke(false);
429         }
430         // Reset the timer
431         mEnteredTrustedPresentationStateTime = -1;
432     } else if (!lastState && newState) {
433         // We were not in the trusted presentation state, but we entered it, begin the timer
434         // and make sure this gets called at least once more!
435         mEnteredTrustedPresentationStateTime = time_in_ms;
436         mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
437     }
438 
439     // Has the timer elapsed, but we are still in the state? Emit a callback if needed
440     if (!mLastReportedTrustedPresentationState && newState &&
441         (time_in_ms - mEnteredTrustedPresentationStateTime >
442          mTrustedPresentationThresholds.stabilityRequirementMs)) {
443         mLastReportedTrustedPresentationState = true;
444         mTrustedPresentationListener.invoke(true);
445     }
446 }
447 
448 /**
449  * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
450  * of how the parameters and thresholds are interpreted. The general spirit is
451  * to produce an upper bound on the amount of the buffer which was presented.
452  */
computeTrustedPresentationState(const FloatRect & bounds,const FloatRect & sourceBounds,const Region & coveredRegion,const FloatRect & screenBounds,float alpha,const ui::Transform & effectiveTransform,const TrustedPresentationThresholds & thresholds)453 bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
454                                             const Region& coveredRegion,
455                                             const FloatRect& screenBounds, float alpha,
456                                             const ui::Transform& effectiveTransform,
457                                             const TrustedPresentationThresholds& thresholds) {
458     if (alpha < thresholds.minAlpha) {
459         return false;
460     }
461     if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
462         return false;
463     }
464     if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
465         return false;
466     }
467 
468     const float sx = effectiveTransform.dsdx();
469     const float sy = effectiveTransform.dsdy();
470     float fractionRendered = std::min(sx * sy, 1.0f);
471 
472     float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
473     float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
474     fractionRendered *= boundsOverSourceW * boundsOverSourceH;
475 
476     Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
477     // Compute the size of all the rects since they may be disconnected.
478     float coveredSize = 0;
479     for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
480         float size = rect->width() * rect->height();
481         coveredSize += size;
482     }
483 
484     fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
485 
486     if (fractionRendered < thresholds.minFractionRendered) {
487         return false;
488     }
489 
490     return true;
491 }
492 
computeBounds(FloatRect parentBounds,ui::Transform parentTransform,float parentShadowRadius)493 void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
494                           float parentShadowRadius) {
495     const State& s(getDrawingState());
496 
497     // Calculate effective layer transform
498     mEffectiveTransform = parentTransform * getActiveTransform(s);
499 
500     if (CC_UNLIKELY(!isTransformValid())) {
501         ALOGW("Stop computing bounds for %s because it has invalid transformation.",
502               getDebugName());
503         return;
504     }
505 
506     // Transform parent bounds to layer space
507     parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
508 
509     // Calculate source bounds
510     mSourceBounds = computeSourceBounds(parentBounds);
511 
512     // Calculate bounds by croping diplay frame with layer crop and parent bounds
513     FloatRect bounds = mSourceBounds;
514     const Rect layerCrop = getCrop(s);
515     if (!layerCrop.isEmpty()) {
516         bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
517     }
518     bounds = bounds.intersect(parentBounds);
519 
520     mBounds = bounds;
521     mScreenBounds = mEffectiveTransform.transform(mBounds);
522 
523     // Use the layer's own shadow radius if set. Otherwise get the radius from
524     // parent.
525     if (s.shadowRadius > 0.f) {
526         mEffectiveShadowRadius = s.shadowRadius;
527     } else {
528         mEffectiveShadowRadius = parentShadowRadius;
529     }
530 
531     // Shadow radius is passed down to only one layer so if the layer can draw shadows,
532     // don't pass it to its children.
533     const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
534 
535     for (const sp<Layer>& child : mDrawingChildren) {
536         child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
537     }
538 
539     if (mPotentialCursor) {
540         prepareCursorCompositionState();
541     }
542 }
543 
getCroppedBufferSize(const State & s) const544 Rect Layer::getCroppedBufferSize(const State& s) const {
545     Rect size = getBufferSize(s);
546     Rect crop = getCrop(s);
547     if (!crop.isEmpty() && size.isValid()) {
548         size.intersect(crop, &size);
549     } else if (!crop.isEmpty()) {
550         size = crop;
551     }
552     return size;
553 }
554 
setupRoundedCornersCropCoordinates(Rect win,const FloatRect & roundedCornersCrop) const555 void Layer::setupRoundedCornersCropCoordinates(Rect win,
556                                                const FloatRect& roundedCornersCrop) const {
557     // Translate win by the rounded corners rect coordinates, to have all values in
558     // layer coordinate space.
559     win.left -= roundedCornersCrop.left;
560     win.right -= roundedCornersCrop.left;
561     win.top -= roundedCornersCrop.top;
562     win.bottom -= roundedCornersCrop.top;
563 }
564 
prepareBasicGeometryCompositionState()565 void Layer::prepareBasicGeometryCompositionState() {
566     const auto& drawingState{getDrawingState()};
567     const auto alpha = static_cast<float>(getAlpha());
568     const bool opaque = isOpaque(drawingState);
569     const bool usesRoundedCorners = hasRoundedCorners();
570 
571     auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
572     if (!opaque || alpha != 1.0f) {
573         blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
574                                         : Hwc2::IComposerClient::BlendMode::COVERAGE;
575     }
576 
577     // Please keep in sync with LayerSnapshotBuilder
578     auto* snapshot = editLayerSnapshot();
579     snapshot->outputFilter = getOutputFilter();
580     snapshot->isVisible = isVisible();
581     snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
582     snapshot->shadowSettings.length = mEffectiveShadowRadius;
583 
584     snapshot->contentDirty = contentDirty;
585     contentDirty = false;
586 
587     snapshot->geomLayerBounds = mBounds;
588     snapshot->geomLayerTransform = getTransform();
589     snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
590     snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
591     snapshot->localTransform = getActiveTransform(drawingState);
592     snapshot->localTransformInverse = snapshot->localTransform.inverse();
593     snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
594     snapshot->alpha = alpha;
595     snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
596     snapshot->blurRegions = getBlurRegions();
597     snapshot->stretchEffect = getStretchEffect();
598 }
599 
prepareGeometryCompositionState()600 void Layer::prepareGeometryCompositionState() {
601     const auto& drawingState{getDrawingState()};
602     auto* snapshot = editLayerSnapshot();
603 
604     // Please keep in sync with LayerSnapshotBuilder
605     snapshot->geomBufferSize = getBufferSize(drawingState);
606     snapshot->geomContentCrop = getBufferCrop();
607     snapshot->geomCrop = getCrop(drawingState);
608     snapshot->geomBufferTransform = getBufferTransform();
609     snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
610     snapshot->geomUsesSourceCrop = usesSourceCrop();
611     snapshot->isSecure = isSecure();
612 
613     snapshot->metadata.clear();
614     const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
615     for (const auto& [key, mandatory] : supportedMetadata) {
616         const auto& genericLayerMetadataCompatibilityMap =
617                 mFlinger->getGenericLayerMetadataKeyMap();
618         auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
619         if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
620             continue;
621         }
622         const uint32_t id = compatIter->second;
623 
624         auto it = drawingState.metadata.mMap.find(id);
625         if (it == std::end(drawingState.metadata.mMap)) {
626             continue;
627         }
628 
629         snapshot->metadata.emplace(key,
630                                    compositionengine::GenericLayerMetadataEntry{mandatory,
631                                                                                 it->second});
632     }
633 }
634 
preparePerFrameCompositionState()635 void Layer::preparePerFrameCompositionState() {
636     const auto& drawingState{getDrawingState()};
637     // Please keep in sync with LayerSnapshotBuilder
638     auto* snapshot = editLayerSnapshot();
639 
640     snapshot->forceClientComposition = false;
641 
642     snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
643     snapshot->dataspace = getDataSpace();
644     snapshot->colorTransform = getColorTransform();
645     snapshot->colorTransformIsIdentity = !hasColorTransform();
646     snapshot->surfaceDamage = surfaceDamageRegion;
647     snapshot->hasProtectedContent = isProtected();
648     snapshot->dimmingEnabled = isDimmingEnabled();
649     snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
650     snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
651     snapshot->cachingHint = getCachingHint();
652 
653     const bool usesRoundedCorners = hasRoundedCorners();
654 
655     snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
656 
657     // Force client composition for special cases known only to the front-end.
658     // Rounded corners no longer force client composition, since we may use a
659     // hole punch so that the layer will appear to have rounded corners.
660     if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
661         snapshot->forceClientComposition = true;
662     }
663     // If there are no visible region changes, we still need to update blur parameters.
664     snapshot->blurRegions = getBlurRegions();
665     snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
666 
667     // Layer framerate is used in caching decisions.
668     // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
669     // LayerFECompositionState where it would be visible to Flattener.
670     snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
671 
672     if (hasBufferOrSidebandStream()) {
673         preparePerFrameBufferCompositionState();
674     } else {
675         preparePerFrameEffectsCompositionState();
676     }
677 }
678 
preparePerFrameBufferCompositionState()679 void Layer::preparePerFrameBufferCompositionState() {
680     // Please keep in sync with LayerSnapshotBuilder
681     auto* snapshot = editLayerSnapshot();
682     // Sideband layers
683     if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
684         snapshot->compositionType =
685                 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
686         return;
687     } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
688         snapshot->compositionType =
689                 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
690     } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
691         snapshot->compositionType =
692                 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
693     } else {
694         // Normal buffer layers
695         snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
696         snapshot->compositionType = mPotentialCursor
697                 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
698                 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
699     }
700 
701     snapshot->buffer = getBuffer();
702     snapshot->acquireFence = mBufferInfo.mFence;
703     snapshot->frameNumber = mBufferInfo.mFrameNumber;
704     snapshot->sidebandStreamHasFrame = false;
705 }
706 
preparePerFrameEffectsCompositionState()707 void Layer::preparePerFrameEffectsCompositionState() {
708     // Please keep in sync with LayerSnapshotBuilder
709     auto* snapshot = editLayerSnapshot();
710     snapshot->color = getColor();
711     snapshot->compositionType =
712             aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
713 }
714 
prepareCursorCompositionState()715 void Layer::prepareCursorCompositionState() {
716     const State& drawingState{getDrawingState()};
717     // Please keep in sync with LayerSnapshotBuilder
718     auto* snapshot = editLayerSnapshot();
719 
720     // Apply the layer's transform, followed by the display's global transform
721     // Here we're guaranteed that the layer's transform preserves rects
722     Rect win = getCroppedBufferSize(drawingState);
723     // Subtract the transparent region and snap to the bounds
724     Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
725     Rect frame(getTransform().transform(bounds));
726 
727     snapshot->cursorFrame = frame;
728 }
729 
getDebugName() const730 const char* Layer::getDebugName() const {
731     return mName.c_str();
732 }
733 
734 // ---------------------------------------------------------------------------
735 // drawing...
736 // ---------------------------------------------------------------------------
737 
getCompositionType(const DisplayDevice & display) const738 aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
739         const DisplayDevice& display) const {
740     const auto outputLayer = findOutputLayerForDisplay(&display);
741     return getCompositionType(outputLayer);
742 }
743 
getCompositionType(const compositionengine::OutputLayer * outputLayer) const744 aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
745         const compositionengine::OutputLayer* outputLayer) const {
746     if (outputLayer == nullptr) {
747         return aidl::android::hardware::graphics::composer3::Composition::INVALID;
748     }
749     if (outputLayer->getState().hwc) {
750         return (*outputLayer->getState().hwc).hwcCompositionType;
751     } else {
752         return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
753     }
754 }
755 
756 // ----------------------------------------------------------------------------
757 // local state
758 // ----------------------------------------------------------------------------
759 
isSecure() const760 bool Layer::isSecure() const {
761     const State& s(mDrawingState);
762     if (s.flags & layer_state_t::eLayerSecure) {
763         return true;
764     }
765 
766     const auto p = mDrawingParent.promote();
767     return (p != nullptr) ? p->isSecure() : false;
768 }
769 
transferAvailableJankData(const std::deque<sp<CallbackHandle>> & handles,std::vector<JankData> & jankData)770 void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
771                                       std::vector<JankData>& jankData) {
772     if (mPendingJankClassifications.empty() ||
773         !mPendingJankClassifications.front()->getJankType()) {
774         return;
775     }
776 
777     bool includeJankData = false;
778     for (const auto& handle : handles) {
779         for (const auto& cb : handle->callbackIds) {
780             if (cb.includeJankData) {
781                 includeJankData = true;
782                 break;
783             }
784         }
785 
786         if (includeJankData) {
787             jankData.reserve(mPendingJankClassifications.size());
788             break;
789         }
790     }
791 
792     while (!mPendingJankClassifications.empty() &&
793            mPendingJankClassifications.front()->getJankType()) {
794         if (includeJankData) {
795             std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
796                     mPendingJankClassifications.front();
797             jankData.emplace_back(JankData(surfaceFrame->getToken(),
798                                            surfaceFrame->getJankType().value(),
799                                            surfaceFrame->getRenderRate().getPeriodNsecs()));
800         }
801         mPendingJankClassifications.pop_front();
802     }
803 }
804 
805 // ----------------------------------------------------------------------------
806 // transaction
807 // ----------------------------------------------------------------------------
808 
doTransaction(uint32_t flags)809 uint32_t Layer::doTransaction(uint32_t flags) {
810     ATRACE_CALL();
811 
812     // TODO: This is unfortunate.
813     mDrawingStateModified = mDrawingState.modified;
814     mDrawingState.modified = false;
815 
816     const State& s(getDrawingState());
817 
818     if (updateGeometry()) {
819         // invalidate and recompute the visible regions if needed
820         flags |= Layer::eVisibleRegion;
821     }
822 
823     if (s.sequence != mLastCommittedTxSequence) {
824         // invalidate and recompute the visible regions if needed
825         mLastCommittedTxSequence = s.sequence;
826         flags |= eVisibleRegion;
827         this->contentDirty = true;
828 
829         // we may use linear filtering, if the matrix scales us
830         mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
831     }
832 
833     if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
834         mFlinger->mUpdateInputInfo = true;
835     }
836 
837     commitTransaction();
838 
839     return flags;
840 }
841 
commitTransaction()842 void Layer::commitTransaction() {
843     // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
844     // bufferSurfaceFrameTX will be presented in latchBuffer.
845     for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
846         if (surfaceFrame->getPresentState() != PresentState::Presented) {
847             // With applyPendingStates, we could end up having presented surfaceframes from previous
848             // states
849             surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
850             mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
851         }
852     }
853     mDrawingState.bufferlessSurfaceFramesTX.clear();
854 }
855 
clearTransactionFlags(uint32_t mask)856 uint32_t Layer::clearTransactionFlags(uint32_t mask) {
857     const auto flags = mTransactionFlags & mask;
858     mTransactionFlags &= ~mask;
859     return flags;
860 }
861 
setTransactionFlags(uint32_t mask)862 void Layer::setTransactionFlags(uint32_t mask) {
863     mTransactionFlags |= mask;
864 }
865 
setChildLayer(const sp<Layer> & childLayer,int32_t z)866 bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
867     ssize_t idx = mCurrentChildren.indexOf(childLayer);
868     if (idx < 0) {
869         return false;
870     }
871     if (childLayer->setLayer(z)) {
872         mCurrentChildren.removeAt(idx);
873         mCurrentChildren.add(childLayer);
874         return true;
875     }
876     return false;
877 }
878 
setChildRelativeLayer(const sp<Layer> & childLayer,const sp<IBinder> & relativeToHandle,int32_t relativeZ)879 bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
880         const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
881     ssize_t idx = mCurrentChildren.indexOf(childLayer);
882     if (idx < 0) {
883         return false;
884     }
885     if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
886         mCurrentChildren.removeAt(idx);
887         mCurrentChildren.add(childLayer);
888         return true;
889     }
890     return false;
891 }
892 
setLayer(int32_t z)893 bool Layer::setLayer(int32_t z) {
894     if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
895     mDrawingState.sequence++;
896     mDrawingState.z = z;
897     mDrawingState.modified = true;
898 
899     mFlinger->mSomeChildrenChanged = true;
900 
901     // Discard all relative layering.
902     if (mDrawingState.zOrderRelativeOf != nullptr) {
903         sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
904         if (strongRelative != nullptr) {
905             strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
906         }
907         setZOrderRelativeOf(nullptr);
908     }
909     setTransactionFlags(eTransactionNeeded);
910     return true;
911 }
912 
removeZOrderRelative(const wp<Layer> & relative)913 void Layer::removeZOrderRelative(const wp<Layer>& relative) {
914     mDrawingState.zOrderRelatives.remove(relative);
915     mDrawingState.sequence++;
916     mDrawingState.modified = true;
917     setTransactionFlags(eTransactionNeeded);
918 }
919 
addZOrderRelative(const wp<Layer> & relative)920 void Layer::addZOrderRelative(const wp<Layer>& relative) {
921     mDrawingState.zOrderRelatives.add(relative);
922     mDrawingState.modified = true;
923     mDrawingState.sequence++;
924     setTransactionFlags(eTransactionNeeded);
925 }
926 
setZOrderRelativeOf(const wp<Layer> & relativeOf)927 void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
928     mDrawingState.zOrderRelativeOf = relativeOf;
929     mDrawingState.sequence++;
930     mDrawingState.modified = true;
931     mDrawingState.isRelativeOf = relativeOf != nullptr;
932 
933     setTransactionFlags(eTransactionNeeded);
934 }
935 
setRelativeLayer(const sp<IBinder> & relativeToHandle,int32_t relativeZ)936 bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
937     sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
938     if (relative == nullptr) {
939         return false;
940     }
941 
942     if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
943         mDrawingState.zOrderRelativeOf == relative) {
944         return false;
945     }
946 
947     if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
948         (relative->mDrawingState.zOrderRelativeOf == this)) {
949         ALOGE("Detected relative layer loop between %s and %s",
950               mName.c_str(), relative->mName.c_str());
951         ALOGE("Ignoring new call to set relative layer");
952         return false;
953     }
954 
955     mFlinger->mSomeChildrenChanged = true;
956 
957     mDrawingState.sequence++;
958     mDrawingState.modified = true;
959     mDrawingState.z = relativeZ;
960 
961     auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
962     if (oldZOrderRelativeOf != nullptr) {
963         oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
964     }
965     setZOrderRelativeOf(relative);
966     relative->addZOrderRelative(wp<Layer>::fromExisting(this));
967 
968     setTransactionFlags(eTransactionNeeded);
969 
970     return true;
971 }
972 
setTrustedOverlay(bool isTrustedOverlay)973 bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
974     if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
975     mDrawingState.isTrustedOverlay = isTrustedOverlay;
976     mDrawingState.modified = true;
977     mFlinger->mUpdateInputInfo = true;
978     setTransactionFlags(eTransactionNeeded);
979     return true;
980 }
981 
isTrustedOverlay() const982 bool Layer::isTrustedOverlay() const {
983     if (getDrawingState().isTrustedOverlay) {
984         return true;
985     }
986     const auto& p = mDrawingParent.promote();
987     return (p != nullptr) && p->isTrustedOverlay();
988 }
989 
setAlpha(float alpha)990 bool Layer::setAlpha(float alpha) {
991     if (mDrawingState.color.a == alpha) return false;
992     mDrawingState.sequence++;
993     mDrawingState.color.a = alpha;
994     mDrawingState.modified = true;
995     setTransactionFlags(eTransactionNeeded);
996     return true;
997 }
998 
setBackgroundColor(const half3 & color,float alpha,ui::Dataspace dataspace)999 bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
1000     if (!mDrawingState.bgColorLayer && alpha == 0) {
1001         return false;
1002     }
1003     mDrawingState.sequence++;
1004     mDrawingState.modified = true;
1005     setTransactionFlags(eTransactionNeeded);
1006 
1007     if (!mDrawingState.bgColorLayer && alpha != 0) {
1008         // create background color layer if one does not yet exist
1009         uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
1010         std::string name = mName + "BackgroundColorLayer";
1011         mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
1012                 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
1013                                                   LayerMetadata()));
1014 
1015         // add to child list
1016         addChild(mDrawingState.bgColorLayer);
1017         mFlinger->mLayersAdded = true;
1018         // set up SF to handle added color layer
1019         if (isRemovedFromCurrentState()) {
1020             MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
1021             mDrawingState.bgColorLayer->onRemovedFromCurrentState();
1022         }
1023         mFlinger->setTransactionFlags(eTransactionNeeded);
1024     } else if (mDrawingState.bgColorLayer && alpha == 0) {
1025         MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
1026         mDrawingState.bgColorLayer->reparent(nullptr);
1027         mDrawingState.bgColorLayer = nullptr;
1028         return true;
1029     }
1030 
1031     mDrawingState.bgColorLayer->setColor(color);
1032     mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1033     mDrawingState.bgColorLayer->setAlpha(alpha);
1034     mDrawingState.bgColorLayer->setDataspace(dataspace);
1035 
1036     return true;
1037 }
1038 
setCornerRadius(float cornerRadius)1039 bool Layer::setCornerRadius(float cornerRadius) {
1040     if (mDrawingState.cornerRadius == cornerRadius) return false;
1041 
1042     mDrawingState.sequence++;
1043     mDrawingState.cornerRadius = cornerRadius;
1044     mDrawingState.modified = true;
1045     setTransactionFlags(eTransactionNeeded);
1046     return true;
1047 }
1048 
setBackgroundBlurRadius(int backgroundBlurRadius)1049 bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
1050     if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
1051     // If we start or stop drawing blur then the layer's visibility state may change so increment
1052     // the magic sequence number.
1053     if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1054         mDrawingState.sequence++;
1055     }
1056     mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1057     mDrawingState.modified = true;
1058     setTransactionFlags(eTransactionNeeded);
1059     return true;
1060 }
1061 
setTransparentRegionHint(const Region & transparent)1062 bool Layer::setTransparentRegionHint(const Region& transparent) {
1063     mDrawingState.sequence++;
1064     mDrawingState.transparentRegionHint = transparent;
1065     mDrawingState.modified = true;
1066     setTransactionFlags(eTransactionNeeded);
1067     return true;
1068 }
1069 
setBlurRegions(const std::vector<BlurRegion> & blurRegions)1070 bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
1071     // If we start or stop drawing blur then the layer's visibility state may change so increment
1072     // the magic sequence number.
1073     if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1074         mDrawingState.sequence++;
1075     }
1076     mDrawingState.blurRegions = blurRegions;
1077     mDrawingState.modified = true;
1078     setTransactionFlags(eTransactionNeeded);
1079     return true;
1080 }
1081 
setFlags(uint32_t flags,uint32_t mask)1082 bool Layer::setFlags(uint32_t flags, uint32_t mask) {
1083     const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1084     if (mDrawingState.flags == newFlags) return false;
1085     mDrawingState.sequence++;
1086     mDrawingState.flags = newFlags;
1087     mDrawingState.modified = true;
1088     setTransactionFlags(eTransactionNeeded);
1089     return true;
1090 }
1091 
setCrop(const Rect & crop)1092 bool Layer::setCrop(const Rect& crop) {
1093     if (mDrawingState.crop == crop) return false;
1094     mDrawingState.sequence++;
1095     mDrawingState.crop = crop;
1096 
1097     mDrawingState.modified = true;
1098     setTransactionFlags(eTransactionNeeded);
1099     return true;
1100 }
1101 
setMetadata(const LayerMetadata & data)1102 bool Layer::setMetadata(const LayerMetadata& data) {
1103     if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1104     mDrawingState.modified = true;
1105     setTransactionFlags(eTransactionNeeded);
1106     return true;
1107 }
1108 
setLayerStack(ui::LayerStack layerStack)1109 bool Layer::setLayerStack(ui::LayerStack layerStack) {
1110     if (mDrawingState.layerStack == layerStack) return false;
1111     mDrawingState.sequence++;
1112     mDrawingState.layerStack = layerStack;
1113     mDrawingState.modified = true;
1114     setTransactionFlags(eTransactionNeeded);
1115     return true;
1116 }
1117 
setColorSpaceAgnostic(const bool agnostic)1118 bool Layer::setColorSpaceAgnostic(const bool agnostic) {
1119     if (mDrawingState.colorSpaceAgnostic == agnostic) {
1120         return false;
1121     }
1122     mDrawingState.sequence++;
1123     mDrawingState.colorSpaceAgnostic = agnostic;
1124     mDrawingState.modified = true;
1125     setTransactionFlags(eTransactionNeeded);
1126     return true;
1127 }
1128 
setDimmingEnabled(const bool dimmingEnabled)1129 bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1130     if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1131 
1132     mDrawingState.sequence++;
1133     mDrawingState.dimmingEnabled = dimmingEnabled;
1134     mDrawingState.modified = true;
1135     setTransactionFlags(eTransactionNeeded);
1136     return true;
1137 }
1138 
setFrameRateSelectionPriority(int32_t priority)1139 bool Layer::setFrameRateSelectionPriority(int32_t priority) {
1140     if (mDrawingState.frameRateSelectionPriority == priority) return false;
1141     mDrawingState.frameRateSelectionPriority = priority;
1142     mDrawingState.sequence++;
1143     mDrawingState.modified = true;
1144     setTransactionFlags(eTransactionNeeded);
1145     return true;
1146 }
1147 
getFrameRateSelectionPriority() const1148 int32_t Layer::getFrameRateSelectionPriority() const {
1149     // Check if layer has priority set.
1150     if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1151         return mDrawingState.frameRateSelectionPriority;
1152     }
1153     // If not, search whether its parents have it set.
1154     sp<Layer> parent = getParent();
1155     if (parent != nullptr) {
1156         return parent->getFrameRateSelectionPriority();
1157     }
1158 
1159     return Layer::PRIORITY_UNSET;
1160 }
1161 
setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility)1162 bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1163     if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1164     mDrawingState.defaultFrameRateCompatibility = compatibility;
1165     mDrawingState.modified = true;
1166     mFlinger->mScheduler->setDefaultFrameRateCompatibility(sequence, compatibility);
1167     setTransactionFlags(eTransactionNeeded);
1168     return true;
1169 }
1170 
getDefaultFrameRateCompatibility() const1171 scheduler::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1172     return mDrawingState.defaultFrameRateCompatibility;
1173 }
1174 
isLayerFocusedBasedOnPriority(int32_t priority)1175 bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1176     return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1177 };
1178 
getLayerStack(LayerVector::StateSet state) const1179 ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1180     bool useDrawing = state == LayerVector::StateSet::Drawing;
1181     const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1182     if (parent) {
1183         return parent->getLayerStack();
1184     }
1185     return getDrawingState().layerStack;
1186 }
1187 
setShadowRadius(float shadowRadius)1188 bool Layer::setShadowRadius(float shadowRadius) {
1189     if (mDrawingState.shadowRadius == shadowRadius) {
1190         return false;
1191     }
1192 
1193     mDrawingState.sequence++;
1194     mDrawingState.shadowRadius = shadowRadius;
1195     mDrawingState.modified = true;
1196     setTransactionFlags(eTransactionNeeded);
1197     return true;
1198 }
1199 
setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint)1200 bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
1201     if (mDrawingState.fixedTransformHint == fixedTransformHint) {
1202         return false;
1203     }
1204 
1205     mDrawingState.sequence++;
1206     mDrawingState.fixedTransformHint = fixedTransformHint;
1207     mDrawingState.modified = true;
1208     setTransactionFlags(eTransactionNeeded);
1209     return true;
1210 }
1211 
setStretchEffect(const StretchEffect & effect)1212 bool Layer::setStretchEffect(const StretchEffect& effect) {
1213     StretchEffect temp = effect;
1214     temp.sanitize();
1215     if (mDrawingState.stretchEffect == temp) {
1216         return false;
1217     }
1218     mDrawingState.sequence++;
1219     mDrawingState.stretchEffect = temp;
1220     mDrawingState.modified = true;
1221     setTransactionFlags(eTransactionNeeded);
1222     return true;
1223 }
1224 
getStretchEffect() const1225 StretchEffect Layer::getStretchEffect() const {
1226     if (mDrawingState.stretchEffect.hasEffect()) {
1227         return mDrawingState.stretchEffect;
1228     }
1229 
1230     sp<Layer> parent = getParent();
1231     if (parent != nullptr) {
1232         auto effect = parent->getStretchEffect();
1233         if (effect.hasEffect()) {
1234             // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1235             return effect;
1236         }
1237     }
1238     return StretchEffect{};
1239 }
1240 
propagateFrameRateForLayerTree(FrameRate parentFrameRate,bool overrideChildren,bool * transactionNeeded)1241 bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool overrideChildren,
1242                                            bool* transactionNeeded) {
1243     // Gets the frame rate to propagate to children.
1244     const auto frameRate = [&] {
1245         if (overrideChildren && parentFrameRate.isValid()) {
1246             return parentFrameRate;
1247         }
1248 
1249         if (mDrawingState.frameRate.isValid()) {
1250             return mDrawingState.frameRate;
1251         }
1252 
1253         return parentFrameRate;
1254     }();
1255 
1256     auto now = systemTime();
1257     *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate, now);
1258 
1259     // The frame rate is propagated to the children by default, but some properties may override it.
1260     bool childrenHaveFrameRate = false;
1261     const bool overrideChildrenFrameRate = overrideChildren || shouldOverrideChildrenFrameRate();
1262     const bool canPropagateFrameRate = shouldPropagateFrameRate() || overrideChildrenFrameRate;
1263     for (const sp<Layer>& child : mCurrentChildren) {
1264         childrenHaveFrameRate |=
1265                 child->propagateFrameRateForLayerTree(canPropagateFrameRate ? frameRate
1266                                                                             : FrameRate(),
1267                                                       overrideChildrenFrameRate, transactionNeeded);
1268     }
1269 
1270     // If we don't have a valid frame rate specification, but the children do, we set this
1271     // layer as NoVote to allow the children to control the refresh rate
1272     if (!frameRate.isValid() && childrenHaveFrameRate) {
1273         *transactionNeeded |=
1274                 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote),
1275                                                now);
1276     }
1277 
1278     // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
1279     // the same reason we are allowing touch boost for those layers. See
1280     // RefreshRateSelector::rankFrameRates for details.
1281     const auto layerVotedWithDefaultCompatibility =
1282             frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1283     const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1284     const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
1285     const auto layerVotedWithExactCompatibility =
1286             frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1287     return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
1288             layerVotedWithExactCompatibility || childrenHaveFrameRate;
1289 }
1290 
updateTreeHasFrameRateVote()1291 void Layer::updateTreeHasFrameRateVote() {
1292     const auto root = [&]() -> sp<Layer> {
1293         sp<Layer> layer = sp<Layer>::fromExisting(this);
1294         while (auto parent = layer->getParent()) {
1295             layer = parent;
1296         }
1297         return layer;
1298     }();
1299 
1300     bool transactionNeeded = false;
1301     root->propagateFrameRateForLayerTree({}, false, &transactionNeeded);
1302 
1303     // TODO(b/195668952): we probably don't need eTraversalNeeded here
1304     if (transactionNeeded) {
1305         mFlinger->setTransactionFlags(eTraversalNeeded);
1306     }
1307 }
1308 
setFrameRate(FrameRate::FrameRateVote frameRateVote)1309 bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1310     if (mDrawingState.frameRate.vote == frameRateVote) {
1311         return false;
1312     }
1313 
1314     mDrawingState.sequence++;
1315     mDrawingState.frameRate.vote = frameRateVote;
1316     mDrawingState.modified = true;
1317 
1318     updateTreeHasFrameRateVote();
1319 
1320     setTransactionFlags(eTransactionNeeded);
1321     return true;
1322 }
1323 
setFrameRateCategory(FrameRateCategory category,bool smoothSwitchOnly)1324 bool Layer::setFrameRateCategory(FrameRateCategory category, bool smoothSwitchOnly) {
1325     if (mDrawingState.frameRate.category == category &&
1326         mDrawingState.frameRate.categorySmoothSwitchOnly == smoothSwitchOnly) {
1327         return false;
1328     }
1329 
1330     mDrawingState.sequence++;
1331     mDrawingState.frameRate.category = category;
1332     mDrawingState.frameRate.categorySmoothSwitchOnly = smoothSwitchOnly;
1333     mDrawingState.modified = true;
1334 
1335     updateTreeHasFrameRateVote();
1336 
1337     setTransactionFlags(eTransactionNeeded);
1338     return true;
1339 }
1340 
setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy)1341 bool Layer::setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy) {
1342     if (mDrawingState.frameRateSelectionStrategy == strategy) return false;
1343     mDrawingState.frameRateSelectionStrategy = strategy;
1344     mDrawingState.sequence++;
1345     mDrawingState.modified = true;
1346 
1347     updateTreeHasFrameRateVote();
1348     setTransactionFlags(eTransactionNeeded);
1349     return true;
1350 }
1351 
setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo & info,nsecs_t postTime)1352 void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1353                                                       nsecs_t postTime) {
1354     mDrawingState.postTime = postTime;
1355 
1356     // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1357     // there are two transactions with the same token, the first one without a buffer and the
1358     // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1359     // in that case.
1360     auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1361     if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
1362         // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1363         mDrawingState.bufferSurfaceFrameTX = it->second;
1364         mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1365         mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1366         mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
1367     } else {
1368         mDrawingState.bufferSurfaceFrameTX =
1369                 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1370     }
1371 
1372     setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
1373 }
1374 
setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo & info,nsecs_t postTime)1375 void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1376                                                           nsecs_t postTime) {
1377     mDrawingState.frameTimelineInfo = info;
1378     mDrawingState.postTime = postTime;
1379     mDrawingState.modified = true;
1380     setTransactionFlags(eTransactionNeeded);
1381 
1382     if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
1383         bufferSurfaceFrameTX != nullptr) {
1384         if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1385             // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1386             // being used for BufferSurfaceFrame, don't create a new one.
1387             return;
1388         }
1389     }
1390     // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1391     // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1392     // targeting different vsyncs).
1393     auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1394     if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
1395         auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
1396         mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
1397     } else {
1398         if (it->second->getPresentState() == PresentState::Presented) {
1399             // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1400             // have been from previous vsync.
1401             it->second = createSurfaceFrameForTransaction(info, postTime);
1402         }
1403     }
1404 
1405     setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
1406 }
1407 
addSurfaceFrameDroppedForBuffer(std::shared_ptr<frametimeline::SurfaceFrame> & surfaceFrame,nsecs_t dropTime)1408 void Layer::addSurfaceFrameDroppedForBuffer(
1409         std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1410     surfaceFrame->setDropTime(dropTime);
1411     surfaceFrame->setPresentState(PresentState::Dropped);
1412     mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1413 }
1414 
addSurfaceFramePresentedForBuffer(std::shared_ptr<frametimeline::SurfaceFrame> & surfaceFrame,nsecs_t acquireFenceTime,nsecs_t currentLatchTime)1415 void Layer::addSurfaceFramePresentedForBuffer(
1416         std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1417         nsecs_t currentLatchTime) {
1418     surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1419     surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1420     mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1421     updateLastLatchTime(currentLatchTime);
1422 }
1423 
createSurfaceFrameForTransaction(const FrameTimelineInfo & info,nsecs_t postTime)1424 std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1425         const FrameTimelineInfo& info, nsecs_t postTime) {
1426     auto surfaceFrame =
1427             mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1428                                                                  getSequence(), mName,
1429                                                                  mTransactionName,
1430                                                                  /*isBuffer*/ false, getGameMode());
1431     surfaceFrame->setActualStartTime(info.startTimeNanos);
1432     // For Transactions, the post time is considered to be both queue and acquire fence time.
1433     surfaceFrame->setActualQueueTime(postTime);
1434     surfaceFrame->setAcquireFenceTime(postTime);
1435     const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1436     if (fps) {
1437         surfaceFrame->setRenderRate(*fps);
1438     }
1439     onSurfaceFrameCreated(surfaceFrame);
1440     return surfaceFrame;
1441 }
1442 
createSurfaceFrameForBuffer(const FrameTimelineInfo & info,nsecs_t queueTime,std::string debugName)1443 std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1444         const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1445     auto surfaceFrame =
1446             mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1447                                                                  getSequence(), mName, debugName,
1448                                                                  /*isBuffer*/ true, getGameMode());
1449     surfaceFrame->setActualStartTime(info.startTimeNanos);
1450     // For buffers, acquire fence time will set during latch.
1451     surfaceFrame->setActualQueueTime(queueTime);
1452     const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1453     if (fps) {
1454         surfaceFrame->setRenderRate(*fps);
1455     }
1456     onSurfaceFrameCreated(surfaceFrame);
1457     return surfaceFrame;
1458 }
1459 
setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo & info,nsecs_t postTime,std::string debugName)1460 void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1461                                                   std::string debugName) {
1462     if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1463         return;
1464     }
1465 
1466     FrameTimelineInfo skippedFrameTimelineInfo = info;
1467     skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1468 
1469     auto surfaceFrame =
1470             mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1471                                                                  mOwnerPid, mOwnerUid,
1472                                                                  getSequence(), mName, debugName,
1473                                                                  /*isBuffer*/ false, getGameMode());
1474     surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1475     // For Transactions, the post time is considered to be both queue and acquire fence time.
1476     surfaceFrame->setActualQueueTime(postTime);
1477     surfaceFrame->setAcquireFenceTime(postTime);
1478     const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1479     if (fps) {
1480         surfaceFrame->setRenderRate(*fps);
1481     }
1482     onSurfaceFrameCreated(surfaceFrame);
1483     addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1484 }
1485 
setFrameRateForLayerTreeLegacy(FrameRate frameRate,nsecs_t now)1486 bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate, nsecs_t now) {
1487     if (mDrawingState.frameRateForLayerTree == frameRate) {
1488         return false;
1489     }
1490 
1491     mDrawingState.frameRateForLayerTree = frameRate;
1492 
1493     // TODO(b/195668952): we probably don't need to dirty visible regions here
1494     // or even store frameRateForLayerTree in mDrawingState
1495     mDrawingState.sequence++;
1496     mDrawingState.modified = true;
1497     setTransactionFlags(eTransactionNeeded);
1498 
1499     mFlinger->mScheduler
1500             ->recordLayerHistory(sequence, getLayerProps(), now, now,
1501                                  scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1502     return true;
1503 }
1504 
setFrameRateForLayerTree(FrameRate frameRate,const scheduler::LayerProps & layerProps,nsecs_t now)1505 bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1506                                      nsecs_t now) {
1507     if (mDrawingState.frameRateForLayerTree == frameRate) {
1508         return false;
1509     }
1510 
1511     mDrawingState.frameRateForLayerTree = frameRate;
1512     mFlinger->mScheduler
1513             ->recordLayerHistory(sequence, layerProps, now, now,
1514                                  scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1515     return true;
1516 }
1517 
getFrameRateForLayerTree() const1518 Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1519     return getDrawingState().frameRateForLayerTree;
1520 }
1521 
isHiddenByPolicy() const1522 bool Layer::isHiddenByPolicy() const {
1523     const State& s(mDrawingState);
1524     const auto& parent = mDrawingParent.promote();
1525     if (parent != nullptr && parent->isHiddenByPolicy()) {
1526         return true;
1527     }
1528     if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1529         auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1530         if (zOrderRelativeOf != nullptr) {
1531             if (zOrderRelativeOf->isHiddenByPolicy()) {
1532                 return true;
1533             }
1534         }
1535     }
1536     if (CC_UNLIKELY(!isTransformValid())) {
1537         ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1538         return true;
1539     }
1540     return s.flags & layer_state_t::eLayerHidden;
1541 }
1542 
getEffectiveUsage(uint32_t usage) const1543 uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
1544     // TODO: should we do something special if mSecure is set?
1545     if (mProtectedByApp) {
1546         // need a hardware-protected path to external video sink
1547         usage |= GraphicBuffer::USAGE_PROTECTED;
1548     }
1549     if (mPotentialCursor) {
1550         usage |= GraphicBuffer::USAGE_CURSOR;
1551     }
1552     usage |= GraphicBuffer::USAGE_HW_COMPOSER;
1553     return usage;
1554 }
1555 
updateTransformHint(ui::Transform::RotationFlags transformHint)1556 void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1557     if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1558         transformHint = ui::Transform::ROT_0;
1559     }
1560 
1561     setTransformHintLegacy(transformHint);
1562 }
1563 
1564 // ----------------------------------------------------------------------------
1565 // debugging
1566 // ----------------------------------------------------------------------------
1567 
miniDumpHeader(std::string & result)1568 void Layer::miniDumpHeader(std::string& result) {
1569     result.append(kDumpTableRowLength, '-');
1570     result.append("\n");
1571     result.append(" Layer name\n");
1572     result.append("           Z | ");
1573     result.append(" Window Type | ");
1574     result.append(" Comp Type | ");
1575     result.append(" Transform | ");
1576     result.append("  Disp Frame (LTRB) | ");
1577     result.append("         Source Crop (LTRB) | ");
1578     result.append("    Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1579     result.append(kDumpTableRowLength, '-');
1580     result.append("\n");
1581 }
1582 
miniDumpLegacy(std::string & result,const DisplayDevice & display) const1583 void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
1584     const auto outputLayer = findOutputLayerForDisplay(&display);
1585     if (!outputLayer) {
1586         return;
1587     }
1588 
1589     std::string name;
1590     if (mName.length() > 77) {
1591         std::string shortened;
1592         shortened.append(mName, 0, 36);
1593         shortened.append("[...]");
1594         shortened.append(mName, mName.length() - 36);
1595         name = std::move(shortened);
1596     } else {
1597         name = mName;
1598     }
1599 
1600     StringAppendF(&result, " %s\n", name.c_str());
1601 
1602     const State& layerState(getDrawingState());
1603     const auto& outputLayerState = outputLayer->getState();
1604 
1605     if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
1606         StringAppendF(&result, "  rel %6d | ", layerState.z);
1607     } else {
1608         StringAppendF(&result, "  %10d | ", layerState.z);
1609     }
1610     StringAppendF(&result, "  %10d | ", mWindowType);
1611     StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
1612     StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1613     const Rect& frame = outputLayerState.displayFrame;
1614     StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1615     const FloatRect& crop = outputLayerState.sourceCrop;
1616     StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1617                   crop.bottom);
1618     const auto frameRate = getFrameRateForLayerTree();
1619     if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1620         StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1621                       ftl::enum_string(frameRate.vote.type).c_str(),
1622                       ftl::enum_string(frameRate.vote.seamlessness).c_str());
1623     } else {
1624         result.append(41, ' ');
1625     }
1626 
1627     const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1628     StringAppendF(&result, "    [%s]\n", focused ? "*" : " ");
1629 
1630     result.append(kDumpTableRowLength, '-');
1631     result.append("\n");
1632 }
1633 
miniDump(std::string & result,const frontend::LayerSnapshot & snapshot,const DisplayDevice & display) const1634 void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1635                      const DisplayDevice& display) const {
1636     const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1637     if (!outputLayer) {
1638         return;
1639     }
1640 
1641     StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1642     StringAppendF(&result, "  %10zu | ", snapshot.globalZ);
1643     StringAppendF(&result, "  %10d | ",
1644                   snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1645     StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1646     const auto& outputLayerState = outputLayer->getState();
1647     StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1648     const Rect& frame = outputLayerState.displayFrame;
1649     StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1650     const FloatRect& crop = outputLayerState.sourceCrop;
1651     StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1652                   crop.bottom);
1653     const auto frameRate = snapshot.frameRate;
1654     std::string frameRateStr;
1655     if (frameRate.vote.rate.isValid()) {
1656         StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
1657     }
1658     if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1659         StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
1660                       ftl::enum_string(frameRate.vote.type).c_str(),
1661                       ftl::enum_string(frameRate.vote.seamlessness).c_str());
1662     } else if (frameRate.category != FrameRateCategory::Default) {
1663         StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
1664                       (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
1665                       ftl::enum_string(frameRate.vote.seamlessness).c_str());
1666     } else {
1667         result.append(41, ' ');
1668     }
1669 
1670     const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1671     StringAppendF(&result, "    [%s]\n", focused ? "*" : " ");
1672 
1673     result.append(kDumpTableRowLength, '-');
1674     result.append("\n");
1675 }
1676 
dumpFrameStats(std::string & result) const1677 void Layer::dumpFrameStats(std::string& result) const {
1678     mFrameTracker.dumpStats(result);
1679 }
1680 
clearFrameStats()1681 void Layer::clearFrameStats() {
1682     mFrameTracker.clearStats();
1683 }
1684 
logFrameStats()1685 void Layer::logFrameStats() {
1686     mFrameTracker.logAndResetStats(mName);
1687 }
1688 
getFrameStats(FrameStats * outStats) const1689 void Layer::getFrameStats(FrameStats* outStats) const {
1690     mFrameTracker.getStats(outStats);
1691 }
1692 
dumpOffscreenDebugInfo(std::string & result) const1693 void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1694     std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1695     StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1696                   mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
1697 }
1698 
onDisconnect()1699 void Layer::onDisconnect() {
1700     const int32_t layerId = getSequence();
1701     mFlinger->mTimeStats->onDestroy(layerId);
1702     mFlinger->mFrameTracer->onDestroy(layerId);
1703 }
1704 
getDescendantCount() const1705 size_t Layer::getDescendantCount() const {
1706     size_t count = 0;
1707     for (const sp<Layer>& child : mDrawingChildren) {
1708         count += 1 + child->getChildrenCount();
1709     }
1710     return count;
1711 }
1712 
setGameModeForTree(GameMode gameMode)1713 void Layer::setGameModeForTree(GameMode gameMode) {
1714     const auto& currentState = getDrawingState();
1715     if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1716         gameMode =
1717                 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
1718     }
1719     setGameMode(gameMode);
1720     for (const sp<Layer>& child : mCurrentChildren) {
1721         child->setGameModeForTree(gameMode);
1722     }
1723 }
1724 
addChild(const sp<Layer> & layer)1725 void Layer::addChild(const sp<Layer>& layer) {
1726     mFlinger->mSomeChildrenChanged = true;
1727     setTransactionFlags(eTransactionNeeded);
1728 
1729     mCurrentChildren.add(layer);
1730     layer->setParent(sp<Layer>::fromExisting(this));
1731     layer->setGameModeForTree(mGameMode);
1732     updateTreeHasFrameRateVote();
1733 }
1734 
removeChild(const sp<Layer> & layer)1735 ssize_t Layer::removeChild(const sp<Layer>& layer) {
1736     mFlinger->mSomeChildrenChanged = true;
1737     setTransactionFlags(eTransactionNeeded);
1738 
1739     layer->setParent(nullptr);
1740     const auto removeResult = mCurrentChildren.remove(layer);
1741 
1742     updateTreeHasFrameRateVote();
1743     layer->setGameModeForTree(GameMode::Unsupported);
1744     layer->updateTreeHasFrameRateVote();
1745 
1746     return removeResult;
1747 }
1748 
setChildrenDrawingParent(const sp<Layer> & newParent)1749 void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
1750     for (const sp<Layer>& child : mDrawingChildren) {
1751         child->mDrawingParent = newParent;
1752         const float parentShadowRadius =
1753                 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
1754         child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
1755                              parentShadowRadius);
1756     }
1757 }
1758 
reparent(const sp<IBinder> & newParentHandle)1759 bool Layer::reparent(const sp<IBinder>& newParentHandle) {
1760     sp<Layer> newParent;
1761     if (newParentHandle != nullptr) {
1762         newParent = LayerHandle::getLayer(newParentHandle);
1763         if (newParent == nullptr) {
1764             ALOGE("Unable to promote Layer handle");
1765             return false;
1766         }
1767         if (newParent == this) {
1768             ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1769             return false;
1770         }
1771     }
1772 
1773     sp<Layer> parent = getParent();
1774     if (parent != nullptr) {
1775         parent->removeChild(sp<Layer>::fromExisting(this));
1776     }
1777 
1778     if (newParentHandle != nullptr) {
1779         newParent->addChild(sp<Layer>::fromExisting(this));
1780         if (!newParent->isRemovedFromCurrentState()) {
1781             addToCurrentState();
1782         } else {
1783             onRemovedFromCurrentState();
1784         }
1785     } else {
1786         onRemovedFromCurrentState();
1787     }
1788 
1789     return true;
1790 }
1791 
setColorTransform(const mat4 & matrix)1792 bool Layer::setColorTransform(const mat4& matrix) {
1793     static const mat4 identityMatrix = mat4();
1794 
1795     if (mDrawingState.colorTransform == matrix) {
1796         return false;
1797     }
1798     ++mDrawingState.sequence;
1799     mDrawingState.colorTransform = matrix;
1800     mDrawingState.hasColorTransform = matrix != identityMatrix;
1801     mDrawingState.modified = true;
1802     setTransactionFlags(eTransactionNeeded);
1803     return true;
1804 }
1805 
getColorTransform() const1806 mat4 Layer::getColorTransform() const {
1807     mat4 colorTransform = mat4(getDrawingState().colorTransform);
1808     if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
1809         colorTransform = parent->getColorTransform() * colorTransform;
1810     }
1811     return colorTransform;
1812 }
1813 
hasColorTransform() const1814 bool Layer::hasColorTransform() const {
1815     bool hasColorTransform = getDrawingState().hasColorTransform;
1816     if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
1817         hasColorTransform = hasColorTransform || parent->hasColorTransform();
1818     }
1819     return hasColorTransform;
1820 }
1821 
isLegacyDataSpace() const1822 bool Layer::isLegacyDataSpace() const {
1823     // return true when no higher bits are set
1824     return !(getDataSpace() &
1825              (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1826               ui::Dataspace::RANGE_MASK));
1827 }
1828 
setParent(const sp<Layer> & layer)1829 void Layer::setParent(const sp<Layer>& layer) {
1830     mCurrentParent = layer;
1831 }
1832 
getZ(LayerVector::StateSet) const1833 int32_t Layer::getZ(LayerVector::StateSet) const {
1834     return mDrawingState.z;
1835 }
1836 
usingRelativeZ(LayerVector::StateSet stateSet) const1837 bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
1838     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1839     const State& state = useDrawing ? mDrawingState : mDrawingState;
1840     return state.isRelativeOf;
1841 }
1842 
makeTraversalList(LayerVector::StateSet stateSet,bool * outSkipRelativeZUsers)1843 __attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
1844         LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
1845     LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1846                         "makeTraversalList received invalid stateSet");
1847     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1848     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1849     const State& state = useDrawing ? mDrawingState : mDrawingState;
1850 
1851     if (state.zOrderRelatives.size() == 0) {
1852         *outSkipRelativeZUsers = true;
1853         return children;
1854     }
1855 
1856     LayerVector traverse(stateSet);
1857     for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1858         sp<Layer> strongRelative = weakRelative.promote();
1859         if (strongRelative != nullptr) {
1860             traverse.add(strongRelative);
1861         }
1862     }
1863 
1864     for (const sp<Layer>& child : children) {
1865         if (child->usingRelativeZ(stateSet)) {
1866             continue;
1867         }
1868         traverse.add(child);
1869     }
1870 
1871     return traverse;
1872 }
1873 
1874 /**
1875  * Negatively signed relatives are before 'this' in Z-order.
1876  */
traverseInZOrder(LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1877 void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
1878     // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1879     // produce a new list for traversing, including our relatives, and not including our children
1880     // who are relatives of another surface. In the case that there are no relative Z,
1881     // makeTraversalList returns our children directly to avoid significant overhead.
1882     // However in this case we need to take the responsibility for filtering children which
1883     // are relatives of another surface here.
1884     bool skipRelativeZUsers = false;
1885     const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
1886 
1887     size_t i = 0;
1888     for (; i < list.size(); i++) {
1889         const auto& relative = list[i];
1890         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1891             continue;
1892         }
1893 
1894         if (relative->getZ(stateSet) >= 0) {
1895             break;
1896         }
1897         relative->traverseInZOrder(stateSet, visitor);
1898     }
1899 
1900     visitor(this);
1901     for (; i < list.size(); i++) {
1902         const auto& relative = list[i];
1903 
1904         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1905             continue;
1906         }
1907         relative->traverseInZOrder(stateSet, visitor);
1908     }
1909 }
1910 
1911 /**
1912  * Positively signed relatives are before 'this' in reverse Z-order.
1913  */
traverseInReverseZOrder(LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1914 void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1915                                     const LayerVector::Visitor& visitor) {
1916     // See traverseInZOrder for documentation.
1917     bool skipRelativeZUsers = false;
1918     LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
1919 
1920     int32_t i = 0;
1921     for (i = int32_t(list.size()) - 1; i >= 0; i--) {
1922         const auto& relative = list[i];
1923 
1924         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1925             continue;
1926         }
1927 
1928         if (relative->getZ(stateSet) < 0) {
1929             break;
1930         }
1931         relative->traverseInReverseZOrder(stateSet, visitor);
1932     }
1933     visitor(this);
1934     for (; i >= 0; i--) {
1935         const auto& relative = list[i];
1936 
1937         if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1938             continue;
1939         }
1940 
1941         relative->traverseInReverseZOrder(stateSet, visitor);
1942     }
1943 }
1944 
traverse(LayerVector::StateSet state,const LayerVector::Visitor & visitor)1945 void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1946     visitor(this);
1947     const LayerVector& children =
1948           state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
1949     for (const sp<Layer>& child : children) {
1950         child->traverse(state, visitor);
1951     }
1952 }
1953 
traverseChildren(const LayerVector::Visitor & visitor)1954 void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1955     for (const sp<Layer>& child : mDrawingChildren) {
1956         visitor(child.get());
1957     }
1958 }
1959 
makeChildrenTraversalList(LayerVector::StateSet stateSet,const std::vector<Layer * > & layersInTree)1960 LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1961                                              const std::vector<Layer*>& layersInTree) {
1962     LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1963                         "makeTraversalList received invalid stateSet");
1964     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1965     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1966     const State& state = useDrawing ? mDrawingState : mDrawingState;
1967 
1968     LayerVector traverse(stateSet);
1969     for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1970         sp<Layer> strongRelative = weakRelative.promote();
1971         // Only add relative layers that are also descendents of the top most parent of the tree.
1972         // If a relative layer is not a descendent, then it should be ignored.
1973         if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1974             traverse.add(strongRelative);
1975         }
1976     }
1977 
1978     for (const sp<Layer>& child : children) {
1979         const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
1980         // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1981         // descendent of the top most parent of the tree. If it's not a descendent, then just add
1982         // the child here since it won't be added later as a relative.
1983         if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1984                                childState.zOrderRelativeOf.promote().get())) {
1985             continue;
1986         }
1987         traverse.add(child);
1988     }
1989 
1990     return traverse;
1991 }
1992 
traverseChildrenInZOrderInner(const std::vector<Layer * > & layersInTree,LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)1993 void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1994                                           LayerVector::StateSet stateSet,
1995                                           const LayerVector::Visitor& visitor) {
1996     const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
1997 
1998     size_t i = 0;
1999     for (; i < list.size(); i++) {
2000         const auto& relative = list[i];
2001         if (relative->getZ(stateSet) >= 0) {
2002             break;
2003         }
2004         relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2005     }
2006 
2007     visitor(this);
2008     for (; i < list.size(); i++) {
2009         const auto& relative = list[i];
2010         relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2011     }
2012 }
2013 
getLayersInTree(LayerVector::StateSet stateSet)2014 std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2015     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2016     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2017 
2018     std::vector<Layer*> layersInTree = {this};
2019     for (size_t i = 0; i < children.size(); i++) {
2020         const auto& child = children[i];
2021         std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2022         layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2023     }
2024 
2025     return layersInTree;
2026 }
2027 
traverseChildrenInZOrder(LayerVector::StateSet stateSet,const LayerVector::Visitor & visitor)2028 void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2029                                      const LayerVector::Visitor& visitor) {
2030     std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2031     std::sort(layersInTree.begin(), layersInTree.end());
2032     traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2033 }
2034 
getTransform() const2035 ui::Transform Layer::getTransform() const {
2036     return mEffectiveTransform;
2037 }
2038 
isTransformValid() const2039 bool Layer::isTransformValid() const {
2040     float transformDet = getTransform().det();
2041     return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2042 }
2043 
getAlpha() const2044 half Layer::getAlpha() const {
2045     const auto& p = mDrawingParent.promote();
2046 
2047     half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2048     return parentAlpha * getDrawingState().color.a;
2049 }
2050 
getFixedTransformHint() const2051 ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
2052     ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
2053     if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2054         return fixedTransformHint;
2055     }
2056     const auto& p = mCurrentParent.promote();
2057     if (!p) return fixedTransformHint;
2058     return p->getFixedTransformHint();
2059 }
2060 
getColor() const2061 half4 Layer::getColor() const {
2062     const half4 color(getDrawingState().color);
2063     return half4(color.r, color.g, color.b, getAlpha());
2064 }
2065 
getBackgroundBlurRadius() const2066 int32_t Layer::getBackgroundBlurRadius() const {
2067     if (getDrawingState().backgroundBlurRadius == 0) {
2068         return 0;
2069     }
2070 
2071     const auto& p = mDrawingParent.promote();
2072     half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2073     return parentAlpha * getDrawingState().backgroundBlurRadius;
2074 }
2075 
getBlurRegions() const2076 const std::vector<BlurRegion> Layer::getBlurRegions() const {
2077     auto regionsCopy(getDrawingState().blurRegions);
2078     float layerAlpha = getAlpha();
2079     for (auto& region : regionsCopy) {
2080         region.alpha = region.alpha * layerAlpha;
2081     }
2082     return regionsCopy;
2083 }
2084 
getRoundedCornerState() const2085 RoundedCornerState Layer::getRoundedCornerState() const {
2086     // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2087     // protected content, remove rounded corners from protected content so it
2088     // can be rendered by the DPU.
2089     if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2090         return {};
2091     }
2092 
2093     // Get parent settings
2094     RoundedCornerState parentSettings;
2095     const auto& parent = mDrawingParent.promote();
2096     if (parent != nullptr) {
2097         parentSettings = parent->getRoundedCornerState();
2098         if (parentSettings.hasRoundedCorners()) {
2099             ui::Transform t = getActiveTransform(getDrawingState());
2100             t = t.inverse();
2101             parentSettings.cropRect = t.transform(parentSettings.cropRect);
2102             parentSettings.radius.x *= t.getScaleX();
2103             parentSettings.radius.y *= t.getScaleY();
2104         }
2105     }
2106 
2107     // Get layer settings
2108     Rect layerCropRect = getCroppedBufferSize(getDrawingState());
2109     const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
2110     RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
2111     const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
2112 
2113     if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
2114         // If the parent and the layer have rounded corner settings, use the parent settings if the
2115         // parent crop is entirely inside the layer crop.
2116         // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2117         if (parentSettings.cropRect.left > layerCropRect.left &&
2118             parentSettings.cropRect.top > layerCropRect.top &&
2119             parentSettings.cropRect.right < layerCropRect.right &&
2120             parentSettings.cropRect.bottom < layerCropRect.bottom) {
2121             return parentSettings;
2122         } else {
2123             return layerSettings;
2124         }
2125     } else if (layerSettingsValid) {
2126         return layerSettings;
2127     } else if (parentSettings.hasRoundedCorners()) {
2128         return parentSettings;
2129     }
2130     return {};
2131 }
2132 
findInHierarchy(const sp<Layer> & l)2133 bool Layer::findInHierarchy(const sp<Layer>& l) {
2134     if (l == this) {
2135         return true;
2136     }
2137     for (auto& child : mDrawingChildren) {
2138       if (child->findInHierarchy(l)) {
2139           return true;
2140       }
2141     }
2142     return false;
2143 }
2144 
commitChildList()2145 void Layer::commitChildList() {
2146     for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2147         const auto& child = mCurrentChildren[i];
2148         child->commitChildList();
2149     }
2150     mDrawingChildren = mCurrentChildren;
2151     mDrawingParent = mCurrentParent;
2152     if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2153         auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2154         if (zOrderRelativeOf == nullptr) return;
2155         if (findInHierarchy(zOrderRelativeOf)) {
2156             ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2157                   zOrderRelativeOf->mName.c_str());
2158             ALOGE("Severing rel Z loop, potentially dangerous");
2159             mDrawingState.isRelativeOf = false;
2160             zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
2161         }
2162     }
2163 }
2164 
2165 
setInputInfo(const WindowInfo & info)2166 void Layer::setInputInfo(const WindowInfo& info) {
2167     mDrawingState.inputInfo = info;
2168     mDrawingState.touchableRegionCrop =
2169             LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
2170     mDrawingState.modified = true;
2171     mFlinger->mUpdateInputInfo = true;
2172     setTransactionFlags(eTransactionNeeded);
2173 }
2174 
writeToProto(perfetto::protos::LayersProto & layersProto,uint32_t traceFlags)2175 perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2176                                                   uint32_t traceFlags) {
2177     perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
2178     writeToProtoDrawingState(layerProto);
2179     writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2180 
2181     if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
2182         ui::LayerStack layerStack =
2183                 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2184         writeCompositionStateToProto(layerProto, layerStack);
2185     }
2186 
2187     for (const sp<Layer>& layer : mDrawingChildren) {
2188         layer->writeToProto(layersProto, traceFlags);
2189     }
2190 
2191     return layerProto;
2192 }
2193 
writeCompositionStateToProto(perfetto::protos::LayerProto * layerProto,ui::LayerStack layerStack)2194 void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2195                                          ui::LayerStack layerStack) {
2196     ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2197     ftl::FakeGuard mainThreadGuard(kMainThreadContext);
2198 
2199     // Only populate for the primary display.
2200     if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
2201         const auto compositionType = getCompositionType(*display);
2202         layerProto->set_hwc_composition_type(
2203                 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
2204         LayerProtoHelper::writeToProto(getVisibleRegion(display),
2205                                        [&]() { return layerProto->mutable_visible_region(); });
2206     }
2207 }
2208 
writeToProtoDrawingState(perfetto::protos::LayerProto * layerInfo)2209 void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
2210     const ui::Transform transform = getTransform();
2211     auto buffer = getExternalTexture();
2212     if (buffer != nullptr) {
2213         LayerProtoHelper::writeToProto(*buffer,
2214                                        [&]() { return layerInfo->mutable_active_buffer(); });
2215         LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2216                                                  layerInfo->mutable_buffer_transform());
2217     }
2218     layerInfo->set_invalidate(contentDirty);
2219     layerInfo->set_is_protected(isProtected());
2220     layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2221     layerInfo->set_queued_frames(getQueuedFrameCount());
2222     layerInfo->set_curr_frame(mCurrentFrameNumber);
2223     layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
2224     layerInfo->set_corner_radius(
2225             (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
2226     layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2227     layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2228     LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2229     LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2230                                            [&]() { return layerInfo->mutable_position(); });
2231     LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
2232     LayerProtoHelper::writeToProto(surfaceDamageRegion,
2233                                    [&]() { return layerInfo->mutable_damage_region(); });
2234 
2235     if (hasColorTransform()) {
2236         LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
2237     }
2238 
2239     LayerProtoHelper::writeToProto(mSourceBounds,
2240                                    [&]() { return layerInfo->mutable_source_bounds(); });
2241     LayerProtoHelper::writeToProto(mScreenBounds,
2242                                    [&]() { return layerInfo->mutable_screen_bounds(); });
2243     LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2244                                    [&]() { return layerInfo->mutable_corner_radius_crop(); });
2245     layerInfo->set_shadow_radius(mEffectiveShadowRadius);
2246 }
2247 
writeToProtoCommonState(perfetto::protos::LayerProto * layerInfo,LayerVector::StateSet stateSet,uint32_t traceFlags)2248 void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2249                                     LayerVector::StateSet stateSet, uint32_t traceFlags) {
2250     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2251     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2252     const State& state = useDrawing ? mDrawingState : mDrawingState;
2253 
2254     ui::Transform requestedTransform = state.transform;
2255 
2256     layerInfo->set_id(sequence);
2257     layerInfo->set_name(getName().c_str());
2258     layerInfo->set_type(getType());
2259 
2260     for (const auto& child : children) {
2261         layerInfo->add_children(child->sequence);
2262     }
2263 
2264     for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2265         sp<Layer> strongRelative = weakRelative.promote();
2266         if (strongRelative != nullptr) {
2267             layerInfo->add_relatives(strongRelative->sequence);
2268         }
2269     }
2270 
2271     LayerProtoHelper::writeToProto(state.transparentRegionHint,
2272                                    [&]() { return layerInfo->mutable_transparent_region(); });
2273 
2274     layerInfo->set_layer_stack(getLayerStack().id);
2275     layerInfo->set_z(state.z);
2276 
2277     LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2278         return layerInfo->mutable_requested_position();
2279     });
2280 
2281     LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2282 
2283     layerInfo->set_is_opaque(isOpaque(state));
2284 
2285     layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2286     LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2287     LayerProtoHelper::writeToProto(state.color,
2288                                    [&]() { return layerInfo->mutable_requested_color(); });
2289     layerInfo->set_flags(state.flags);
2290 
2291     LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2292                                              layerInfo->mutable_requested_transform());
2293 
2294     auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2295     if (parent != nullptr) {
2296         layerInfo->set_parent(parent->sequence);
2297     }
2298 
2299     auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2300     if (zOrderRelativeOf != nullptr) {
2301         layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2302     }
2303 
2304     layerInfo->set_is_relative_of(state.isRelativeOf);
2305 
2306     layerInfo->set_owner_uid(mOwnerUid);
2307 
2308     if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
2309         WindowInfo info;
2310         if (useDrawing) {
2311             info = fillInputInfo(
2312                     InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
2313         } else {
2314             info = state.inputInfo;
2315         }
2316 
2317         LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
2318                                        [&]() { return layerInfo->mutable_input_window_info(); });
2319     }
2320 
2321     if (traceFlags & LayerTracing::TRACE_EXTRA) {
2322         auto protoMap = layerInfo->mutable_metadata();
2323         for (const auto& entry : state.metadata.mMap) {
2324             (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2325         }
2326     }
2327 
2328     LayerProtoHelper::writeToProto(state.destinationFrame,
2329                                    [&]() { return layerInfo->mutable_destination_frame(); });
2330 }
2331 
isRemovedFromCurrentState() const2332 bool Layer::isRemovedFromCurrentState() const  {
2333     return mRemovedFromDrawingState;
2334 }
2335 
2336 // Applies the given transform to the region, while protecting against overflows caused by any
2337 // offsets. If applying the offset in the transform to any of the Rects in the region would result
2338 // in an overflow, they are not added to the output Region.
transformTouchableRegionSafely(const ui::Transform & t,const Region & r,const std::string & debugWindowName)2339 static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2340                                              const std::string& debugWindowName) {
2341     // Round the translation using the same rounding strategy used by ui::Transform.
2342     const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2343     const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2344 
2345     ui::Transform transformWithoutOffset = t;
2346     transformWithoutOffset.set(0.f, 0.f);
2347 
2348     const Region transformed = transformWithoutOffset.transform(r);
2349 
2350     // Apply the translation to each of the Rects in the region while discarding any that overflow.
2351     Region ret;
2352     for (const auto& rect : transformed) {
2353         Rect newRect;
2354         if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2355             __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2356             __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2357             __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2358             ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2359                   debugWindowName.c_str());
2360             continue;
2361         }
2362         ret.orSelf(newRect);
2363     }
2364     return ret;
2365 }
2366 
fillInputFrameInfo(WindowInfo & info,const ui::Transform & screenToDisplay)2367 void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2368     auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2369     if (!inputBoundsValid) {
2370         info.touchableRegion.clear();
2371     }
2372 
2373     info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
2374 
2375     ui::Transform inputToLayer;
2376     inputToLayer.set(inputBounds.left, inputBounds.top);
2377     const ui::Transform layerToScreen = getInputTransform();
2378     const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
2379 
2380     // InputDispatcher expects a display-to-input transform.
2381     info.transform = inputToDisplay.inverse();
2382 
2383     // The touchable region is specified in the input coordinate space. Change it to display space.
2384     info.touchableRegion =
2385             transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
2386 }
2387 
fillTouchOcclusionMode(WindowInfo & info)2388 void Layer::fillTouchOcclusionMode(WindowInfo& info) {
2389     sp<Layer> p = sp<Layer>::fromExisting(this);
2390     while (p != nullptr && !p->hasInputInfo()) {
2391         p = p->mDrawingParent.promote();
2392     }
2393     if (p != nullptr) {
2394         info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2395     }
2396 }
2397 
getDropInputMode() const2398 gui::DropInputMode Layer::getDropInputMode() const {
2399     gui::DropInputMode mode = mDrawingState.dropInputMode;
2400     if (mode == gui::DropInputMode::ALL) {
2401         return mode;
2402     }
2403     sp<Layer> parent = mDrawingParent.promote();
2404     if (parent) {
2405         gui::DropInputMode parentMode = parent->getDropInputMode();
2406         if (parentMode != gui::DropInputMode::NONE) {
2407             return parentMode;
2408         }
2409     }
2410     return mode;
2411 }
2412 
handleDropInputMode(gui::WindowInfo & info) const2413 void Layer::handleDropInputMode(gui::WindowInfo& info) const {
2414     if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
2415         return;
2416     }
2417 
2418     // Check if we need to drop input unconditionally
2419     gui::DropInputMode dropInputMode = getDropInputMode();
2420     if (dropInputMode == gui::DropInputMode::ALL) {
2421         info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
2422         ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2423         return;
2424     }
2425 
2426     // Check if we need to check if the window is obscured by parent
2427     if (dropInputMode != gui::DropInputMode::OBSCURED) {
2428         return;
2429     }
2430 
2431     // Check if the parent has set an alpha on the layer
2432     sp<Layer> parent = mDrawingParent.promote();
2433     if (parent && parent->getAlpha() != 1.0_hf) {
2434         info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
2435         ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2436               static_cast<float>(getAlpha()));
2437     }
2438 
2439     // Check if the parent has cropped the buffer
2440     Rect bufferSize = getCroppedBufferSize(getDrawingState());
2441     if (!bufferSize.isValid()) {
2442         info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
2443         return;
2444     }
2445 
2446     // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2447     // To check if the layer has been cropped, we take the buffer bounds, apply the local
2448     // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2449     // match then the layer has not been cropped by its parents.
2450     Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2451     bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2452 
2453     if (croppedByParent) {
2454         info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
2455         ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2456               getDebugName());
2457     } else {
2458         // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2459         // input if the window is obscured. This check should be done in surfaceflinger but the
2460         // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2461         // drop input events if the window is obscured.
2462         info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
2463     }
2464 }
2465 
fillInputInfo(const InputDisplayArgs & displayArgs)2466 WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
2467     if (!hasInputInfo()) {
2468         mDrawingState.inputInfo.name = getName();
2469         mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
2470         mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
2471         mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
2472         mDrawingState.inputInfo.displayId = toLogicalDisplayId(getLayerStack());
2473     }
2474 
2475     const ui::Transform& displayTransform =
2476             displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2477 
2478     WindowInfo info = mDrawingState.inputInfo;
2479     info.id = sequence;
2480     info.displayId = toLogicalDisplayId(getLayerStack());
2481 
2482     fillInputFrameInfo(info, displayTransform);
2483 
2484     if (displayArgs.transform == nullptr) {
2485         // Do not let the window receive touches if it is not associated with a valid display
2486         // transform. We still allow the window to receive keys and prevent ANRs.
2487         info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2488     }
2489 
2490     info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
2491 
2492     info.alpha = getAlpha();
2493     fillTouchOcclusionMode(info);
2494     handleDropInputMode(info);
2495 
2496     // If the window will be blacked out on a display because the display does not have the secure
2497     // flag and the layer has the secure flag set, then drop input.
2498     if (!displayArgs.isSecure && isSecure()) {
2499         info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
2500     }
2501 
2502     sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
2503     if (info.replaceTouchableRegionWithCrop) {
2504         Rect inputBoundsInDisplaySpace;
2505         if (!cropLayer) {
2506             FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2507             inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2508         } else {
2509             FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2510             inputBoundsInDisplaySpace =
2511                     cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2512         }
2513         info.touchableRegion = Region(inputBoundsInDisplaySpace);
2514     } else if (cropLayer != nullptr) {
2515         FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2516         Rect inputBoundsInDisplaySpace =
2517                 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2518         info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
2519     }
2520 
2521     // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2522     // if it was set by WM for a known system overlay
2523     if (isTrustedOverlay()) {
2524         info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2525     }
2526 
2527     // If the layer is a clone, we need to crop the input region to cloned root to prevent
2528     // touches from going outside the cloned area.
2529     if (isClone()) {
2530         info.inputConfig |= WindowInfo::InputConfig::CLONE;
2531         if (const sp<Layer> clonedRoot = getClonedRoot()) {
2532             const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
2533             info.touchableRegion = info.touchableRegion.intersect(rect);
2534         }
2535     }
2536 
2537     Rect bufferSize = getBufferSize(getDrawingState());
2538     info.contentSize = Size(bufferSize.width(), bufferSize.height());
2539 
2540     return info;
2541 }
2542 
getInputBoundsInDisplaySpace(const FloatRect & inputBounds,const ui::Transform & screenToDisplay)2543 Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2544                                          const ui::Transform& screenToDisplay) {
2545     // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2546     // frame and transform used for the layer, which determines the bounds and the coordinate space
2547     // within which the layer will receive input.
2548 
2549     // Coordinate space definitions:
2550     //   - display: The display device's coordinate space. Correlates to pixels on the display.
2551     //   - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2552     //   - layer: The coordinate space of this layer.
2553     //   - input: The coordinate space in which this layer will receive input events. This could be
2554     //            different than layer space if a surfaceInset is used, which changes the origin
2555     //            of the input space.
2556 
2557     // Crop the input bounds to ensure it is within the parent's bounds.
2558     const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2559     const ui::Transform layerToScreen = getInputTransform();
2560     const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2561     return Rect{layerToDisplay.transform(croppedInputBounds)};
2562 }
2563 
getClonedRoot()2564 sp<Layer> Layer::getClonedRoot() {
2565     if (mClonedChild != nullptr) {
2566         return sp<Layer>::fromExisting(this);
2567     }
2568     if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
2569         return nullptr;
2570     }
2571     return mDrawingParent.promote()->getClonedRoot();
2572 }
2573 
hasInputInfo() const2574 bool Layer::hasInputInfo() const {
2575     return mDrawingState.inputInfo.token != nullptr ||
2576             mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
2577 }
2578 
findOutputLayerForDisplay(const DisplayDevice * display) const2579 compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2580         const DisplayDevice* display) const {
2581     if (!display) return nullptr;
2582     if (!mFlinger->mLayerLifecycleManagerEnabled) {
2583         return display->getCompositionDisplay()->getOutputLayerForLayer(
2584                 getCompositionEngineLayerFE());
2585     }
2586     sp<LayerFE> layerFE;
2587     frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2588     for (auto& [p, layer] : mLayerFEs) {
2589         if (p == path) {
2590             layerFE = layer;
2591         }
2592     }
2593 
2594     if (!layerFE) return nullptr;
2595     return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2596 }
2597 
findOutputLayerForDisplay(const DisplayDevice * display,const frontend::LayerHierarchy::TraversalPath & path) const2598 compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2599         const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2600     if (!display) return nullptr;
2601     if (!mFlinger->mLayerLifecycleManagerEnabled) {
2602         return display->getCompositionDisplay()->getOutputLayerForLayer(
2603                 getCompositionEngineLayerFE());
2604     }
2605     sp<LayerFE> layerFE;
2606     for (auto& [p, layer] : mLayerFEs) {
2607         if (p == path) {
2608             layerFE = layer;
2609         }
2610     }
2611 
2612     if (!layerFE) return nullptr;
2613     return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2614 }
2615 
getVisibleRegion(const DisplayDevice * display) const2616 Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2617     const auto outputLayer = findOutputLayerForDisplay(display);
2618     return outputLayer ? outputLayer->getState().visibleRegion : Region();
2619 }
2620 
updateCloneBufferInfo()2621 void Layer::updateCloneBufferInfo() {
2622     if (!isClone() || !isClonedFromAlive()) {
2623         return;
2624     }
2625 
2626     sp<Layer> clonedFrom = getClonedFrom();
2627     mBufferInfo = clonedFrom->mBufferInfo;
2628     mSidebandStream = clonedFrom->mSidebandStream;
2629     surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2630     mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2631     mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2632 
2633     // After buffer info is updated, the drawingState from the real layer needs to be copied into
2634     // the cloned. This is because some properties of drawingState can change when latchBuffer is
2635     // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2636     // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2637     // the cloned drawingState again.
2638     wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2639     SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2640     wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2641     WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2642 
2643     cloneDrawingState(clonedFrom.get());
2644 
2645     mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2646     mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2647     mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2648     mDrawingState.inputInfo = tmpInputInfo;
2649 }
2650 
updateMirrorInfo(const std::deque<Layer * > & cloneRootsPendingUpdates)2651 bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
2652     if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2653         // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2654         // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2655         // that case, we want to delete the reference to the clone since we want it to get
2656         // destroyed. The root, this layer, will still be around since the client can continue
2657         // to hold a reference, but no cloned layers will be displayed.
2658         mClonedChild = nullptr;
2659         return true;
2660     }
2661 
2662     std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2663     // If the real layer exists and is in current state, add the clone as a child of the root.
2664     // There's no need to remove from drawingState when the layer is offscreen since currentState is
2665     // copied to drawingState for the root layer. So the clonedChild is always removed from
2666     // drawingState and then needs to be added back each traversal.
2667     if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2668         addChildToDrawing(mClonedChild);
2669     }
2670 
2671     mClonedChild->updateClonedDrawingState(clonedLayersMap);
2672     mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
2673     mClonedChild->updateClonedRelatives(clonedLayersMap);
2674 
2675     for (Layer* root : cloneRootsPendingUpdates) {
2676         if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2677             return false;
2678         }
2679     }
2680     return true;
2681 }
2682 
updateClonedDrawingState(std::map<sp<Layer>,sp<Layer>> & clonedLayersMap)2683 void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2684     // If the layer the clone was cloned from is alive, copy the content of the drawingState
2685     // to the clone. If the real layer is no longer alive, continue traversing the children
2686     // since we may be able to pull out other children that are still alive.
2687     if (isClonedFromAlive()) {
2688         sp<Layer> clonedFrom = getClonedFrom();
2689         cloneDrawingState(clonedFrom.get());
2690         clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
2691     }
2692 
2693     // The clone layer may have children in drawingState since they may have been created and
2694     // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2695     // that already exist, since we can just re-use them.
2696     // The drawingChildren will not get overwritten by the currentChildren since the clones are
2697     // not updated in the regular traversal. They are skipped since the root will lose the
2698     // reference to them when it copies its currentChildren to drawing.
2699     for (sp<Layer>& child : mDrawingChildren) {
2700         child->updateClonedDrawingState(clonedLayersMap);
2701     }
2702 }
2703 
updateClonedChildren(const sp<Layer> & mirrorRoot,std::map<sp<Layer>,sp<Layer>> & clonedLayersMap)2704 void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2705                                  std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2706     mDrawingChildren.clear();
2707 
2708     if (!isClonedFromAlive()) {
2709         return;
2710     }
2711 
2712     sp<Layer> clonedFrom = getClonedFrom();
2713     for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2714         if (child == mirrorRoot) {
2715             // This is to avoid cyclical mirroring.
2716             continue;
2717         }
2718         sp<Layer> clonedChild = clonedLayersMap[child];
2719         if (clonedChild == nullptr) {
2720             clonedChild = child->createClone();
2721             clonedLayersMap[child] = clonedChild;
2722         }
2723         addChildToDrawing(clonedChild);
2724         clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2725     }
2726 }
2727 
updateClonedInputInfo(const std::map<sp<Layer>,sp<Layer>> & clonedLayersMap)2728 void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2729     auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2730     if (cropLayer != nullptr) {
2731         if (clonedLayersMap.count(cropLayer) == 0) {
2732             // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2733             // self as crop layer to avoid going outside bounds.
2734             mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
2735         } else {
2736             const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2737             mDrawingState.touchableRegionCrop = clonedCropLayer;
2738         }
2739     }
2740     // Cloned layers shouldn't handle watch outside since their z order is not determined by
2741     // WM or the client.
2742     mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
2743 }
2744 
updateClonedRelatives(const std::map<sp<Layer>,sp<Layer>> & clonedLayersMap)2745 void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2746     mDrawingState.zOrderRelativeOf = wp<Layer>();
2747     mDrawingState.zOrderRelatives.clear();
2748 
2749     if (!isClonedFromAlive()) {
2750         return;
2751     }
2752 
2753     const sp<Layer>& clonedFrom = getClonedFrom();
2754     for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
2755         const sp<Layer>& relative = relativeWeak.promote();
2756         if (clonedLayersMap.count(relative) > 0) {
2757             auto& clonedRelative = clonedLayersMap.at(relative);
2758             mDrawingState.zOrderRelatives.add(clonedRelative);
2759         }
2760     }
2761 
2762     // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2763     // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2764     // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2765     // still traverse the children, but the layer with the missing relativeOf will not be shown
2766     // on screen.
2767     const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2768     if (clonedLayersMap.count(relativeOf) > 0) {
2769         const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
2770         mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2771     }
2772 
2773     updateClonedInputInfo(clonedLayersMap);
2774 
2775     for (sp<Layer>& child : mDrawingChildren) {
2776         child->updateClonedRelatives(clonedLayersMap);
2777     }
2778 }
2779 
addChildToDrawing(const sp<Layer> & layer)2780 void Layer::addChildToDrawing(const sp<Layer>& layer) {
2781     mDrawingChildren.add(layer);
2782     layer->mDrawingParent = sp<Layer>::fromExisting(this);
2783 }
2784 
isInternalDisplayOverlay() const2785 bool Layer::isInternalDisplayOverlay() const {
2786     const State& s(mDrawingState);
2787     if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2788         return true;
2789     }
2790 
2791     sp<Layer> parent = mDrawingParent.promote();
2792     return parent && parent->isInternalDisplayOverlay();
2793 }
2794 
setClonedChild(const sp<Layer> & clonedChild)2795 void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2796     mClonedChild = clonedChild;
2797     mHadClonedChild = true;
2798     mFlinger->mLayerMirrorRoots.push_back(this);
2799 }
2800 
setDropInputMode(gui::DropInputMode mode)2801 bool Layer::setDropInputMode(gui::DropInputMode mode) {
2802     if (mDrawingState.dropInputMode == mode) {
2803         return false;
2804     }
2805     mDrawingState.dropInputMode = mode;
2806     return true;
2807 }
2808 
cloneDrawingState(const Layer * from)2809 void Layer::cloneDrawingState(const Layer* from) {
2810     mDrawingState = from->mDrawingState;
2811     // Skip callback info since they are not applicable for cloned layers.
2812     mDrawingState.releaseBufferListener = nullptr;
2813     // TODO (b/238781169) currently broken for mirror layers because we do not
2814     // track release fences for mirror layers composed on other displays
2815     mDrawingState.callbackHandles = {};
2816 }
2817 
callReleaseBufferCallback(const sp<ITransactionCompletedListener> & listener,const sp<GraphicBuffer> & buffer,uint64_t framenumber,const sp<Fence> & releaseFence)2818 void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2819                                       const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2820                                       const sp<Fence>& releaseFence) {
2821     if (!listener) {
2822         return;
2823     }
2824     ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
2825     uint32_t currentMaxAcquiredBufferCount =
2826             mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2827     listener->onReleaseBuffer({buffer->getId(), framenumber},
2828                               releaseFence ? releaseFence : Fence::NO_FENCE,
2829                               currentMaxAcquiredBufferCount);
2830 }
2831 
findCallbackHandle()2832 sp<CallbackHandle> Layer::findCallbackHandle() {
2833     // If we are displayed on multiple displays in a single composition cycle then we would
2834     // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2835     //  For example we can only use it if all the displays are client comp, and we need
2836     //  to merge all the client comp fences. We could do this, but for now we just
2837     // disable the optimization when a layer is composed on multiple displays.
2838     if (mClearClientCompositionFenceOnLayerDisplayed) {
2839         mLastClientCompositionFence = nullptr;
2840     } else {
2841         mClearClientCompositionFenceOnLayerDisplayed = true;
2842     }
2843 
2844     // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2845     // buffer that was presented on this layer. The first transaction that came in this frame that
2846     // replaced the previous buffer on this layer needs this release fence, because the fence will
2847     // let the client know when that previous buffer is removed from the screen.
2848     //
2849     // Every other transaction on this layer does not need a release fence because no other
2850     // Transactions that were set on this layer this frame are going to have their preceding buffer
2851     // removed from the display this frame.
2852     //
2853     // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2854     // buffer so it doesn't need a previous release fence because the layer still needs the previous
2855     // buffer. The second transaction contains a buffer so it needs a previous release fence because
2856     // the previous buffer will be released this frame. The third transaction also contains a
2857     // buffer. It replaces the buffer in the second transaction. The buffer in the second
2858     // transaction will now no longer be presented so it is released immediately and the third
2859     // transaction doesn't need a previous release fence.
2860     sp<CallbackHandle> ch;
2861     for (auto& handle : mDrawingState.callbackHandles) {
2862         if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
2863             ch = handle;
2864             break;
2865         }
2866     }
2867     return ch;
2868 }
2869 
prepareReleaseCallbacks(ftl::Future<FenceResult> futureFenceResult,ui::LayerStack layerStack)2870 void Layer::prepareReleaseCallbacks(ftl::Future<FenceResult> futureFenceResult,
2871                                     ui::LayerStack layerStack) {
2872     sp<CallbackHandle> ch = findCallbackHandle();
2873 
2874     if (ch != nullptr) {
2875         ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2876         ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2877         ch->name = mName;
2878     } else {
2879         // If we didn't get a release callback yet (e.g. some scenarios when capturing
2880         // screenshots asynchronously) then make sure we don't drop the fence.
2881         // Older fences for the same layer stack can be dropped when a new fence arrives.
2882         // An assumption here is that RenderEngine performs work sequentially, so an
2883         // incoming fence will not fire before an existing fence.
2884         mAdditionalPreviousReleaseFences.emplace_or_replace(layerStack,
2885                                                             std::move(futureFenceResult));
2886     }
2887 
2888     if (mBufferInfo.mBuffer) {
2889         mPreviouslyPresentedLayerStacks.push_back(layerStack);
2890     }
2891 
2892     if (mDrawingState.frameNumber > 0) {
2893         mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2894     }
2895 }
2896 
onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,ui::LayerStack layerStack,std::function<FenceResult (FenceResult)> && continuation)2897 void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2898                              ui::LayerStack layerStack,
2899                              std::function<FenceResult(FenceResult)>&& continuation) {
2900     sp<CallbackHandle> ch = findCallbackHandle();
2901 
2902     if (!FlagManager::getInstance().screenshot_fence_preservation() && continuation) {
2903         futureFenceResult = ftl::Future(futureFenceResult).then(std::move(continuation)).share();
2904     }
2905 
2906     if (ch != nullptr) {
2907         ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2908         ch->previousSharedReleaseFences.emplace_back(std::move(futureFenceResult));
2909         ch->name = mName;
2910     } else if (FlagManager::getInstance().screenshot_fence_preservation()) {
2911         // If we didn't get a release callback yet, e.g. some scenarios when capturing screenshots
2912         // asynchronously, then make sure we don't drop the fence.
2913         mPreviousReleaseFenceAndContinuations.emplace_back(std::move(futureFenceResult),
2914                                                            std::move(continuation));
2915         std::vector<FenceAndContinuation> mergedFences;
2916         sp<Fence> prevFence = nullptr;
2917         // For a layer that's frequently screenshotted, try to merge fences to make sure we don't
2918         // grow unbounded.
2919         for (const auto& futureAndContinuation : mPreviousReleaseFenceAndContinuations) {
2920             auto result = futureAndContinuation.future.wait_for(0s);
2921             if (result != std::future_status::ready) {
2922                 mergedFences.emplace_back(futureAndContinuation);
2923                 continue;
2924             }
2925 
2926             mergeFence(getDebugName(),
2927                        futureAndContinuation.chain().get().value_or(Fence::NO_FENCE), prevFence);
2928         }
2929         if (prevFence != nullptr) {
2930             mergedFences.emplace_back(ftl::yield(FenceResult(std::move(prevFence))).share());
2931         }
2932 
2933         mPreviousReleaseFenceAndContinuations.swap(mergedFences);
2934     }
2935 
2936     if (mBufferInfo.mBuffer) {
2937         mPreviouslyPresentedLayerStacks.push_back(layerStack);
2938     }
2939 
2940     if (mDrawingState.frameNumber > 0) {
2941         mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2942     }
2943 }
2944 
onSurfaceFrameCreated(const std::shared_ptr<frametimeline::SurfaceFrame> & surfaceFrame)2945 void Layer::onSurfaceFrameCreated(
2946         const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2947     while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2948         // Too many SurfaceFrames pending classification. The front of the deque is probably not
2949         // tracked by FrameTimeline and will never be presented. This will only result in a memory
2950         // leak.
2951         if (hasBufferOrSidebandStreamInDrawing()) {
2952             // Only log for layers with a buffer, since we expect the jank data to be drained for
2953             // these, while there may be no jank listeners for bufferless layers.
2954             ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2955                   mName.c_str());
2956             std::string miniDump = mPendingJankClassifications.front()->miniDump();
2957             ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2958         }
2959         mPendingJankClassifications.pop_front();
2960     }
2961     mPendingJankClassifications.emplace_back(surfaceFrame);
2962 }
2963 
releasePendingBuffer(nsecs_t dequeueReadyTime)2964 void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2965     for (const auto& handle : mDrawingState.callbackHandles) {
2966         handle->transformHint = mTransformHint;
2967         handle->dequeueReadyTime = dequeueReadyTime;
2968         handle->currentMaxAcquiredBufferCount =
2969                 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2970         ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2971                               handle->previousReleaseCallbackId.framenumber);
2972     }
2973 
2974     for (auto& handle : mDrawingState.callbackHandles) {
2975         if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
2976             handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2977             break;
2978         }
2979     }
2980 
2981     std::vector<JankData> jankData;
2982     transferAvailableJankData(mDrawingState.callbackHandles, jankData);
2983     mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2984                                                                  jankData);
2985     mDrawingState.callbackHandles = {};
2986 }
2987 
willPresentCurrentTransaction() const2988 bool Layer::willPresentCurrentTransaction() const {
2989     // Returns true if the most recent Transaction applied to CurrentState will be presented.
2990     return (getSidebandStreamChanged() || getAutoRefresh() ||
2991             (mDrawingState.modified &&
2992              (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2993 }
2994 
setTransform(uint32_t transform)2995 bool Layer::setTransform(uint32_t transform) {
2996     if (mDrawingState.bufferTransform == transform) return false;
2997     mDrawingState.bufferTransform = transform;
2998     mDrawingState.modified = true;
2999     setTransactionFlags(eTransactionNeeded);
3000     return true;
3001 }
3002 
setTransformToDisplayInverse(bool transformToDisplayInverse)3003 bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3004     if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3005     mDrawingState.sequence++;
3006     mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3007     mDrawingState.modified = true;
3008     setTransactionFlags(eTransactionNeeded);
3009     return true;
3010 }
3011 
setBufferCrop(const Rect & bufferCrop)3012 bool Layer::setBufferCrop(const Rect& bufferCrop) {
3013     if (mDrawingState.bufferCrop == bufferCrop) return false;
3014 
3015     mDrawingState.sequence++;
3016     mDrawingState.bufferCrop = bufferCrop;
3017 
3018     mDrawingState.modified = true;
3019     setTransactionFlags(eTransactionNeeded);
3020     return true;
3021 }
3022 
setDestinationFrame(const Rect & destinationFrame)3023 bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3024     if (mDrawingState.destinationFrame == destinationFrame) return false;
3025 
3026     mDrawingState.sequence++;
3027     mDrawingState.destinationFrame = destinationFrame;
3028 
3029     mDrawingState.modified = true;
3030     setTransactionFlags(eTransactionNeeded);
3031     return true;
3032 }
3033 
3034 // Translate destination frame into scale and position. If a destination frame is not set, use the
3035 // provided scale and position
updateGeometry()3036 bool Layer::updateGeometry() {
3037     if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3038         mDrawingState.destinationFrame.isEmpty()) {
3039         // If destination frame is not set, use the requested transform set via
3040         // Layer::setPosition and Layer::setMatrix.
3041         return assignTransform(&mDrawingState.transform, mRequestedTransform);
3042     }
3043 
3044     Rect destRect = mDrawingState.destinationFrame;
3045     int32_t destW = destRect.width();
3046     int32_t destH = destRect.height();
3047     if (destRect.left < 0) {
3048         destRect.left = 0;
3049         destRect.right = destW;
3050     }
3051     if (destRect.top < 0) {
3052         destRect.top = 0;
3053         destRect.bottom = destH;
3054     }
3055 
3056     if (!mDrawingState.buffer) {
3057         ui::Transform t;
3058         t.set(destRect.left, destRect.top);
3059         return assignTransform(&mDrawingState.transform, t);
3060     }
3061 
3062     uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3063     uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3064     // Undo any transformations on the buffer.
3065     if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3066         std::swap(bufferWidth, bufferHeight);
3067     }
3068     uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
3069     if (mDrawingState.transformToDisplayInverse) {
3070         if (invTransform & ui::Transform::ROT_90) {
3071             std::swap(bufferWidth, bufferHeight);
3072         }
3073     }
3074 
3075     float sx = destW / static_cast<float>(bufferWidth);
3076     float sy = destH / static_cast<float>(bufferHeight);
3077     ui::Transform t;
3078     t.set(sx, 0, 0, sy);
3079     t.set(destRect.left, destRect.top);
3080     return assignTransform(&mDrawingState.transform, t);
3081 }
3082 
setMatrix(const layer_state_t::matrix22_t & matrix)3083 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3084     if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3085         mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3086         return false;
3087     }
3088 
3089     mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3090 
3091     mDrawingState.sequence++;
3092     mDrawingState.modified = true;
3093     setTransactionFlags(eTransactionNeeded);
3094 
3095     return true;
3096 }
3097 
setPosition(float x,float y)3098 bool Layer::setPosition(float x, float y) {
3099     if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3100         return false;
3101     }
3102 
3103     mRequestedTransform.set(x, y);
3104 
3105     mDrawingState.sequence++;
3106     mDrawingState.modified = true;
3107     setTransactionFlags(eTransactionNeeded);
3108 
3109     return true;
3110 }
3111 
releasePreviousBuffer()3112 void Layer::releasePreviousBuffer() {
3113     mReleasePreviousBuffer = true;
3114     if (!mBufferInfo.mBuffer ||
3115         (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3116          mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3117         // If mDrawingState has a buffer, and we are about to update again
3118         // before swapping to drawing state, then the first buffer will be
3119         // dropped and we should decrement the pending buffer count and
3120         // call any release buffer callbacks if set.
3121         callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3122                                   mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3123                                   mDrawingState.acquireFence);
3124         decrementPendingBufferCount();
3125         if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3126             mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3127             addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3128             mDrawingState.bufferSurfaceFrameTX.reset();
3129         }
3130     } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3131         callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3132                                   mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3133                                   mLastClientCompositionFence);
3134         mLastClientCompositionFence = nullptr;
3135     }
3136 }
3137 
resetDrawingStateBufferInfo()3138 void Layer::resetDrawingStateBufferInfo() {
3139     mDrawingState.producerId = 0;
3140     mDrawingState.frameNumber = 0;
3141     mDrawingState.previousFrameNumber = 0;
3142     mDrawingState.releaseBufferListener = nullptr;
3143     mDrawingState.buffer = nullptr;
3144     mDrawingState.acquireFence = sp<Fence>::make(-1);
3145     mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3146     mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3147     mDrawingState.releaseBufferEndpoint = nullptr;
3148 }
3149 
setBuffer(std::shared_ptr<renderengine::ExternalTexture> & buffer,const BufferData & bufferData,nsecs_t postTime,nsecs_t desiredPresentTime,bool isAutoTimestamp,const FrameTimelineInfo & info)3150 bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3151                       const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3152                       bool isAutoTimestamp, const FrameTimelineInfo& info) {
3153     ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
3154 
3155     const bool frameNumberChanged =
3156             bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3157     const uint64_t frameNumber =
3158             frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
3159     ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
3160 
3161     if (mDrawingState.buffer) {
3162         releasePreviousBuffer();
3163     } else if (buffer) {
3164         // if we are latching a buffer for the first time then clear the mLastLatchTime since
3165         // we don't want to incorrectly classify a frame if we miss the desired present time.
3166         updateLastLatchTime(0);
3167     }
3168 
3169     mDrawingState.desiredPresentTime = desiredPresentTime;
3170     mDrawingState.isAutoTimestamp = isAutoTimestamp;
3171     mDrawingState.latchedVsyncId = info.vsyncId;
3172     mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
3173     mDrawingState.modified = true;
3174     if (!buffer) {
3175         resetDrawingStateBufferInfo();
3176         setTransactionFlags(eTransactionNeeded);
3177         mDrawingState.bufferSurfaceFrameTX = nullptr;
3178         setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3179         return true;
3180     } else {
3181         // release sideband stream if it exists and a non null buffer is being set
3182         if (mDrawingState.sidebandStream != nullptr) {
3183             setSidebandStream(nullptr, info, postTime);
3184         }
3185     }
3186 
3187     if ((mDrawingState.producerId > bufferData.producerId) ||
3188         ((mDrawingState.producerId == bufferData.producerId) &&
3189          (mDrawingState.frameNumber > frameNumber))) {
3190         ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3191               " -> producedId=%d frameNumber=%" PRIu64,
3192               getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3193               bufferData.producerId, frameNumber);
3194         TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3195     }
3196 
3197     mDrawingState.producerId = bufferData.producerId;
3198     mDrawingState.barrierProducerId =
3199             std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
3200     mDrawingState.frameNumber = frameNumber;
3201     mDrawingState.barrierFrameNumber =
3202             std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3203 
3204     mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3205     mDrawingState.buffer = std::move(buffer);
3206     mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3207             ? bufferData.acquireFence
3208             : Fence::NO_FENCE;
3209     mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3210     if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3211         // We latched this buffer unsiganled, so we need to pass the acquire fence
3212         // on the callback instead of just the acquire time, since it's unknown at
3213         // this point.
3214         mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3215     } else {
3216         mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3217     }
3218     setTransactionFlags(eTransactionNeeded);
3219 
3220     const int32_t layerId = getSequence();
3221     mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3222                                       mOwnerUid, postTime, getGameMode());
3223 
3224     setFrameTimelineVsyncForBufferTransaction(info, postTime);
3225 
3226     if (bufferData.dequeueTime > 0) {
3227         const uint64_t bufferId = mDrawingState.buffer->getId();
3228         mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3229         mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber,
3230                                                bufferData.dequeueTime,
3231                                                FrameTracer::FrameEvent::DEQUEUE);
3232         mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3233                                                FrameTracer::FrameEvent::QUEUE);
3234     }
3235 
3236     mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3237 
3238     // If the layer had been updated a TextureView, this would make sure the present time could be
3239     // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
3240     if (mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
3241         if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3242             mUsedVsyncIdForRefreshRateSelection = true;
3243         }
3244     }
3245     return true;
3246 }
3247 
setDesiredPresentTime(nsecs_t desiredPresentTime,bool isAutoTimestamp)3248 void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3249     mDrawingState.desiredPresentTime = desiredPresentTime;
3250     mDrawingState.isAutoTimestamp = isAutoTimestamp;
3251 }
3252 
recordLayerHistoryBufferUpdate(const scheduler::LayerProps & layerProps,nsecs_t now)3253 void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
3254     ATRACE_CALL();
3255     const nsecs_t presentTime = [&] {
3256         if (!mDrawingState.isAutoTimestamp) {
3257             ATRACE_FORMAT_INSTANT("desiredPresentTime");
3258             return mDrawingState.desiredPresentTime;
3259         }
3260 
3261         if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3262             const auto prediction =
3263                     mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3264                             mDrawingState.latchedVsyncId);
3265             if (prediction.has_value()) {
3266                 ATRACE_FORMAT_INSTANT("predictedPresentTime");
3267                 mMaxTimeForUseVsyncId = prediction->presentTime +
3268                         scheduler::LayerHistory::kMaxPeriodForHistory.count();
3269                 return prediction->presentTime;
3270             }
3271         }
3272 
3273         if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
3274             return static_cast<nsecs_t>(0);
3275         }
3276 
3277         // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3278         // return "0" to tell the layer history that it will use the max refresh rate without
3279         // calculating the adaptive rate.
3280         if (mWindowType != WindowInfo::Type::APPLICATION &&
3281             mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3282             return static_cast<nsecs_t>(0);
3283         }
3284 
3285         // Return the valid present time only when the layer potentially updated a TextureView so
3286         // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3287         if (mUsedVsyncIdForRefreshRateSelection) {
3288             const auto prediction =
3289                     mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3290                             mDrawingState.latchedVsyncId);
3291             if (prediction.has_value()) {
3292                 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3293                     return prediction->presentTime;
3294                 }
3295                 mUsedVsyncIdForRefreshRateSelection = false;
3296             }
3297         }
3298 
3299         return static_cast<nsecs_t>(0);
3300     }();
3301 
3302     if (ATRACE_ENABLED() && presentTime > 0) {
3303         const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3304         ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3305     }
3306 
3307     mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
3308                                              scheduler::LayerHistory::LayerUpdateType::Buffer);
3309 }
3310 
recordLayerHistoryAnimationTx(const scheduler::LayerProps & layerProps,nsecs_t now)3311 void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
3312     const nsecs_t presentTime =
3313             mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3314     mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
3315                                              scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3316 }
3317 
setDataspace(ui::Dataspace dataspace)3318 bool Layer::setDataspace(ui::Dataspace dataspace) {
3319     if (mDrawingState.dataspace == dataspace) return false;
3320     mDrawingState.dataspace = dataspace;
3321     mDrawingState.modified = true;
3322     setTransactionFlags(eTransactionNeeded);
3323     return true;
3324 }
3325 
setExtendedRangeBrightness(float currentBufferRatio,float desiredRatio)3326 bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
3327     if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3328         mDrawingState.desiredHdrSdrRatio == desiredRatio)
3329         return false;
3330     mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3331     mDrawingState.desiredHdrSdrRatio = desiredRatio;
3332     mDrawingState.modified = true;
3333     setTransactionFlags(eTransactionNeeded);
3334     return true;
3335 }
3336 
setDesiredHdrHeadroom(float desiredRatio)3337 bool Layer::setDesiredHdrHeadroom(float desiredRatio) {
3338     if (mDrawingState.desiredHdrSdrRatio == desiredRatio) return false;
3339     mDrawingState.desiredHdrSdrRatio = desiredRatio;
3340     mDrawingState.modified = true;
3341     setTransactionFlags(eTransactionNeeded);
3342     return true;
3343 }
3344 
setCachingHint(gui::CachingHint cachingHint)3345 bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3346     if (mDrawingState.cachingHint == cachingHint) return false;
3347     mDrawingState.cachingHint = cachingHint;
3348     mDrawingState.modified = true;
3349     setTransactionFlags(eTransactionNeeded);
3350     return true;
3351 }
3352 
setHdrMetadata(const HdrMetadata & hdrMetadata)3353 bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3354     if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3355     mDrawingState.hdrMetadata = hdrMetadata;
3356     mDrawingState.modified = true;
3357     setTransactionFlags(eTransactionNeeded);
3358     return true;
3359 }
3360 
setSurfaceDamageRegion(const Region & surfaceDamage)3361 bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3362     if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
3363     mDrawingState.surfaceDamageRegion = surfaceDamage;
3364     mDrawingState.modified = true;
3365     setTransactionFlags(eTransactionNeeded);
3366     setIsSmallDirty(surfaceDamage, getTransform());
3367     return true;
3368 }
3369 
setApi(int32_t api)3370 bool Layer::setApi(int32_t api) {
3371     if (mDrawingState.api == api) return false;
3372     mDrawingState.api = api;
3373     mDrawingState.modified = true;
3374     setTransactionFlags(eTransactionNeeded);
3375     return true;
3376 }
3377 
setSidebandStream(const sp<NativeHandle> & sidebandStream,const FrameTimelineInfo & info,nsecs_t postTime)3378 bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
3379                               nsecs_t postTime) {
3380     if (mDrawingState.sidebandStream == sidebandStream) return false;
3381 
3382     if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3383         mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3384     } else if (sidebandStream != nullptr) {
3385         mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3386     }
3387 
3388     mDrawingState.sidebandStream = sidebandStream;
3389     mDrawingState.modified = true;
3390     if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3391         releasePreviousBuffer();
3392         resetDrawingStateBufferInfo();
3393         mDrawingState.bufferSurfaceFrameTX = nullptr;
3394         setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3395     }
3396     setTransactionFlags(eTransactionNeeded);
3397     if (!mSidebandStreamChanged.exchange(true)) {
3398         // mSidebandStreamChanged was false
3399         mFlinger->onLayerUpdate();
3400     }
3401     return true;
3402 }
3403 
setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>> & handles,bool willPresent)3404 bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3405                                              bool willPresent) {
3406     // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3407     if (handles.empty()) {
3408         mReleasePreviousBuffer = false;
3409         return false;
3410     }
3411 
3412     std::deque<sp<CallbackHandle>> remainingHandles;
3413     for (const auto& handle : handles) {
3414         // If this transaction set a buffer on this layer, release its previous buffer
3415         handle->releasePreviousBuffer = mReleasePreviousBuffer;
3416 
3417         // If this layer will be presented in this frame
3418         if (willPresent) {
3419             // If this transaction set an acquire fence on this layer, set its acquire time
3420             handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3421             handle->frameNumber = mDrawingState.frameNumber;
3422             handle->previousFrameNumber = mDrawingState.previousFrameNumber;
3423             if (FlagManager::getInstance().ce_fence_promise() &&
3424                 mPreviousReleaseBufferEndpoint == handle->listener) {
3425                 // Add fence from previous screenshot now so that it can be dispatched to the
3426                 // client.
3427                 for (auto& [_, future] : mAdditionalPreviousReleaseFences) {
3428                     handle->previousReleaseFences.emplace_back(std::move(future));
3429                 }
3430                 mAdditionalPreviousReleaseFences.clear();
3431             } else if (FlagManager::getInstance().screenshot_fence_preservation() &&
3432                        mPreviousReleaseBufferEndpoint == handle->listener) {
3433                 // Add fences from previous screenshots now so that they can be dispatched to the
3434                 // client.
3435                 for (const auto& futureAndContinution : mPreviousReleaseFenceAndContinuations) {
3436                     handle->previousSharedReleaseFences.emplace_back(futureAndContinution.chain());
3437                 }
3438                 mPreviousReleaseFenceAndContinuations.clear();
3439             }
3440             // Store so latched time and release fence can be set
3441             mDrawingState.callbackHandles.push_back(handle);
3442 
3443         } else { // If this layer will NOT need to be relatched and presented this frame
3444             // Queue this handle to be notified below.
3445             remainingHandles.push_back(handle);
3446         }
3447     }
3448 
3449     if (!remainingHandles.empty()) {
3450         // Notify the transaction completed threads these handles are done. These are only the
3451         // handles that were not added to the mDrawingState, which will be notified later.
3452         std::vector<JankData> jankData;
3453         transferAvailableJankData(remainingHandles, jankData);
3454         mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3455     }
3456 
3457     mReleasePreviousBuffer = false;
3458     mCallbackHandleAcquireTimeOrFence = -1;
3459 
3460     return willPresent;
3461 }
3462 
getBufferSize(const State &) const3463 Rect Layer::getBufferSize(const State& /*s*/) const {
3464     // for buffer state layers we use the display frame size as the buffer size.
3465 
3466     if (mBufferInfo.mBuffer == nullptr) {
3467         return Rect::INVALID_RECT;
3468     }
3469 
3470     uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3471     uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3472 
3473     // Undo any transformations on the buffer and return the result.
3474     if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3475         std::swap(bufWidth, bufHeight);
3476     }
3477 
3478     if (getTransformToDisplayInverse()) {
3479         uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
3480         if (invTransform & ui::Transform::ROT_90) {
3481             std::swap(bufWidth, bufHeight);
3482         }
3483     }
3484 
3485     return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3486 }
3487 
computeSourceBounds(const FloatRect & parentBounds) const3488 FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3489     if (mBufferInfo.mBuffer == nullptr) {
3490         return parentBounds;
3491     }
3492 
3493     return getBufferSize(getDrawingState()).toFloatRect();
3494 }
3495 
fenceHasSignaled() const3496 bool Layer::fenceHasSignaled() const {
3497     if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3498         return true;
3499     }
3500 
3501     const bool fenceSignaled =
3502             getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3503     if (!fenceSignaled) {
3504         mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3505                                                     TimeStats::LatchSkipReason::LateAcquire);
3506     }
3507 
3508     return fenceSignaled;
3509 }
3510 
onPreComposition(nsecs_t refreshStartTime)3511 void Layer::onPreComposition(nsecs_t refreshStartTime) {
3512     for (const auto& handle : mDrawingState.callbackHandles) {
3513         handle->refreshStartTime = refreshStartTime;
3514     }
3515 }
3516 
setAutoRefresh(bool autoRefresh)3517 void Layer::setAutoRefresh(bool autoRefresh) {
3518     mDrawingState.autoRefresh = autoRefresh;
3519 }
3520 
latchSidebandStream(bool & recomputeVisibleRegions)3521 bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3522     // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
3523     auto* snapshot = editLayerSnapshot();
3524     snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
3525 
3526     if (mSidebandStreamChanged.exchange(false)) {
3527         const State& s(getDrawingState());
3528         // mSidebandStreamChanged was true
3529         mSidebandStream = s.sidebandStream;
3530         snapshot->sidebandStream = mSidebandStream;
3531         if (mSidebandStream != nullptr) {
3532             setTransactionFlags(eTransactionNeeded);
3533             mFlinger->setTransactionFlags(eTraversalNeeded);
3534         }
3535         recomputeVisibleRegions = true;
3536 
3537         return true;
3538     }
3539     return false;
3540 }
3541 
hasFrameUpdate() const3542 bool Layer::hasFrameUpdate() const {
3543     const State& c(getDrawingState());
3544     return (mDrawingStateModified || mDrawingState.modified) &&
3545             (c.buffer != nullptr || c.bgColorLayer != nullptr);
3546 }
3547 
updateTexImage(nsecs_t latchTime,bool bgColorOnly)3548 void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
3549     const State& s(getDrawingState());
3550 
3551     if (!s.buffer) {
3552         if (bgColorOnly || mBufferInfo.mBuffer) {
3553             for (auto& handle : mDrawingState.callbackHandles) {
3554                 handle->latchTime = latchTime;
3555             }
3556         }
3557         return;
3558     }
3559 
3560     for (auto& handle : mDrawingState.callbackHandles) {
3561         if (handle->frameNumber == mDrawingState.frameNumber) {
3562             handle->latchTime = latchTime;
3563         }
3564     }
3565 
3566     const int32_t layerId = getSequence();
3567     const uint64_t bufferId = mDrawingState.buffer->getId();
3568     const uint64_t frameNumber = mDrawingState.frameNumber;
3569     const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3570     mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3571     mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3572 
3573     mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3574                                        FrameTracer::FrameEvent::ACQUIRE_FENCE);
3575     mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3576                                            FrameTracer::FrameEvent::LATCH);
3577 
3578     auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3579     if (bufferSurfaceFrame != nullptr &&
3580         bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3581         // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3582         // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3583         // are processing the next state.
3584         addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3585                                           mDrawingState.acquireFenceTime->getSignalTime(),
3586                                           latchTime);
3587         mDrawingState.bufferSurfaceFrameTX.reset();
3588     }
3589 
3590     std::deque<sp<CallbackHandle>> remainingHandles;
3591     mFlinger->getTransactionCallbackInvoker()
3592             .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3593     mDrawingState.callbackHandles = remainingHandles;
3594 
3595     mDrawingStateModified = false;
3596 }
3597 
gatherBufferInfo()3598 void Layer::gatherBufferInfo() {
3599     mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3600     mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3601     if (!mDrawingState.buffer) {
3602         mBufferInfo = {};
3603         return;
3604     }
3605 
3606     if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
3607         decrementPendingBufferCount();
3608     }
3609 
3610     mBufferInfo.mBuffer = mDrawingState.buffer;
3611     mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
3612     mBufferInfo.mFence = mDrawingState.acquireFence;
3613     mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3614     mBufferInfo.mPixelFormat =
3615             !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3616     mBufferInfo.mFrameLatencyNeeded = true;
3617     mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3618     mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3619     mBufferInfo.mFence = mDrawingState.acquireFence;
3620     mBufferInfo.mTransform = mDrawingState.bufferTransform;
3621     auto lastDataspace = mBufferInfo.mDataspace;
3622     mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3623     if (mBufferInfo.mBuffer != nullptr) {
3624         auto& mapper = GraphicBufferMapper::get();
3625         // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3626         // and don't need to possibly remaps buffers.
3627         ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3628         status_t err = OK;
3629         {
3630             ATRACE_NAME("getDataspace");
3631             err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3632         }
3633         if (err != OK || dataspace != mBufferInfo.mDataspace) {
3634             {
3635                 ATRACE_NAME("setDataspace");
3636                 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3637                                           static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3638             }
3639 
3640             // Some GPU drivers may cache gralloc metadata which means before we composite we need
3641             // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3642             // compatible with old vendors, with a ticking clock.
3643             static const int32_t kVendorVersion =
3644                     base::GetIntProperty("ro.board.api_level", __ANDROID_API_FUTURE__);
3645             if (const auto format =
3646                         static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3647                                 mBufferInfo.mBuffer->getPixelFormat());
3648                 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3649                 (format ==
3650                          aidl::android::hardware::graphics::common::PixelFormat::
3651                                  IMPLEMENTATION_DEFINED ||
3652                  format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3653                  format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3654                  format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3655                 mBufferInfo.mBuffer->remapBuffer();
3656             }
3657         }
3658     }
3659     if (lastDataspace != mBufferInfo.mDataspace) {
3660         mFlinger->mHdrLayerInfoChanged = true;
3661     }
3662     if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3663         mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
3664         mFlinger->mHdrLayerInfoChanged = true;
3665     }
3666     mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3667     mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3668     mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3669     mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3670     mBufferInfo.mApi = mDrawingState.api;
3671     mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
3672 }
3673 
computeBufferCrop(const State & s)3674 Rect Layer::computeBufferCrop(const State& s) {
3675     if (s.buffer && !s.bufferCrop.isEmpty()) {
3676         Rect bufferCrop;
3677         s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3678         return bufferCrop;
3679     } else if (s.buffer) {
3680         return s.buffer->getBounds();
3681     } else {
3682         return s.bufferCrop;
3683     }
3684 }
3685 
createClone()3686 sp<Layer> Layer::createClone() {
3687     surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3688                                            LayerMetadata());
3689     sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
3690     return layer;
3691 }
3692 
decrementPendingBufferCount()3693 void Layer::decrementPendingBufferCount() {
3694     int32_t pendingBuffers = --mPendingBufferTransactions;
3695     tracePendingBufferCount(pendingBuffers);
3696 }
3697 
tracePendingBufferCount(int32_t pendingBuffers)3698 void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3699     ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3700 }
3701 
3702 /*
3703  * We don't want to send the layer's transform to input, but rather the
3704  * parent's transform. This is because Layer's transform is
3705  * information about how the buffer is placed on screen. The parent's
3706  * transform makes more sense to send since it's information about how the
3707  * layer is placed on screen. This transform is used by input to determine
3708  * how to go from screen space back to window space.
3709  */
getInputTransform() const3710 ui::Transform Layer::getInputTransform() const {
3711     if (!hasBufferOrSidebandStream()) {
3712         return getTransform();
3713     }
3714     sp<Layer> parent = mDrawingParent.promote();
3715     if (parent == nullptr) {
3716         return ui::Transform();
3717     }
3718 
3719     return parent->getTransform();
3720 }
3721 
3722 /**
3723  * Returns the bounds used to fill the input frame and the touchable region.
3724  *
3725  * Similar to getInputTransform, we need to update the bounds to include the transform.
3726  * This is because bounds don't include the buffer transform, where the input assumes
3727  * that's already included.
3728  */
getInputBounds(bool fillParentBounds) const3729 std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3730     Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3731     FloatRect inputBounds = croppedBufferSize.toFloatRect();
3732     if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3733         mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3734         inputBounds = mDrawingState.transform.transform(inputBounds);
3735     }
3736 
3737     bool inputBoundsValid = croppedBufferSize.isValid();
3738     if (!inputBoundsValid) {
3739         /**
3740          * Input bounds are based on the layer crop or buffer size. But if we are using
3741          * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3742          * we can use the parent bounds as the input bounds if the layer does not have buffer
3743          * or a crop. We want to unify this logic but because of compat reasons we cannot always
3744          * use the parent bounds. A layer without a buffer can get input. So when a window is
3745          * initially added, its touchable region can fill its parent layer bounds and that can
3746          * have negative consequences.
3747          */
3748         inputBounds = fillParentBounds ? mBounds : FloatRect{};
3749     }
3750 
3751     // Clamp surface inset to the input bounds.
3752     const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3753     const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3754     const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3755 
3756     // Apply the insets to the input bounds.
3757     inputBounds.left += xSurfaceInset;
3758     inputBounds.top += ySurfaceInset;
3759     inputBounds.right -= xSurfaceInset;
3760     inputBounds.bottom -= ySurfaceInset;
3761 
3762     return {inputBounds, inputBoundsValid};
3763 }
3764 
isSimpleBufferUpdate(const layer_state_t & s) const3765 bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
3766     const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3767 
3768     const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3769             layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3770             layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3771             layer_state_t::eLayerStackChanged | layer_state_t::eReparent |
3772             (FlagManager::getInstance().latch_unsignaled_with_auto_refresh_changed()
3773                      ? 0
3774                      : layer_state_t::eAutoRefreshChanged);
3775 
3776     if ((s.what & requiredFlags) != requiredFlags) {
3777         ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3778                               (s.what | requiredFlags) & ~s.what);
3779         return false;
3780     }
3781 
3782     if (s.what & deniedFlags) {
3783         ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3784                               s.what & deniedFlags);
3785         return false;
3786     }
3787 
3788     if (s.what & layer_state_t::ePositionChanged) {
3789         if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3790             ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
3791             return false;
3792         }
3793     }
3794 
3795     if (s.what & layer_state_t::eAlphaChanged) {
3796         if (mDrawingState.color.a != s.color.a) {
3797             ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
3798             return false;
3799         }
3800     }
3801 
3802     if (s.what & layer_state_t::eColorTransformChanged) {
3803         if (mDrawingState.colorTransform != s.colorTransform) {
3804             ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
3805             return false;
3806         }
3807     }
3808 
3809     if (s.what & layer_state_t::eBackgroundColorChanged) {
3810         if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
3811             ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
3812             return false;
3813         }
3814     }
3815 
3816     if (s.what & layer_state_t::eMatrixChanged) {
3817         if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3818             mRequestedTransform.dtdy() != s.matrix.dtdy ||
3819             mRequestedTransform.dtdx() != s.matrix.dtdx ||
3820             mRequestedTransform.dsdy() != s.matrix.dsdy) {
3821             ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
3822             return false;
3823         }
3824     }
3825 
3826     if (s.what & layer_state_t::eCornerRadiusChanged) {
3827         if (mDrawingState.cornerRadius != s.cornerRadius) {
3828             ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
3829             return false;
3830         }
3831     }
3832 
3833     if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3834         if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3835             ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3836             return false;
3837         }
3838     }
3839 
3840     if (s.what & layer_state_t::eBufferTransformChanged) {
3841         if (mDrawingState.bufferTransform != s.bufferTransform) {
3842             ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
3843             return false;
3844         }
3845     }
3846 
3847     if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3848         if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3849             ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3850                                   __func__);
3851             return false;
3852         }
3853     }
3854 
3855     if (s.what & layer_state_t::eCropChanged) {
3856         if (mDrawingState.crop != s.crop) {
3857             ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
3858             return false;
3859         }
3860     }
3861 
3862     if (s.what & layer_state_t::eDataspaceChanged) {
3863         if (mDrawingState.dataspace != s.dataspace) {
3864             ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
3865             return false;
3866         }
3867     }
3868 
3869     if (s.what & layer_state_t::eHdrMetadataChanged) {
3870         if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3871             ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
3872             return false;
3873         }
3874     }
3875 
3876     if (s.what & layer_state_t::eSidebandStreamChanged) {
3877         if (mDrawingState.sidebandStream != s.sidebandStream) {
3878             ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
3879             return false;
3880         }
3881     }
3882 
3883     if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3884         if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3885             ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3886             return false;
3887         }
3888     }
3889 
3890     if (s.what & layer_state_t::eShadowRadiusChanged) {
3891         if (mDrawingState.shadowRadius != s.shadowRadius) {
3892             ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
3893             return false;
3894         }
3895     }
3896 
3897     if (s.what & layer_state_t::eFixedTransformHintChanged) {
3898         if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3899             ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
3900             return false;
3901         }
3902     }
3903 
3904     if (s.what & layer_state_t::eTrustedOverlayChanged) {
3905         if (mDrawingState.isTrustedOverlay != (s.trustedOverlay == gui::TrustedOverlay::ENABLED)) {
3906             ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
3907             return false;
3908         }
3909     }
3910 
3911     if (s.what & layer_state_t::eStretchChanged) {
3912         StretchEffect temp = s.stretchEffect;
3913         temp.sanitize();
3914         if (mDrawingState.stretchEffect != temp) {
3915             ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
3916             return false;
3917         }
3918     }
3919 
3920     if (s.what & layer_state_t::eBufferCropChanged) {
3921         if (mDrawingState.bufferCrop != s.bufferCrop) {
3922             ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
3923             return false;
3924         }
3925     }
3926 
3927     if (s.what & layer_state_t::eDestinationFrameChanged) {
3928         if (mDrawingState.destinationFrame != s.destinationFrame) {
3929             ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
3930             return false;
3931         }
3932     }
3933 
3934     if (s.what & layer_state_t::eDimmingEnabledChanged) {
3935         if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3936             ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
3937             return false;
3938         }
3939     }
3940 
3941     if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
3942         if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3943             mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
3944             ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
3945             return false;
3946         }
3947     }
3948 
3949     if (s.what & layer_state_t::eDesiredHdrHeadroomChanged) {
3950         if (mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
3951             ATRACE_FORMAT_INSTANT("%s: false [eDesiredHdrHeadroomChanged changed]", __func__);
3952             return false;
3953         }
3954     }
3955 
3956     return true;
3957 }
3958 
getCompositionEngineLayerFE() const3959 sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
3960     // There's no need to get a CE Layer if the layer isn't going to draw anything.
3961     return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
3962 }
3963 
getLayerSnapshot() const3964 const LayerSnapshot* Layer::getLayerSnapshot() const {
3965     return mSnapshot.get();
3966 }
3967 
editLayerSnapshot()3968 LayerSnapshot* Layer::editLayerSnapshot() {
3969     return mSnapshot.get();
3970 }
3971 
stealLayerSnapshot()3972 std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3973     return std::move(mSnapshot);
3974 }
3975 
updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot)3976 void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3977     mSnapshot = std::move(snapshot);
3978 }
3979 
getCompositionState() const3980 const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
3981     return mSnapshot.get();
3982 }
3983 
copyCompositionEngineLayerFE() const3984 sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
3985     auto result = mFlinger->getFactory().createLayerFE(mName, this);
3986     result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3987     return result;
3988 }
3989 
getCompositionEngineLayerFE(const frontend::LayerHierarchy::TraversalPath & path)3990 sp<LayerFE> Layer::getCompositionEngineLayerFE(
3991         const frontend::LayerHierarchy::TraversalPath& path) {
3992     for (auto& [p, layerFE] : mLayerFEs) {
3993         if (p == path) {
3994             return layerFE;
3995         }
3996     }
3997     auto layerFE = mFlinger->getFactory().createLayerFE(mName, this);
3998     mLayerFEs.emplace_back(path, layerFE);
3999     return layerFE;
4000 }
4001 
useSurfaceDamage()4002 void Layer::useSurfaceDamage() {
4003     if (mFlinger->mForceFullDamage) {
4004         surfaceDamageRegion = Region::INVALID_REGION;
4005     } else {
4006         surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
4007     }
4008 }
4009 
useEmptyDamage()4010 void Layer::useEmptyDamage() {
4011     surfaceDamageRegion.clear();
4012 }
4013 
isOpaque(const Layer::State & s) const4014 bool Layer::isOpaque(const Layer::State& s) const {
4015     // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
4016     // layer's opaque flag.
4017     if (!hasSomethingToDraw()) {
4018         return false;
4019     }
4020 
4021     // if the layer has the opaque flag, then we're always opaque
4022     if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
4023         return true;
4024     }
4025 
4026     // If the buffer has no alpha channel, then we are opaque
4027     if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
4028         return true;
4029     }
4030 
4031     // Lastly consider the layer opaque if drawing a color with alpha == 1.0
4032     return fillsColor() && getAlpha() == 1.0_hf;
4033 }
4034 
canReceiveInput() const4035 bool Layer::canReceiveInput() const {
4036     return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
4037 }
4038 
isVisible() const4039 bool Layer::isVisible() const {
4040     if (!hasSomethingToDraw()) {
4041         return false;
4042     }
4043 
4044     if (isHiddenByPolicy()) {
4045         return false;
4046     }
4047 
4048     return getAlpha() > 0.0f || hasBlur();
4049 }
4050 
onCompositionPresented(const DisplayDevice * display,const std::shared_ptr<FenceTime> & glDoneFence,const std::shared_ptr<FenceTime> & presentFence,const CompositorTiming & compositorTiming)4051 void Layer::onCompositionPresented(const DisplayDevice* display,
4052                                    const std::shared_ptr<FenceTime>& glDoneFence,
4053                                    const std::shared_ptr<FenceTime>& presentFence,
4054                                    const CompositorTiming& compositorTiming) {
4055     // mFrameLatencyNeeded is true when a new frame was latched for the
4056     // composition.
4057     if (!mBufferInfo.mFrameLatencyNeeded) return;
4058 
4059     for (const auto& handle : mDrawingState.callbackHandles) {
4060         handle->gpuCompositionDoneFence = glDoneFence;
4061         handle->compositorTiming = compositorTiming;
4062     }
4063 
4064     // Update mFrameTracker.
4065     nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
4066     mFrameTracker.setDesiredPresentTime(desiredPresentTime);
4067 
4068     const int32_t layerId = getSequence();
4069     mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4070 
4071     const auto outputLayer = findOutputLayerForDisplay(display);
4072     if (outputLayer && outputLayer->requiresClientComposition()) {
4073         nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4074         mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4075                                                clientCompositionTimestamp,
4076                                                FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4077         // Update the SurfaceFrames in the drawing state
4078         if (mDrawingState.bufferSurfaceFrameTX) {
4079             mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4080         }
4081         for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4082             surfaceFrame->setGpuComposition();
4083         }
4084     }
4085 
4086     std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4087     if (frameReadyFence->isValid()) {
4088         mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4089     } else {
4090         // There was no fence for this frame, so assume that it was ready
4091         // to be presented at the desired present time.
4092         mFrameTracker.setFrameReadyTime(desiredPresentTime);
4093     }
4094 
4095     if (display) {
4096         const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
4097         const std::optional<Fps> renderRate =
4098                 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4099 
4100         const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
4101         const auto gameMode = getGameMode();
4102 
4103         if (presentFence->isValid()) {
4104             mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4105                                                   refreshRate, renderRate, vote, gameMode);
4106             mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4107                                                presentFence,
4108                                                FrameTracer::FrameEvent::PRESENT_FENCE);
4109             mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4110         } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4111                    displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
4112             // The HWC doesn't support present fences, so use the present timestamp instead.
4113             const nsecs_t presentTimestamp =
4114                     mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4115 
4116             const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4117             const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4118             const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4119 
4120             mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4121                                                  refreshRate, renderRate, vote, gameMode);
4122             mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4123                                                    mCurrentFrameNumber, actualPresentTime,
4124                                                    FrameTracer::FrameEvent::PRESENT_FENCE);
4125             mFrameTracker.setActualPresentTime(actualPresentTime);
4126         }
4127     }
4128 
4129     mFrameTracker.advanceFrame();
4130     mBufferInfo.mFrameLatencyNeeded = false;
4131 }
4132 
willReleaseBufferOnLatch() const4133 bool Layer::willReleaseBufferOnLatch() const {
4134     return !mDrawingState.buffer && mBufferInfo.mBuffer;
4135 }
4136 
latchBuffer(bool & recomputeVisibleRegions,nsecs_t latchTime)4137 bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
4138     const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4139     return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4140 }
4141 
latchBufferImpl(bool & recomputeVisibleRegions,nsecs_t latchTime,bool bgColorOnly)4142 bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
4143     ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4144                           getDrawingState().frameNumber);
4145 
4146     bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4147 
4148     if (refreshRequired) {
4149         return refreshRequired;
4150     }
4151 
4152     // If the head buffer's acquire fence hasn't signaled yet, return and
4153     // try again later
4154     if (!fenceHasSignaled()) {
4155         ATRACE_NAME("!fenceHasSignaled()");
4156         mFlinger->onLayerUpdate();
4157         return false;
4158     }
4159     updateTexImage(latchTime, bgColorOnly);
4160 
4161     // Capture the old state of the layer for comparisons later
4162     BufferInfo oldBufferInfo = mBufferInfo;
4163     const bool oldOpacity = isOpaque(mDrawingState);
4164     mPreviousFrameNumber = mCurrentFrameNumber;
4165     mCurrentFrameNumber = mDrawingState.frameNumber;
4166     gatherBufferInfo();
4167 
4168     if (mBufferInfo.mBuffer) {
4169         // We latched a buffer that will be presented soon. Clear the previously presented layer
4170         // stack list.
4171         mPreviouslyPresentedLayerStacks.clear();
4172     }
4173 
4174     if (mDrawingState.buffer == nullptr) {
4175         const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4176         recomputeVisibleRegions = bufferReleased;
4177         return bufferReleased;
4178     }
4179 
4180     if (oldBufferInfo.mBuffer == nullptr) {
4181         // the first time we receive a buffer, we need to trigger a
4182         // geometry invalidation.
4183         recomputeVisibleRegions = true;
4184     }
4185 
4186     if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4187         (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4188         (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4189         (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4190         recomputeVisibleRegions = true;
4191     }
4192 
4193     if (oldBufferInfo.mBuffer != nullptr) {
4194         uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4195         uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4196         if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4197             bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4198             recomputeVisibleRegions = true;
4199         }
4200     }
4201 
4202     if (oldOpacity != isOpaque(mDrawingState)) {
4203         recomputeVisibleRegions = true;
4204     }
4205 
4206     return true;
4207 }
4208 
hasReadyFrame() const4209 bool Layer::hasReadyFrame() const {
4210     return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4211 }
4212 
isProtected() const4213 bool Layer::isProtected() const {
4214     return (mBufferInfo.mBuffer != nullptr) &&
4215             (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4216 }
4217 
latchAndReleaseBuffer()4218 void Layer::latchAndReleaseBuffer() {
4219     if (hasReadyFrame()) {
4220         bool ignored = false;
4221         latchBuffer(ignored, systemTime());
4222     }
4223     releasePendingBuffer(systemTime());
4224 }
4225 
getPixelFormat() const4226 PixelFormat Layer::getPixelFormat() const {
4227     return mBufferInfo.mPixelFormat;
4228 }
4229 
getTransformToDisplayInverse() const4230 bool Layer::getTransformToDisplayInverse() const {
4231     return mBufferInfo.mTransformToDisplayInverse;
4232 }
4233 
getBufferCrop() const4234 Rect Layer::getBufferCrop() const {
4235     // this is the crop rectangle that applies to the buffer
4236     // itself (as opposed to the window)
4237     if (!mBufferInfo.mCrop.isEmpty()) {
4238         // if the buffer crop is defined, we use that
4239         return mBufferInfo.mCrop;
4240     } else if (mBufferInfo.mBuffer != nullptr) {
4241         // otherwise we use the whole buffer
4242         return mBufferInfo.mBuffer->getBounds();
4243     } else {
4244         // if we don't have a buffer yet, we use an empty/invalid crop
4245         return Rect();
4246     }
4247 }
4248 
getBufferTransform() const4249 uint32_t Layer::getBufferTransform() const {
4250     return mBufferInfo.mTransform;
4251 }
4252 
getDataSpace() const4253 ui::Dataspace Layer::getDataSpace() const {
4254     return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4255 }
4256 
isFrontBuffered() const4257 bool Layer::isFrontBuffered() const {
4258     if (mBufferInfo.mBuffer == nullptr) {
4259         return false;
4260     }
4261 
4262     return mBufferInfo.mBuffer->getUsage() & AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
4263 }
4264 
translateDataspace(ui::Dataspace dataspace)4265 ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4266     ui::Dataspace updatedDataspace = dataspace;
4267     // translate legacy dataspaces to modern dataspaces
4268     switch (dataspace) {
4269         // Treat unknown dataspaces as V0_sRGB
4270         case ui::Dataspace::UNKNOWN:
4271         case ui::Dataspace::SRGB:
4272             updatedDataspace = ui::Dataspace::V0_SRGB;
4273             break;
4274         case ui::Dataspace::SRGB_LINEAR:
4275             updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4276             break;
4277         case ui::Dataspace::JFIF:
4278             updatedDataspace = ui::Dataspace::V0_JFIF;
4279             break;
4280         case ui::Dataspace::BT601_625:
4281             updatedDataspace = ui::Dataspace::V0_BT601_625;
4282             break;
4283         case ui::Dataspace::BT601_525:
4284             updatedDataspace = ui::Dataspace::V0_BT601_525;
4285             break;
4286         case ui::Dataspace::BT709:
4287             updatedDataspace = ui::Dataspace::V0_BT709;
4288             break;
4289         default:
4290             break;
4291     }
4292 
4293     return updatedDataspace;
4294 }
4295 
getBuffer() const4296 sp<GraphicBuffer> Layer::getBuffer() const {
4297     return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4298 }
4299 
setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint)4300 void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4301     mTransformHintLegacy = getFixedTransformHint();
4302     if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4303         mTransformHintLegacy = displayTransformHint;
4304     }
4305 }
4306 
getExternalTexture() const4307 const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4308     return mBufferInfo.mBuffer;
4309 }
4310 
setColor(const half3 & color)4311 bool Layer::setColor(const half3& color) {
4312     if (mDrawingState.color.rgb == color) {
4313         return false;
4314     }
4315 
4316     mDrawingState.sequence++;
4317     mDrawingState.color.rgb = color;
4318     mDrawingState.modified = true;
4319     setTransactionFlags(eTransactionNeeded);
4320     return true;
4321 }
4322 
fillsColor() const4323 bool Layer::fillsColor() const {
4324     return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4325             mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4326 }
4327 
hasBlur() const4328 bool Layer::hasBlur() const {
4329     return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4330 }
4331 
updateSnapshot(bool updateGeometry)4332 void Layer::updateSnapshot(bool updateGeometry) {
4333     if (!getCompositionEngineLayerFE()) {
4334         return;
4335     }
4336 
4337     auto* snapshot = editLayerSnapshot();
4338     if (updateGeometry) {
4339         prepareBasicGeometryCompositionState();
4340         prepareGeometryCompositionState();
4341         snapshot->roundedCorner = getRoundedCornerState();
4342         snapshot->transformedBounds = mScreenBounds;
4343         if (mEffectiveShadowRadius > 0.f) {
4344             snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4345 
4346             // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4347             // it if transparent regions are present. This may not be necessary since shadows are
4348             // typically cast by layers without transparent regions.
4349             snapshot->shadowSettings.boundaries = mBounds;
4350 
4351             const float casterAlpha = snapshot->alpha;
4352             const bool casterIsOpaque =
4353                     ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4354 
4355             // If the casting layer is translucent, we need to fill in the shadow underneath the
4356             // layer. Otherwise the generated shadow will only be shown around the casting layer.
4357             snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4358             snapshot->shadowSettings.ambientColor *= casterAlpha;
4359             snapshot->shadowSettings.spotColor *= casterAlpha;
4360         }
4361         snapshot->shadowSettings.length = mEffectiveShadowRadius;
4362     }
4363     snapshot->contentOpaque = isOpaque(mDrawingState);
4364     snapshot->layerOpaqueFlagSet =
4365             (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
4366     sp<Layer> p = mDrawingParent.promote();
4367     if (p != nullptr) {
4368         snapshot->parentTransform = p->getTransform();
4369     } else {
4370         snapshot->parentTransform.reset();
4371     }
4372     snapshot->bufferSize = getBufferSize(mDrawingState);
4373     snapshot->externalTexture = mBufferInfo.mBuffer;
4374     snapshot->hasReadyFrame = hasReadyFrame();
4375     preparePerFrameCompositionState();
4376 }
4377 
updateChildrenSnapshots(bool updateGeometry)4378 void Layer::updateChildrenSnapshots(bool updateGeometry) {
4379     for (const sp<Layer>& child : mDrawingChildren) {
4380         child->updateSnapshot(updateGeometry);
4381         child->updateChildrenSnapshots(updateGeometry);
4382     }
4383 }
4384 
updateMetadataSnapshot(const LayerMetadata & parentMetadata)4385 void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4386     mSnapshot->layerMetadata = parentMetadata;
4387     mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4388     for (const sp<Layer>& child : mDrawingChildren) {
4389         child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4390     }
4391 }
4392 
updateRelativeMetadataSnapshot(const LayerMetadata & relativeLayerMetadata,std::unordered_set<Layer * > & visited)4393 void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4394                                            std::unordered_set<Layer*>& visited) {
4395     if (visited.find(this) != visited.end()) {
4396         ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4397         return;
4398     }
4399     visited.insert(this);
4400 
4401     mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4402 
4403     if (mDrawingState.zOrderRelatives.empty()) {
4404         return;
4405     }
4406     LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4407     childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4408     for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4409         sp<Layer> relative = weakRelative.promote();
4410         if (!relative) {
4411             continue;
4412         }
4413         relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4414     }
4415 }
4416 
setTrustedPresentationInfo(TrustedPresentationThresholds const & thresholds,TrustedPresentationListener const & listener)4417 bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
4418                                        TrustedPresentationListener const& listener) {
4419     bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4420     mTrustedPresentationListener = listener;
4421     mTrustedPresentationThresholds = thresholds;
4422     bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4423     if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4424         mFlinger->mNumTrustedPresentationListeners++;
4425     } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4426         mFlinger->mNumTrustedPresentationListeners--;
4427     }
4428 
4429     // Reset trusted presentation states to ensure we start the time again.
4430     mEnteredTrustedPresentationStateTime = -1;
4431     mLastReportedTrustedPresentationState = false;
4432     mLastComputedTrustedPresentationState = false;
4433 
4434     // If there's a new trusted presentation listener, the code needs to go through the composite
4435     // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4436     // we're already in the requested state.
4437     return haveTrustedPresentationListener;
4438 }
4439 
updateLastLatchTime(nsecs_t latchTime)4440 void Layer::updateLastLatchTime(nsecs_t latchTime) {
4441     mLastLatchTime = latchTime;
4442 }
4443 
setIsSmallDirty(const Region & damageRegion,const ui::Transform & layerToDisplayTransform)4444 void Layer::setIsSmallDirty(const Region& damageRegion,
4445                             const ui::Transform& layerToDisplayTransform) {
4446     mSmallDirty = false;
4447     if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
4448         return;
4449     }
4450 
4451     if (mWindowType != WindowInfo::Type::APPLICATION &&
4452         mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4453         return;
4454     }
4455 
4456     Rect bounds = damageRegion.getBounds();
4457     if (!bounds.isValid()) {
4458         return;
4459     }
4460 
4461     // Transform to screen space.
4462     bounds = layerToDisplayTransform.transform(bounds);
4463 
4464     // If the damage region is a small dirty, this could give the hint for the layer history that
4465     // it could suppress the heuristic rate when calculating.
4466     mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
4467                                                          bounds.getWidth() * bounds.getHeight());
4468 }
4469 
setIsSmallDirty(frontend::LayerSnapshot * snapshot)4470 void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
4471     setIsSmallDirty(snapshot->surfaceDamage, snapshot->localTransform);
4472     snapshot->isSmallDirty = mSmallDirty;
4473 }
4474 
4475 } // namespace android
4476 
4477 #if defined(__gl_h_)
4478 #error "don't include gl/gl.h in this file"
4479 #endif
4480 
4481 #if defined(__gl2_h_)
4482 #error "don't include gl2/gl2.h in this file"
4483 #endif
4484 
4485 // TODO(b/129481165): remove the #pragma below and fix conversion issues
4486 #pragma clang diagnostic pop // ignored "-Wconversion"
4487