• 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 #pragma once
18 
19 #include <android/gui/DropInputMode.h>
20 #include <android/gui/ISurfaceComposerClient.h>
21 #include <gui/BufferQueue.h>
22 #include <gui/LayerState.h>
23 #include <gui/WindowInfo.h>
24 #include <layerproto/LayerProtoHeader.h>
25 #include <math/vec4.h>
26 #include <renderengine/Mesh.h>
27 #include <renderengine/Texture.h>
28 #include <sys/types.h>
29 #include <ui/BlurRegion.h>
30 #include <ui/FloatRect.h>
31 #include <ui/FrameStats.h>
32 #include <ui/GraphicBuffer.h>
33 #include <ui/PixelFormat.h>
34 #include <ui/Region.h>
35 #include <ui/StretchEffect.h>
36 #include <ui/Transform.h>
37 #include <utils/RefBase.h>
38 #include <utils/Timers.h>
39 
40 #include <compositionengine/LayerFE.h>
41 #include <compositionengine/LayerFECompositionState.h>
42 #include <scheduler/Fps.h>
43 #include <scheduler/Seamlessness.h>
44 
45 #include <chrono>
46 #include <cstdint>
47 #include <list>
48 #include <optional>
49 #include <vector>
50 
51 #include "Client.h"
52 #include "DisplayHardware/HWComposer.h"
53 #include "FrameTracker.h"
54 #include "LayerFE.h"
55 #include "LayerVector.h"
56 #include "Scheduler/LayerInfo.h"
57 #include "SurfaceFlinger.h"
58 #include "Tracing/LayerTracing.h"
59 #include "TransactionCallbackInvoker.h"
60 
61 using namespace android::surfaceflinger;
62 
63 namespace android {
64 
65 class Client;
66 class Colorizer;
67 class DisplayDevice;
68 class GraphicBuffer;
69 class SurfaceFlinger;
70 
71 namespace compositionengine {
72 class OutputLayer;
73 struct LayerFECompositionState;
74 }
75 
76 namespace gui {
77 class LayerDebugInfo;
78 }
79 
80 namespace frametimeline {
81 class SurfaceFrame;
82 } // namespace frametimeline
83 
84 class Layer : public virtual RefBase {
85 public:
86     // The following constants represent priority of the window. SF uses this information when
87     // deciding which window has a priority when deciding about the refresh rate of the screen.
88     // Priority 0 is considered the highest priority. -1 means that the priority is unset.
89     static constexpr int32_t PRIORITY_UNSET = -1;
90     // Windows that are in focus and voted for the preferred mode ID
91     static constexpr int32_t PRIORITY_FOCUSED_WITH_MODE = 0;
92     // // Windows that are in focus, but have not requested a specific mode ID.
93     static constexpr int32_t PRIORITY_FOCUSED_WITHOUT_MODE = 1;
94     // Windows that are not in focus, but voted for a specific mode ID.
95     static constexpr int32_t PRIORITY_NOT_FOCUSED_WITH_MODE = 2;
96 
97     enum { // flags for doTransaction()
98         eDontUpdateGeometryState = 0x00000001,
99         eVisibleRegion = 0x00000002,
100         eInputInfoChanged = 0x00000004
101     };
102 
103     struct Geometry {
104         uint32_t w;
105         uint32_t h;
106         ui::Transform transform;
107 
108         inline bool operator==(const Geometry& rhs) const {
109             return (w == rhs.w && h == rhs.h) && (transform.tx() == rhs.transform.tx()) &&
110                     (transform.ty() == rhs.transform.ty());
111         }
112         inline bool operator!=(const Geometry& rhs) const { return !operator==(rhs); }
113     };
114 
115     using FrameRate = scheduler::LayerInfo::FrameRate;
116     using FrameRateCompatibility = scheduler::LayerInfo::FrameRateCompatibility;
117 
118     struct State {
119         int32_t z;
120         ui::LayerStack layerStack;
121         uint32_t flags;
122         int32_t sequence; // changes when visible regions can change
123         bool modified;
124         // Crop is expressed in layer space coordinate.
125         Rect crop;
126         LayerMetadata metadata;
127         // If non-null, a Surface this Surface's Z-order is interpreted relative to.
128         wp<Layer> zOrderRelativeOf;
129         bool isRelativeOf{false};
130 
131         // A list of surfaces whose Z-order is interpreted relative to ours.
132         SortedVector<wp<Layer>> zOrderRelatives;
133         half4 color;
134         float cornerRadius;
135         int backgroundBlurRadius;
136         gui::WindowInfo inputInfo;
137         wp<Layer> touchableRegionCrop;
138 
139         ui::Dataspace dataspace;
140 
141         uint64_t frameNumber;
142         // high watermark framenumber to use to check for barriers to protect ourselves
143         // from out of order transactions
144         uint64_t barrierFrameNumber;
145         ui::Transform transform;
146 
147         uint32_t producerId = 0;
148         // high watermark producerId to use to check for barriers to protect ourselves
149         // from out of order transactions
150         uint32_t barrierProducerId = 0;
151 
152         uint32_t bufferTransform;
153         bool transformToDisplayInverse;
154         Region transparentRegionHint;
155         std::shared_ptr<renderengine::ExternalTexture> buffer;
156         sp<Fence> acquireFence;
157         std::shared_ptr<FenceTime> acquireFenceTime;
158         HdrMetadata hdrMetadata;
159         Region surfaceDamageRegion;
160         int32_t api;
161         sp<NativeHandle> sidebandStream;
162         mat4 colorTransform;
163         bool hasColorTransform;
164         // pointer to background color layer that, if set, appears below the buffer state layer
165         // and the buffer state layer's children.  Z order will be set to
166         // INT_MIN
167         sp<Layer> bgColorLayer;
168 
169         // The deque of callback handles for this frame. The back of the deque contains the most
170         // recent callback handle.
171         std::deque<sp<CallbackHandle>> callbackHandles;
172         bool colorSpaceAgnostic;
173         nsecs_t desiredPresentTime = 0;
174         bool isAutoTimestamp = true;
175 
176         // Length of the cast shadow. If the radius is > 0, a shadow of length shadowRadius will
177         // be rendered around the layer.
178         float shadowRadius;
179 
180         // Layer regions that are made of custom materials, like frosted glass
181         std::vector<BlurRegion> blurRegions;
182 
183         // Priority of the layer assigned by Window Manager.
184         int32_t frameRateSelectionPriority;
185 
186         // Default frame rate compatibility used to set the layer refresh rate votetype.
187         FrameRateCompatibility defaultFrameRateCompatibility;
188         FrameRate frameRate;
189 
190         // The combined frame rate of parents / children of this layer
191         FrameRate frameRateForLayerTree;
192 
193         // Set by window manager indicating the layer and all its children are
194         // in a different orientation than the display. The hint suggests that
195         // the graphic producers should receive a transform hint as if the
196         // display was in this orientation. When the display changes to match
197         // the layer orientation, the graphic producer may not need to allocate
198         // a buffer of a different size. ui::Transform::ROT_INVALID means the
199         // a fixed transform hint is not set.
200         ui::Transform::RotationFlags fixedTransformHint;
201 
202         // The vsync info that was used to start the transaction
203         FrameTimelineInfo frameTimelineInfo;
204 
205         // When the transaction was posted
206         nsecs_t postTime;
207         sp<ITransactionCompletedListener> releaseBufferListener;
208         // SurfaceFrame that tracks the timeline of Transactions that contain a Buffer. Only one
209         // such SurfaceFrame exists because only one buffer can be presented on the layer per vsync.
210         // If multiple buffers are queued, the prior ones will be dropped, along with the
211         // SurfaceFrame that's tracking them.
212         std::shared_ptr<frametimeline::SurfaceFrame> bufferSurfaceFrameTX;
213         // A map of token(frametimelineVsyncId) to the SurfaceFrame that's tracking a transaction
214         // that contains the token. Only one SurfaceFrame exisits for transactions that share the
215         // same token, unless they are presented in different vsyncs.
216         std::unordered_map<int64_t, std::shared_ptr<frametimeline::SurfaceFrame>>
217                 bufferlessSurfaceFramesTX;
218         // An arbitrary threshold for the number of BufferlessSurfaceFrames in the state. Used to
219         // trigger a warning if the number of SurfaceFrames crosses the threshold.
220         static constexpr uint32_t kStateSurfaceFramesThreshold = 25;
221 
222         // Stretch effect to apply to this layer
223         StretchEffect stretchEffect;
224 
225         // Whether or not this layer is a trusted overlay for input
226         bool isTrustedOverlay;
227         Rect bufferCrop;
228         Rect destinationFrame;
229         sp<IBinder> releaseBufferEndpoint;
230         gui::DropInputMode dropInputMode;
231         bool autoRefresh = false;
232         bool dimmingEnabled = true;
233         float currentHdrSdrRatio = 1.f;
234         float desiredHdrSdrRatio = 1.f;
235         gui::CachingHint cachingHint = gui::CachingHint::Enabled;
236         int64_t latchedVsyncId = 0;
237         bool useVsyncIdForRefreshRateSelection = false;
238     };
239 
240     explicit Layer(const LayerCreationArgs& args);
241     virtual ~Layer();
242 
243     static bool isLayerFocusedBasedOnPriority(int32_t priority);
244     static void miniDumpHeader(std::string& result);
245 
246     // Provide unique string for each class type in the Layer hierarchy
getType()247     virtual const char* getType() const { return "Layer"; }
248 
249     // true if this layer is visible, false otherwise
250     virtual bool isVisible() const;
251 
252     virtual sp<Layer> createClone(uint32_t mirrorRoot);
253 
254     // Set a 2x2 transformation matrix on the layer. This transform
255     // will be applied after parent transforms, but before any final
256     // producer specified transform.
257     bool setMatrix(const layer_state_t::matrix22_t& matrix);
258 
259     // This second set of geometry attributes are controlled by
260     // setGeometryAppliesWithResize, and their default mode is to be
261     // immediate. If setGeometryAppliesWithResize is specified
262     // while a resize is pending, then update of these attributes will
263     // be delayed until the resize completes.
264 
265     // setPosition operates in parent buffer space (pre parent-transform) or display
266     // space for top-level layers.
267     bool setPosition(float x, float y);
268     // Buffer space
269     bool setCrop(const Rect& crop);
270 
271     // TODO(b/38182121): Could we eliminate the various latching modes by
272     // using the layer hierarchy?
273     // -----------------------------------------------------------------------
274     virtual bool setLayer(int32_t z);
275     virtual bool setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ);
276 
277     virtual bool setAlpha(float alpha);
278     bool setColor(const half3& /*color*/);
279 
280     // Set rounded corner radius for this layer and its children.
281     //
282     // We only support 1 radius per layer in the hierarchy, where parent layers have precedence.
283     // The shape of the rounded corner rectangle is specified by the crop rectangle of the layer
284     // from which we inferred the rounded corner radius.
285     virtual bool setCornerRadius(float cornerRadius);
286     // When non-zero, everything below this layer will be blurred by backgroundBlurRadius, which
287     // is specified in pixels.
288     virtual bool setBackgroundBlurRadius(int backgroundBlurRadius);
289     virtual bool setBlurRegions(const std::vector<BlurRegion>& effectRegions);
290     bool setTransparentRegionHint(const Region& transparent);
291     virtual bool setTrustedOverlay(bool);
292     virtual bool setFlags(uint32_t flags, uint32_t mask);
293     virtual bool setLayerStack(ui::LayerStack);
294     virtual ui::LayerStack getLayerStack(
295             LayerVector::StateSet state = LayerVector::StateSet::Drawing) const;
296 
297     virtual bool setMetadata(const LayerMetadata& data);
298     virtual void setChildrenDrawingParent(const sp<Layer>&);
299     virtual bool reparent(const sp<IBinder>& newParentHandle) REQUIRES(mFlinger->mStateLock);
300     virtual bool setColorTransform(const mat4& matrix);
301     virtual mat4 getColorTransform() const;
302     virtual bool hasColorTransform() const;
isColorSpaceAgnostic()303     virtual bool isColorSpaceAgnostic() const { return mDrawingState.colorSpaceAgnostic; }
isDimmingEnabled()304     virtual bool isDimmingEnabled() const { return getDrawingState().dimmingEnabled; }
getDesiredHdrSdrRatio()305     float getDesiredHdrSdrRatio() const { return getDrawingState().desiredHdrSdrRatio; }
getCurrentHdrSdrRatio()306     float getCurrentHdrSdrRatio() const { return getDrawingState().currentHdrSdrRatio; }
getCachingHint()307     gui::CachingHint getCachingHint() const { return getDrawingState().cachingHint; }
308 
309     bool setTransform(uint32_t /*transform*/);
310     bool setTransformToDisplayInverse(bool /*transformToDisplayInverse*/);
311     bool setBuffer(std::shared_ptr<renderengine::ExternalTexture>& /* buffer */,
312                    const BufferData& /* bufferData */, nsecs_t /* postTime */,
313                    nsecs_t /*desiredPresentTime*/, bool /*isAutoTimestamp*/,
314                    std::optional<nsecs_t> /* dequeueTime */, const FrameTimelineInfo& /*info*/);
315     void setDesiredPresentTime(nsecs_t /*desiredPresentTime*/, bool /*isAutoTimestamp*/);
316     bool setDataspace(ui::Dataspace /*dataspace*/);
317     bool setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio);
318     bool setCachingHint(gui::CachingHint cachingHint);
319     bool setHdrMetadata(const HdrMetadata& /*hdrMetadata*/);
320     bool setSurfaceDamageRegion(const Region& /*surfaceDamage*/);
321     bool setApi(int32_t /*api*/);
322     bool setSidebandStream(const sp<NativeHandle>& /*sidebandStream*/);
323     bool setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& /*handles*/,
324                                           bool willPresent);
325     virtual bool setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace)
326             REQUIRES(mFlinger->mStateLock);
327     virtual bool setColorSpaceAgnostic(const bool agnostic);
328     virtual bool setDimmingEnabled(const bool dimmingEnabled);
329     virtual bool setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility);
330     virtual bool setFrameRateSelectionPriority(int32_t priority);
331     virtual bool setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint);
332     void setAutoRefresh(bool /* autoRefresh */);
333     bool setDropInputMode(gui::DropInputMode);
334 
335     //  If the variable is not set on the layer, it traverses up the tree to inherit the frame
336     //  rate priority from its parent.
337     virtual int32_t getFrameRateSelectionPriority() const;
338     //
339     virtual FrameRateCompatibility getDefaultFrameRateCompatibility() const;
340     //
341     ui::Dataspace getDataSpace() const;
342 
343     virtual sp<LayerFE> getCompositionEngineLayerFE() const;
344     virtual sp<LayerFE> copyCompositionEngineLayerFE() const;
345     sp<LayerFE> getCompositionEngineLayerFE(const frontend::LayerHierarchy::TraversalPath&);
346 
347     const frontend::LayerSnapshot* getLayerSnapshot() const;
348     frontend::LayerSnapshot* editLayerSnapshot();
349     std::unique_ptr<frontend::LayerSnapshot> stealLayerSnapshot();
350     void updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot);
351 
352     // If we have received a new buffer this frame, we will pass its surface
353     // damage down to hardware composer. Otherwise, we must send a region with
354     // one empty rect.
355     void useSurfaceDamage();
356     void useEmptyDamage();
357     Region getVisibleRegion(const DisplayDevice*) const;
358     void updateLastLatchTime(nsecs_t latchtime);
359 
360     /*
361      * isOpaque - true if this surface is opaque
362      *
363      * This takes into account the buffer format (i.e. whether or not the
364      * pixel format includes an alpha channel) and the "opaque" flag set
365      * on the layer.  It does not examine the current plane alpha value.
366      */
367     bool isOpaque(const Layer::State&) const;
368 
369     /*
370      * Returns whether this layer can receive input.
371      */
372     bool canReceiveInput() const;
373 
374     /*
375      * Whether or not the layer should be considered visible for input calculations.
376      */
isVisibleForInput()377     virtual bool isVisibleForInput() const {
378         // For compatibility reasons we let layers which can receive input
379         // receive input before they have actually submitted a buffer. Because
380         // of this we use canReceiveInput instead of isVisible to check the
381         // policy-visibility, ignoring the buffer state. However for layers with
382         // hasInputInfo()==false we can use the real visibility state.
383         // We are just using these layers for occlusion detection in
384         // InputDispatcher, and obviously if they aren't visible they can't occlude
385         // anything.
386         return hasInputInfo() ? canReceiveInput() : isVisible();
387     }
388 
389     /*
390      * isProtected - true if the layer may contain protected contents in the
391      * GRALLOC_USAGE_PROTECTED sense.
392      */
393     bool isProtected() const;
394 
395     /*
396      * isFixedSize - true if content has a fixed size
397      */
isFixedSize()398     virtual bool isFixedSize() const { return true; }
399 
400     /*
401      * usesSourceCrop - true if content should use a source crop
402      */
usesSourceCrop()403     bool usesSourceCrop() const { return hasBufferOrSidebandStream(); }
404 
405     // Most layers aren't created from the main thread, and therefore need to
406     // grab the SF state lock to access HWC, but ContainerLayer does, so we need
407     // to avoid grabbing the lock again to avoid deadlock
isCreatedFromMainThread()408     virtual bool isCreatedFromMainThread() const { return false; }
409 
getActiveTransform(const Layer::State & s)410     ui::Transform getActiveTransform(const Layer::State& s) const { return s.transform; }
getActiveTransparentRegion(const Layer::State & s)411     Region getActiveTransparentRegion(const Layer::State& s) const {
412         return s.transparentRegionHint;
413     }
getCrop(const Layer::State & s)414     Rect getCrop(const Layer::State& s) const { return s.crop; }
415     bool needsFiltering(const DisplayDevice*) const;
416 
417     // True if this layer requires filtering
418     // This method is distinct from needsFiltering() in how the filter
419     // requirement is computed. needsFiltering() compares displayFrame and crop,
420     // where as this method transforms the displayFrame to layer-stack space
421     // first. This method should be used if there is no physical display to
422     // project onto when taking screenshots, as the filtering requirements are
423     // different.
424     // If the parent transform needs to be undone when capturing the layer, then
425     // the inverse parent transform is also required.
426     bool needsFilteringForScreenshots(const DisplayDevice*, const ui::Transform&) const;
427 
428     // from graphics API
429     ui::Dataspace translateDataspace(ui::Dataspace dataspace);
430     void updateCloneBufferInfo();
431     uint64_t mPreviousFrameNumber = 0;
432 
433     bool isHdrY410() const;
434 
435     /*
436      * called after composition.
437      * returns true if the layer latched a new buffer this frame.
438      */
439     void onPostComposition(const DisplayDevice*, const std::shared_ptr<FenceTime>& /*glDoneFence*/,
440                            const std::shared_ptr<FenceTime>& /*presentFence*/,
441                            const CompositorTiming&);
442 
443     // If a buffer was replaced this frame, release the former buffer
444     void releasePendingBuffer(nsecs_t /*dequeueReadyTime*/);
445 
446     /*
447      * latchBuffer - called each time the screen is redrawn and returns whether
448      * the visible regions need to be recomputed (this is a fairly heavy
449      * operation, so this should be set only if needed). Typically this is used
450      * to figure out if the content or size of a surface has changed.
451      */
452     bool latchBuffer(bool& /*recomputeVisibleRegions*/, nsecs_t /*latchTime*/);
453 
454     bool latchBufferImpl(bool& /*recomputeVisibleRegions*/, nsecs_t /*latchTime*/,
455                          bool bgColorOnly);
456 
457     /*
458      * Returns true if the currently presented buffer will be released when this layer state
459      * is latched. This will return false if there is no buffer currently presented.
460      */
461     bool willReleaseBufferOnLatch() const;
462 
463     /*
464      * Calls latchBuffer if the buffer has a frame queued and then releases the buffer.
465      * This is used if the buffer is just latched and releases to free up the buffer
466      * and will not be shown on screen.
467      * Should only be called on the main thread.
468      */
469     void latchAndReleaseBuffer();
470 
471     /*
472      * returns the rectangle that crops the content of the layer and scales it
473      * to the layer's size.
474      */
475     Rect getBufferCrop() const;
476 
477     /*
478      * Returns the transform applied to the buffer.
479      */
480     uint32_t getBufferTransform() const;
481 
482     sp<GraphicBuffer> getBuffer() const;
483     const std::shared_ptr<renderengine::ExternalTexture>& getExternalTexture() const;
484 
485     /*
486      * Returns if a frame is ready
487      */
488     bool hasReadyFrame() const;
489 
getQueuedFrameCount()490     virtual int32_t getQueuedFrameCount() const { return 0; }
491 
492     /**
493      * Returns active buffer size in the correct orientation. Buffer size is determined by undoing
494      * any buffer transformations. Returns Rect::INVALID_RECT if the layer has no buffer or the
495      * layer does not have a display frame and its parent is not bounded.
496      */
497     Rect getBufferSize(const Layer::State&) const;
498 
499     /**
500      * Returns the source bounds. If the bounds are not defined, it is inferred from the
501      * buffer size. Failing that, the bounds are determined from the passed in parent bounds.
502      * For the root layer, this is the display viewport size.
503      */
504     FloatRect computeSourceBounds(const FloatRect& parentBounds) const;
505     virtual FrameRate getFrameRateForLayerTree() const;
506 
507     bool getTransformToDisplayInverse() const;
508 
509     // Returns how rounded corners should be drawn for this layer.
510     // A layer can override its parent's rounded corner settings if the parent's rounded
511     // corner crop does not intersect with its own rounded corner crop.
512     virtual frontend::RoundedCornerState getRoundedCornerState() const;
513 
hasRoundedCorners()514     bool hasRoundedCorners() const { return getRoundedCornerState().hasRoundedCorners(); }
515 
516     PixelFormat getPixelFormat() const;
517     /**
518      * Return whether this layer needs an input info. We generate InputWindowHandles for all
519      * non-cursor buffered layers regardless of whether they have an InputChannel. This is to enable
520      * the InputDispatcher to do PID based occlusion detection.
521      */
needsInputInfo()522     bool needsInputInfo() const {
523         return (hasInputInfo() || hasBufferOrSidebandStream()) && !mPotentialCursor;
524     }
525 
526     // Implements RefBase.
527     void onFirstRef() override;
528 
529     struct BufferInfo {
530         nsecs_t mDesiredPresentTime;
531         std::shared_ptr<FenceTime> mFenceTime;
532         sp<Fence> mFence;
533         uint32_t mTransform{0};
534         ui::Dataspace mDataspace{ui::Dataspace::UNKNOWN};
535         Rect mCrop;
536         uint32_t mScaleMode{NATIVE_WINDOW_SCALING_MODE_FREEZE};
537         Region mSurfaceDamage;
538         HdrMetadata mHdrMetadata;
539         int mApi;
540         PixelFormat mPixelFormat{PIXEL_FORMAT_NONE};
541         bool mTransformToDisplayInverse{false};
542 
543         std::shared_ptr<renderengine::ExternalTexture> mBuffer;
544         uint64_t mFrameNumber;
545         sp<IBinder> mReleaseBufferEndpoint;
546 
547         bool mFrameLatencyNeeded{false};
548         float mDesiredHdrSdrRatio = 1.f;
549     };
550 
551     BufferInfo mBufferInfo;
552 
553     // implements compositionengine::LayerFE
554     const compositionengine::LayerFECompositionState* getCompositionState() const;
555     bool fenceHasSignaled() const;
556     void onPreComposition(nsecs_t refreshStartTime);
557     void onLayerDisplayed(ftl::SharedFuture<FenceResult>, ui::LayerStack layerStack);
558 
setWasClientComposed(const sp<Fence> & fence)559     void setWasClientComposed(const sp<Fence>& fence) {
560         mLastClientCompositionFence = fence;
561         mClearClientCompositionFenceOnLayerDisplayed = false;
562     }
563 
564     const char* getDebugName() const;
565 
566     bool setShadowRadius(float shadowRadius);
567 
568     // Before color management is introduced, contents on Android have to be
569     // desaturated in order to match what they appears like visually.
570     // With color management, these contents will appear desaturated, thus
571     // needed to be saturated so that they match what they are designed for
572     // visually.
573     bool isLegacyDataSpace() const;
574 
getTransactionFlags()575     uint32_t getTransactionFlags() const { return mTransactionFlags; }
576 
577     static bool computeTrustedPresentationState(const FloatRect& bounds,
578                                                 const FloatRect& sourceBounds,
579                                                 const Region& coveredRegion,
580                                                 const FloatRect& screenBounds, float,
581                                                 const ui::Transform&,
582                                                 const TrustedPresentationThresholds&);
583     void updateTrustedPresentationState(const DisplayDevice* display,
584                                         const frontend::LayerSnapshot* snapshot, int64_t time_in_ms,
585                                         bool leaveState);
586 
hasTrustedPresentationListener()587     inline bool hasTrustedPresentationListener() {
588         return mTrustedPresentationListener.callbackInterface != nullptr;
589     }
590 
591     // Sets the masked bits.
592     void setTransactionFlags(uint32_t mask);
593 
594     // Clears and returns the masked bits.
595     uint32_t clearTransactionFlags(uint32_t mask);
596 
597     FloatRect getBounds(const Region& activeTransparentRegion) const;
598     FloatRect getBounds() const;
599     Rect getInputBoundsInDisplaySpace(const FloatRect& insetBounds,
600                                       const ui::Transform& displayTransform);
601 
602     // Compute bounds for the layer and cache the results.
603     void computeBounds(FloatRect parentBounds, ui::Transform parentTransform, float shadowRadius);
604 
getSequence()605     int32_t getSequence() const { return sequence; }
606 
607     // For tracing.
608     // TODO: Replace with raw buffer id from buffer metadata when that becomes available.
609     // GraphicBuffer::getId() does not provide a reliable global identifier. Since the traces
610     // creates its tracks by buffer id and has no way of associating a buffer back to the process
611     // that created it, the current implementation is only sufficient for cases where a buffer is
612     // only used within a single layer.
getCurrentBufferId()613     uint64_t getCurrentBufferId() const { return getBuffer() ? getBuffer()->getId() : 0; }
614 
615     /*
616      * isSecure - true if this surface is secure, that is if it prevents
617      * screenshots or VNC servers. A surface can be set to be secure by the
618      * application, being secure doesn't mean the surface has DRM contents.
619      */
620     bool isSecure() const;
621 
622     /*
623      * isHiddenByPolicy - true if this layer has been forced invisible.
624      * just because this is false, doesn't mean isVisible() is true.
625      * For example if this layer has no active buffer, it may not be hidden by
626      * policy, but it still can not be visible.
627      */
628     bool isHiddenByPolicy() const;
629 
630     // True if the layer should be skipped in screenshots, screen recordings,
631     // and mirroring to external or virtual displays.
632     bool isInternalDisplayOverlay() const;
633 
getOutputFilter()634     ui::LayerFilter getOutputFilter() const {
635         return {getLayerStack(), isInternalDisplayOverlay()};
636     }
637 
638     bool isRemovedFromCurrentState() const;
639 
640     LayerProto* writeToProto(LayersProto& layersProto, uint32_t traceFlags);
641     void writeCompositionStateToProto(LayerProto* layerProto, ui::LayerStack layerStack);
642 
643     // Write states that are modified by the main thread. This includes drawing
644     // state as well as buffer data. This should be called in the main or tracing
645     // thread.
646     void writeToProtoDrawingState(LayerProto* layerInfo);
647     // Write drawing or current state. If writing current state, the caller should hold the
648     // external mStateLock. If writing drawing state, this function should be called on the
649     // main or tracing thread.
650     void writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet,
651                                  uint32_t traceFlags = LayerTracing::TRACE_ALL);
652 
getWindowType()653     gui::WindowInfo::Type getWindowType() const { return mWindowType; }
654 
655     bool updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates);
656 
657     /*
658      * doTransaction - process the transaction. This is a good place to figure
659      * out which attributes of the surface have changed.
660      */
661     virtual uint32_t doTransaction(uint32_t transactionFlags);
662 
663     /*
664      * Remove relative z for the layer if its relative parent is not part of the
665      * provided layer tree.
666      */
667     void removeRelativeZ(const std::vector<Layer*>& layersInTree);
668 
669     /*
670      * Remove from current state and mark for removal.
671      */
672     void removeFromCurrentState() REQUIRES(mFlinger->mStateLock);
673 
674     /*
675      * called with the state lock from a binder thread when the layer is
676      * removed from the current list to the pending removal list
677      */
678     void onRemovedFromCurrentState() REQUIRES(mFlinger->mStateLock);
679 
680     /*
681      * Called when the layer is added back to the current state list.
682      */
683     void addToCurrentState();
684 
685     /*
686      * Sets display transform hint on BufferLayerConsumer.
687      */
688     void updateTransformHint(ui::Transform::RotationFlags);
689     void skipReportingTransformHint();
getDrawingState()690     inline const State& getDrawingState() const { return mDrawingState; }
getDrawingState()691     inline State& getDrawingState() { return mDrawingState; }
692 
693     gui::LayerDebugInfo getLayerDebugInfo(const DisplayDevice*) const;
694 
695     void miniDump(std::string& result, const DisplayDevice&) const;
696     void dumpFrameStats(std::string& result) const;
697     void dumpOffscreenDebugInfo(std::string& result) const;
698     void clearFrameStats();
699     void logFrameStats();
700     void getFrameStats(FrameStats* outStats) const;
701     void onDisconnect();
702 
703     ui::Transform getTransform() const;
704     bool isTransformValid() const;
705 
706     // Returns the Alpha of the Surface, accounting for the Alpha
707     // of parent Surfaces in the hierarchy (alpha's will be multiplied
708     // down the hierarchy).
709     half getAlpha() const;
710     half4 getColor() const;
711     int32_t getBackgroundBlurRadius() const;
drawShadows()712     bool drawShadows() const { return mEffectiveShadowRadius > 0.f; };
713 
714     // Returns the transform hint set by Window Manager on the layer or one of its parents.
715     // This traverses the current state because the data is needed when creating
716     // the layer(off drawing thread) and the hint should be available before the producer
717     // is ready to acquire a buffer.
718     ui::Transform::RotationFlags getFixedTransformHint() const;
719 
720     /**
721      * Traverse this layer and it's hierarchy of children directly. Unlike traverseInZOrder
722      * which will not emit children who have relativeZOrder to another layer, this method
723      * just directly emits all children. It also emits them in no particular order.
724      * So this method is not suitable for graphical operations, as it doesn't represent
725      * the scene state, but it's also more efficient than traverseInZOrder and so useful for
726      * book-keeping.
727      */
728     void traverse(LayerVector::StateSet, const LayerVector::Visitor&);
729     void traverseInReverseZOrder(LayerVector::StateSet, const LayerVector::Visitor&);
730     void traverseInZOrder(LayerVector::StateSet, const LayerVector::Visitor&);
731     void traverseChildren(const LayerVector::Visitor&);
732 
733     /**
734      * Traverse only children in z order, ignoring relative layers that are not children of the
735      * parent.
736      */
737     void traverseChildrenInZOrder(LayerVector::StateSet, const LayerVector::Visitor&);
738 
739     size_t getDescendantCount() const;
getChildrenCount()740     size_t getChildrenCount() const { return mDrawingChildren.size(); }
isHandleAlive()741     bool isHandleAlive() const { return mHandleAlive; }
onHandleDestroyed()742     bool onHandleDestroyed() { return mHandleAlive = false; }
743 
744     // ONLY CALL THIS FROM THE LAYER DTOR!
745     // See b/141111965.  We need to add current children to offscreen layers in
746     // the layer dtor so as not to dangle layers.  Since the layer has not
747     // committed its transaction when the layer is destroyed, we must add
748     // current children.  This is safe in the dtor as we will no longer update
749     // the current state, but should not be called anywhere else!
getCurrentChildren()750     LayerVector& getCurrentChildren() { return mCurrentChildren; }
751 
752     void addChild(const sp<Layer>&);
753     // Returns index if removed, or negative value otherwise
754     // for symmetry with Vector::remove
755     ssize_t removeChild(const sp<Layer>& layer);
getParent()756     sp<Layer> getParent() const { return mCurrentParent.promote(); }
757 
758     // Should be called with the surfaceflinger statelock held
isAtRoot()759     bool isAtRoot() const { return mIsAtRoot; }
setIsAtRoot(bool isAtRoot)760     void setIsAtRoot(bool isAtRoot) { mIsAtRoot = isAtRoot; }
761 
hasParent()762     bool hasParent() const { return getParent() != nullptr; }
763     Rect getScreenBounds(bool reduceTransparentRegion = true) const;
764     bool setChildLayer(const sp<Layer>& childLayer, int32_t z);
765     bool setChildRelativeLayer(const sp<Layer>& childLayer,
766             const sp<IBinder>& relativeToHandle, int32_t relativeZ);
767 
768     // Copy the current list of children to the drawing state. Called by
769     // SurfaceFlinger to complete a transaction.
770     void commitChildList();
771     int32_t getZ(LayerVector::StateSet) const;
772 
773     /**
774      * Returns the cropped buffer size or the layer crop if the layer has no buffer. Return
775      * INVALID_RECT if the layer has no buffer and no crop.
776      * A layer with an invalid buffer size and no crop is considered to be boundless. The layer
777      * bounds are constrained by its parent bounds.
778      */
779     Rect getCroppedBufferSize(const Layer::State& s) const;
780 
781     bool setFrameRate(FrameRate);
782 
setFrameTimelineInfoForBuffer(const FrameTimelineInfo &)783     virtual void setFrameTimelineInfoForBuffer(const FrameTimelineInfo& /*info*/) {}
784     void setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info, nsecs_t postTime);
785     void setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
786                                                        nsecs_t postTime);
787 
788     void addSurfaceFrameDroppedForBuffer(std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame,
789                                          nsecs_t dropTime);
790     void addSurfaceFramePresentedForBuffer(
791             std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
792             nsecs_t currentLatchTime);
793 
794     std::shared_ptr<frametimeline::SurfaceFrame> createSurfaceFrameForTransaction(
795             const FrameTimelineInfo& info, nsecs_t postTime);
796     std::shared_ptr<frametimeline::SurfaceFrame> createSurfaceFrameForBuffer(
797             const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName);
798     void setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
799                                                std::string debugName);
800 
801     bool setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
802                                     TrustedPresentationListener const& listener);
803 
804     // Creates a new handle each time, so we only expect
805     // this to be called once.
806     sp<IBinder> getHandle();
getName()807     const std::string& getName() const { return mName; }
808     bool getPremultipledAlpha() const;
809     void setInputInfo(const gui::WindowInfo& info);
810 
811     struct InputDisplayArgs {
812         const ui::Transform* transform = nullptr;
813         bool isSecure = false;
814     };
815     gui::WindowInfo fillInputInfo(const InputDisplayArgs& displayArgs);
816 
817     /**
818      * Returns whether this layer has an explicitly set input-info.
819      */
820     bool hasInputInfo() const;
821 
822     // Sets the gui::GameMode for the tree rooted at this layer. A layer in the tree inherits this
823     // gui::GameMode unless it (or an ancestor) has GAME_MODE_METADATA.
824     void setGameModeForTree(gui::GameMode);
825 
setGameMode(gui::GameMode gameMode)826     void setGameMode(gui::GameMode gameMode) { mGameMode = gameMode; }
getGameMode()827     gui::GameMode getGameMode() const { return mGameMode; }
828 
getOwnerUid()829     virtual uid_t getOwnerUid() const { return mOwnerUid; }
830 
getOwnerPid()831     pid_t getOwnerPid() { return mOwnerPid; }
832 
833     // This layer is not a clone, but it's the parent to the cloned hierarchy. The
834     // variable mClonedChild represents the top layer that will be cloned so this
835     // layer will be the parent of mClonedChild.
836     // The layers in the cloned hierarchy will match the lifetime of the real layers. That is
837     // if the real layer is destroyed, then the clone layer will also be destroyed.
838     sp<Layer> mClonedChild;
839     bool mHadClonedChild = false;
840     void setClonedChild(const sp<Layer>& mClonedChild);
841 
842     mutable bool contentDirty{false};
843     Region surfaceDamageRegion;
844 
845     // True when the surfaceDamageRegion is recognized as a small area update.
846     bool mSmallDirty{false};
847     // Used to check if mUsedVsyncIdForRefreshRateSelection should be expired when it stop updating.
848     nsecs_t mMaxTimeForUseVsyncId = 0;
849     // True when DrawState.useVsyncIdForRefreshRateSelection previously set to true during updating
850     // buffer.
851     bool mUsedVsyncIdForRefreshRateSelection{false};
852 
853     // Layer serial number.  This gives layers an explicit ordering, so we
854     // have a stable sort order when their layer stack and Z-order are
855     // the same.
856     const int32_t sequence;
857 
858     bool mPendingHWCDestroy{false};
859 
backpressureEnabled()860     bool backpressureEnabled() const {
861         return mDrawingState.flags & layer_state_t::eEnableBackpressure;
862     }
863 
864     bool setStretchEffect(const StretchEffect& effect);
865     StretchEffect getStretchEffect() const;
866     bool enableBorder(bool shouldEnable, float width, const half4& color);
867     bool isBorderEnabled();
868     float getBorderWidth();
869     const half4& getBorderColor();
870 
871     bool setBufferCrop(const Rect& /* bufferCrop */);
872     bool setDestinationFrame(const Rect& /* destinationFrame */);
873     // See mPendingBufferTransactions
874     void decrementPendingBufferCount();
getPendingBufferCounter()875     std::atomic<int32_t>* getPendingBufferCounter() { return &mPendingBufferTransactions; }
getPendingBufferCounterName()876     std::string getPendingBufferCounterName() { return mBlastTransactionName; }
877     bool updateGeometry();
878 
879     bool isSimpleBufferUpdate(const layer_state_t& s) const;
880 
881     static bool isOpaqueFormat(PixelFormat format);
882 
883     // Updates the LayerSnapshot. This must be called prior to sending layer data to
884     // CompositionEngine or RenderEngine (i.e. before calling CompositionEngine::present or
885     // LayerFE::prepareClientComposition).
886     //
887     // TODO(b/238781169) Remove direct calls to RenderEngine::drawLayers that don't go through
888     // CompositionEngine to create a single path for composing layers.
889     void updateSnapshot(bool updateGeometry);
890     void updateChildrenSnapshots(bool updateGeometry);
891     void updateMetadataSnapshot(const LayerMetadata& parentMetadata);
892     void updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
893                                         std::unordered_set<Layer*>& visited);
getClonedFrom()894     sp<Layer> getClonedFrom() const {
895         return mClonedFrom != nullptr ? mClonedFrom.promote() : nullptr;
896     }
isClone()897     bool isClone() { return mClonedFrom != nullptr; }
898 
899     bool willPresentCurrentTransaction() const;
900 
901     void callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
902                                    const sp<GraphicBuffer>& buffer, uint64_t framenumber,
903                                    const sp<Fence>& releaseFence);
904     bool setFrameRateForLayerTreeLegacy(FrameRate);
905     bool setFrameRateForLayerTree(FrameRate, const scheduler::LayerProps&);
906     void recordLayerHistoryBufferUpdate(const scheduler::LayerProps&);
907     void recordLayerHistoryAnimationTx(const scheduler::LayerProps&);
getLayerProps()908     auto getLayerProps() const {
909         return scheduler::LayerProps{
910                 .visible = isVisible(),
911                 .bounds = getBounds(),
912                 .transform = getTransform(),
913                 .setFrameRateVote = getFrameRateForLayerTree(),
914                 .frameRateSelectionPriority = getFrameRateSelectionPriority(),
915                 .isSmallDirty = mSmallDirty,
916         };
917     };
hasBuffer()918     bool hasBuffer() const { return mBufferInfo.mBuffer != nullptr; }
setTransformHint(std::optional<ui::Transform::RotationFlags> transformHint)919     void setTransformHint(std::optional<ui::Transform::RotationFlags> transformHint) {
920         mTransformHint = transformHint;
921     }
922     // Keeps track of the previously presented layer stacks. This is used to get
923     // the release fences from the correct displays when we release the last buffer
924     // from the layer.
925     std::vector<ui::LayerStack> mPreviouslyPresentedLayerStacks;
926     // Exposed so SurfaceFlinger can assert that it's held
927     const sp<SurfaceFlinger> mFlinger;
928 
929     // Check if the damage region is a small dirty.
930     void setIsSmallDirty();
931 
932 protected:
933     // For unit tests
934     friend class TestableSurfaceFlinger;
935     friend class FpsReporterTest;
936     friend class RefreshRateSelectionTest;
937     friend class SetFrameRateTest;
938     friend class TransactionFrameTracerTest;
939     friend class TransactionSurfaceFrameTest;
940 
941     virtual void setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId);
942     void preparePerFrameCompositionState();
943     void preparePerFrameBufferCompositionState();
944     void preparePerFrameEffectsCompositionState();
945     virtual void commitTransaction(State& stateToCommit);
946     void gatherBufferInfo();
947     void onSurfaceFrameCreated(const std::shared_ptr<frametimeline::SurfaceFrame>&);
948 
isClonedFromAlive()949     bool isClonedFromAlive() { return getClonedFrom() != nullptr; }
950 
951     void cloneDrawingState(const Layer* from);
952     void updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap);
953     void updateClonedChildren(const sp<Layer>& mirrorRoot,
954                               std::map<sp<Layer>, sp<Layer>>& clonedLayersMap);
955     void updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap);
956     void addChildToDrawing(const sp<Layer>&);
957     void updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap);
958 
959     void prepareBasicGeometryCompositionState();
960     void prepareGeometryCompositionState();
961     void prepareCursorCompositionState();
962 
963     uint32_t getEffectiveUsage(uint32_t usage) const;
964 
965     /**
966      * Setup rounded corners coordinates of this layer, taking into account the layer bounds and
967      * crop coordinates, transforming them into layer space.
968      */
969     void setupRoundedCornersCropCoordinates(Rect win, const FloatRect& roundedCornersCrop) const;
970     void setParent(const sp<Layer>&);
971     LayerVector makeTraversalList(LayerVector::StateSet, bool* outSkipRelativeZUsers);
972     void addZOrderRelative(const wp<Layer>& relative);
973     void removeZOrderRelative(const wp<Layer>& relative);
974     compositionengine::OutputLayer* findOutputLayerForDisplay(const DisplayDevice*) const;
975     bool usingRelativeZ(LayerVector::StateSet) const;
976 
977     virtual ui::Transform getInputTransform() const;
978     /**
979      * Get the bounds in layer space within which this layer can receive input.
980      *
981      * These bounds are used to:
982      * - Determine the input frame for the layer to be used for occlusion detection; and
983      * - Determine the coordinate space within which the layer will receive input. The top-left of
984      *   this rect will be the origin of the coordinate space that the input events sent to the
985      *   layer will be in (prior to accounting for surface insets).
986      *
987      * The layer can still receive touch input if these bounds are invalid if
988      * "replaceTouchableRegionWithCrop" is specified. In this case, the layer will receive input
989      * in this layer's space, regardless of the specified crop layer.
990      */
991     std::pair<FloatRect, bool> getInputBounds(bool fillParentBounds) const;
992 
993     bool mPremultipliedAlpha{true};
994     const std::string mName;
995     const std::string mTransactionName{"TX - " + mName};
996 
997     // These are only accessed by the main thread or the tracing thread.
998     State mDrawingState;
999 
1000     TrustedPresentationThresholds mTrustedPresentationThresholds;
1001     TrustedPresentationListener mTrustedPresentationListener;
1002     bool mLastComputedTrustedPresentationState = false;
1003     bool mLastReportedTrustedPresentationState = false;
1004     int64_t mEnteredTrustedPresentationStateTime = -1;
1005 
1006     uint32_t mTransactionFlags{0};
1007     // Updated in doTransaction, used to track the last sequence number we
1008     // committed. Currently this is really only used for updating visible
1009     // regions.
1010     int32_t mLastCommittedTxSequence = -1;
1011 
1012     // Timestamp history for UIAutomation. Thread safe.
1013     FrameTracker mFrameTracker;
1014 
1015     // main thread
1016     sp<NativeHandle> mSidebandStream;
1017     // False if the buffer and its contents have been previously used for GPU
1018     // composition, true otherwise.
1019     bool mIsActiveBufferUpdatedForGpu = true;
1020 
1021     // We encode unset as -1.
1022     std::atomic<uint64_t> mCurrentFrameNumber{0};
1023     // Whether filtering is needed b/c of the drawingstate
1024     bool mNeedsFiltering{false};
1025 
1026     std::atomic<bool> mRemovedFromDrawingState{false};
1027 
1028     // page-flip thread (currently main thread)
1029     bool mProtectedByApp{false}; // application requires protected path to external sink
1030 
1031     // protected by mLock
1032     mutable Mutex mLock;
1033 
1034     const wp<Client> mClientRef;
1035 
1036     // This layer can be a cursor on some displays.
1037     bool mPotentialCursor{false};
1038 
1039     LayerVector mCurrentChildren{LayerVector::StateSet::Current};
1040     LayerVector mDrawingChildren{LayerVector::StateSet::Drawing};
1041 
1042     wp<Layer> mCurrentParent;
1043     wp<Layer> mDrawingParent;
1044 
1045     // Window types from WindowManager.LayoutParams
1046     const gui::WindowInfo::Type mWindowType;
1047 
1048     // The owner of the layer. If created from a non system process, it will be the calling uid.
1049     // If created from a system process, the value can be passed in.
1050     uid_t mOwnerUid;
1051 
1052     // The owner pid of the layer. If created from a non system process, it will be the calling pid.
1053     // If created from a system process, the value can be passed in.
1054     pid_t mOwnerPid;
1055 
1056     // Keeps track of the time SF latched the last buffer from this layer.
1057     // Used in buffer stuffing analysis in FrameTimeline.
1058     nsecs_t mLastLatchTime = 0;
1059 
1060     mutable bool mDrawingStateModified = false;
1061 
1062     sp<Fence> mLastClientCompositionFence;
1063     bool mClearClientCompositionFenceOnLayerDisplayed = false;
1064 private:
1065     friend class SlotGenerationTest;
1066     friend class TransactionFrameTracerTest;
1067     friend class TransactionSurfaceFrameTest;
1068 
getAutoRefresh()1069     bool getAutoRefresh() const { return mDrawingState.autoRefresh; }
getSidebandStreamChanged()1070     bool getSidebandStreamChanged() const { return mSidebandStreamChanged; }
1071 
1072     std::atomic<bool> mSidebandStreamChanged{false};
1073 
1074     // Returns true if the layer can draw shadows on its border.
canDrawShadows()1075     virtual bool canDrawShadows() const { return true; }
1076 
1077     aidl::android::hardware::graphics::composer3::Composition getCompositionType(
1078             const DisplayDevice&) const;
1079 
1080     /**
1081      * Returns an unsorted vector of all layers that are part of this tree.
1082      * That includes the current layer and all its descendants.
1083      */
1084     std::vector<Layer*> getLayersInTree(LayerVector::StateSet);
1085     /**
1086      * Traverses layers that are part of this tree in the correct z order.
1087      * layersInTree must be sorted before calling this method.
1088      */
1089     void traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1090                                        LayerVector::StateSet, const LayerVector::Visitor&);
1091     LayerVector makeChildrenTraversalList(LayerVector::StateSet,
1092                                           const std::vector<Layer*>& layersInTree);
1093 
1094     void updateTreeHasFrameRateVote();
1095     bool propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded);
1096     void setZOrderRelativeOf(const wp<Layer>& relativeOf);
1097     bool isTrustedOverlay() const;
1098     gui::DropInputMode getDropInputMode() const;
1099     void handleDropInputMode(gui::WindowInfo& info) const;
1100 
1101     // Find the root of the cloned hierarchy, this means the first non cloned parent.
1102     // This will return null if first non cloned parent is not found.
1103     sp<Layer> getClonedRoot();
1104 
1105     // Finds the top most layer in the hierarchy. This will find the root Layer where the parent is
1106     // null.
1107     sp<Layer> getRootLayer();
1108 
1109     // Fills in the touch occlusion mode of the first parent (including this layer) that
1110     // hasInputInfo() or no-op if no such parent is found.
1111     void fillTouchOcclusionMode(gui::WindowInfo& info);
1112 
1113     // Fills in the frame and transform info for the gui::WindowInfo.
1114     void fillInputFrameInfo(gui::WindowInfo&, const ui::Transform& screenToDisplay);
1115 
1116     inline void tracePendingBufferCount(int32_t pendingBuffers);
1117 
1118     // Latch sideband stream and returns true if the dirty region should be updated.
1119     bool latchSidebandStream(bool& recomputeVisibleRegions);
1120 
1121     bool hasFrameUpdate() const;
1122 
1123     void updateTexImage(nsecs_t latchTime, bool bgColorOnly = false);
1124 
1125     // Crop that applies to the buffer
1126     Rect computeBufferCrop(const State& s);
1127 
1128     void callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
1129                                    const sp<GraphicBuffer>& buffer, uint64_t framenumber,
1130                                    const sp<Fence>& releaseFence,
1131                                    uint32_t currentMaxAcquiredBufferCount);
1132 
1133     // Returns true if the transformed buffer size does not match the layer size and we need
1134     // to apply filtering.
1135     bool bufferNeedsFiltering() const;
1136 
1137     // Returns true if there is a valid color to fill.
1138     bool fillsColor() const;
1139     // Returns true if this layer has a blur value.
1140     bool hasBlur() const;
hasEffect()1141     bool hasEffect() const { return fillsColor() || drawShadows() || hasBlur(); }
hasBufferOrSidebandStream()1142     bool hasBufferOrSidebandStream() const {
1143         return ((mSidebandStream != nullptr) || (mBufferInfo.mBuffer != nullptr));
1144     }
1145 
hasBufferOrSidebandStreamInDrawing()1146     bool hasBufferOrSidebandStreamInDrawing() const {
1147         return ((mDrawingState.sidebandStream != nullptr) || (mDrawingState.buffer != nullptr));
1148     }
1149 
hasSomethingToDraw()1150     bool hasSomethingToDraw() const { return hasEffect() || hasBufferOrSidebandStream(); }
1151 
1152     // Fills the provided vector with the currently available JankData and removes the processed
1153     // JankData from the pending list.
1154     void transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
1155                                    std::vector<JankData>& jankData);
1156 
1157     // Cached properties computed from drawing state
1158     // Effective transform taking into account parent transforms and any parent scaling, which is
1159     // a transform from the current layer coordinate space to display(screen) coordinate space.
1160     ui::Transform mEffectiveTransform;
1161 
1162     // Bounds of the layer before any transformation is applied and before it has been cropped
1163     // by its parents.
1164     FloatRect mSourceBounds;
1165 
1166     // Bounds of the layer in layer space. This is the mSourceBounds cropped by its layer crop and
1167     // its parent bounds.
1168     FloatRect mBounds;
1169 
1170     // Layer bounds in screen space.
1171     FloatRect mScreenBounds;
1172 
1173     bool mGetHandleCalled = false;
1174 
1175     // The current layer is a clone of mClonedFrom. This means that this layer will update it's
1176     // properties based on mClonedFrom. When mClonedFrom latches a new buffer for BufferLayers,
1177     // this layer will update it's buffer. When mClonedFrom updates it's drawing state, children,
1178     // and relatives, this layer will update as well.
1179     wp<Layer> mClonedFrom;
1180 
1181     // The inherited shadow radius after taking into account the layer hierarchy. This is the
1182     // final shadow radius for this layer. If a shadow is specified for a layer, then effective
1183     // shadow radius is the set shadow radius, otherwise its the parent's shadow radius.
1184     float mEffectiveShadowRadius = 0.f;
1185 
1186     // Game mode for the layer. Set by WindowManagerShell and recorded by SurfaceFlingerStats.
1187     gui::GameMode mGameMode = gui::GameMode::Unsupported;
1188 
1189     // A list of regions on this layer that should have blurs.
1190     const std::vector<BlurRegion> getBlurRegions() const;
1191 
1192     bool mIsAtRoot = false;
1193 
1194     uint32_t mLayerCreationFlags;
1195 
1196     bool findInHierarchy(const sp<Layer>&);
1197 
1198     bool mBorderEnabled = false;
1199     float mBorderWidth;
1200     half4 mBorderColor;
1201 
1202     void setTransformHintLegacy(ui::Transform::RotationFlags);
1203     void resetDrawingStateBufferInfo();
1204 
1205     const uint32_t mTextureName;
1206 
1207     // Transform hint provided to the producer. This must be accessed holding
1208     // the mStateLock.
1209     ui::Transform::RotationFlags mTransformHintLegacy = ui::Transform::ROT_0;
1210     bool mSkipReportingTransformHint = true;
1211     std::optional<ui::Transform::RotationFlags> mTransformHint = std::nullopt;
1212 
1213     ReleaseCallbackId mPreviousReleaseCallbackId = ReleaseCallbackId::INVALID_ID;
1214     sp<IBinder> mPreviousReleaseBufferEndpoint;
1215     uint64_t mPreviousReleasedFrameNumber = 0;
1216 
1217     uint64_t mPreviousBarrierFrameNumber = 0;
1218 
1219     bool mReleasePreviousBuffer = false;
1220 
1221     // Stores the last set acquire fence signal time used to populate the callback handle's acquire
1222     // time.
1223     std::variant<nsecs_t, sp<Fence>> mCallbackHandleAcquireTimeOrFence = -1;
1224 
1225     std::deque<std::shared_ptr<android::frametimeline::SurfaceFrame>> mPendingJankClassifications;
1226     // An upper bound on the number of SurfaceFrames in the pending classifications deque.
1227     static constexpr int kPendingClassificationMaxSurfaceFrames = 50;
1228 
1229     const std::string mBlastTransactionName{"BufferTX - " + mName};
1230     // This integer is incremented everytime a buffer arrives at the server for this layer,
1231     // and decremented when a buffer is dropped or latched. When changed the integer is exported
1232     // to systrace with ATRACE_INT and mBlastTransactionName. This way when debugging perf it is
1233     // possible to see when a buffer arrived at the server, and in which frame it latched.
1234     //
1235     // You can understand the trace this way:
1236     //     - If the integer increases, a buffer arrived at the server.
1237     //     - If the integer decreases in latchBuffer, that buffer was latched
1238     //     - If the integer decreases in setBuffer or doTransaction, a buffer was dropped
1239     std::atomic<int32_t> mPendingBufferTransactions{0};
1240 
1241     // Contains requested position and matrix updates. This will be applied if the client does
1242     // not specify a destination frame.
1243     ui::Transform mRequestedTransform;
1244 
1245     sp<LayerFE> mLegacyLayerFE;
1246     std::vector<std::pair<frontend::LayerHierarchy::TraversalPath, sp<LayerFE>>> mLayerFEs;
1247     std::unique_ptr<frontend::LayerSnapshot> mSnapshot =
1248             std::make_unique<frontend::LayerSnapshot>();
1249     bool mHandleAlive = false;
1250 };
1251 
1252 std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate);
1253 
1254 } // namespace android
1255