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