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