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 <compositionengine/LayerFE.h>
20 #include <gui/BufferQueue.h>
21 #include <gui/ISurfaceComposerClient.h>
22 #include <gui/LayerState.h>
23 #include <input/InputWindow.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/FloatRect.h>
30 #include <ui/FrameStats.h>
31 #include <ui/GraphicBuffer.h>
32 #include <ui/PixelFormat.h>
33 #include <ui/Region.h>
34 #include <ui/Transform.h>
35 #include <utils/RefBase.h>
36 #include <utils/Timers.h>
37 
38 #include <cstdint>
39 #include <list>
40 #include <optional>
41 #include <vector>
42 
43 #include "Client.h"
44 #include "ClientCache.h"
45 #include "DisplayHardware/ComposerHal.h"
46 #include "DisplayHardware/HWComposer.h"
47 #include "FrameTracker.h"
48 #include "LayerVector.h"
49 #include "MonitoredProducer.h"
50 #include "RenderArea.h"
51 #include "SurfaceFlinger.h"
52 #include "TransactionCompletedThread.h"
53 
54 using namespace android::surfaceflinger;
55 
56 namespace android {
57 
58 // ---------------------------------------------------------------------------
59 
60 class Client;
61 class Colorizer;
62 class DisplayDevice;
63 class GraphicBuffer;
64 class SurfaceFlinger;
65 class LayerDebugInfo;
66 
67 namespace compositionengine {
68 class OutputLayer;
69 struct LayerFECompositionState;
70 }
71 
72 namespace impl {
73 class SurfaceInterceptor;
74 }
75 
76 // ---------------------------------------------------------------------------
77 
78 struct LayerCreationArgs {
79     LayerCreationArgs(SurfaceFlinger*, sp<Client>, std::string name, uint32_t w, uint32_t h,
80                       uint32_t flags, LayerMetadata);
81 
82     SurfaceFlinger* flinger;
83     const sp<Client> client;
84     std::string name;
85     uint32_t w;
86     uint32_t h;
87     uint32_t flags;
88     LayerMetadata metadata;
89 
90     pid_t callingPid;
91     uid_t callingUid;
92     uint32_t textureName;
93 };
94 
95 class Layer : public virtual RefBase, compositionengine::LayerFE {
96     static std::atomic<int32_t> sSequence;
97     // The following constants represent priority of the window. SF uses this information when
98     // deciding which window has a priority when deciding about the refresh rate of the screen.
99     // Priority 0 is considered the highest priority. -1 means that the priority is unset.
100     static constexpr int32_t PRIORITY_UNSET = -1;
101     // Windows that are in focus and voted for the preferred mode ID
102     static constexpr int32_t PRIORITY_FOCUSED_WITH_MODE = 0;
103     // // Windows that are in focus, but have not requested a specific mode ID.
104     static constexpr int32_t PRIORITY_FOCUSED_WITHOUT_MODE = 1;
105     // Windows that are not in focus, but voted for a specific mode ID.
106     static constexpr int32_t PRIORITY_NOT_FOCUSED_WITH_MODE = 2;
107 
108 public:
109     mutable bool contentDirty{false};
110     Region surfaceDamageRegion;
111 
112     // Layer serial number.  This gives layers an explicit ordering, so we
113     // have a stable sort order when their layer stack and Z-order are
114     // the same.
115     int32_t sequence{sSequence++};
116 
117     enum { // flags for doTransaction()
118         eDontUpdateGeometryState = 0x00000001,
119         eVisibleRegion = 0x00000002,
120         eInputInfoChanged = 0x00000004
121     };
122 
123     struct Geometry {
124         uint32_t w;
125         uint32_t h;
126         ui::Transform transform;
127 
128         inline bool operator==(const Geometry& rhs) const {
129             return (w == rhs.w && h == rhs.h) && (transform.tx() == rhs.transform.tx()) &&
130                     (transform.ty() == rhs.transform.ty());
131         }
132         inline bool operator!=(const Geometry& rhs) const { return !operator==(rhs); }
133     };
134 
135     struct RoundedCornerState {
136         RoundedCornerState() = default;
RoundedCornerStateRoundedCornerState137         RoundedCornerState(FloatRect cropRect, float radius)
138               : cropRect(cropRect), radius(radius) {}
139 
140         // Rounded rectangle in local layer coordinate space.
141         FloatRect cropRect = FloatRect();
142         // Radius of the rounded rectangle.
143         float radius = 0.0f;
144     };
145 
146     // FrameRateCompatibility specifies how we should interpret the frame rate associated with
147     // the layer.
148     enum class FrameRateCompatibility {
149         Default, // Layer didn't specify any specific handling strategy
150 
151         ExactOrMultiple, // Layer needs the exact frame rate (or a multiple of it) to present the
152                          // content properly. Any other value will result in a pull down.
153 
154         NoVote, // Layer doesn't have any requirements for the refresh rate and
155                 // should not be considered when the display refresh rate is determined.
156     };
157 
158     // Encapsulates the frame rate and compatibility of the layer. This information will be used
159     // when the display refresh rate is determined.
160     struct FrameRate {
161         float rate;
162         FrameRateCompatibility type;
163 
FrameRateFrameRate164         FrameRate() : rate(0), type(FrameRateCompatibility::Default) {}
FrameRateFrameRate165         FrameRate(float rate, FrameRateCompatibility type) : rate(rate), type(type) {}
166 
167         bool operator==(const FrameRate& other) const {
168             return rate == other.rate && type == other.type;
169         }
170 
171         bool operator!=(const FrameRate& other) const { return !(*this == other); }
172 
173         // Convert an ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_* value to a
174         // Layer::FrameRateCompatibility. Logs fatal if the compatibility value is invalid.
175         static FrameRateCompatibility convertCompatibility(int8_t compatibility);
176     };
177 
178     struct State {
179         Geometry active_legacy;
180         Geometry requested_legacy;
181         int32_t z;
182 
183         // The identifier of the layer stack this layer belongs to. A layer can
184         // only be associated to a single layer stack. A layer stack is a
185         // z-ordered group of layers which can be associated to one or more
186         // displays. Using the same layer stack on different displays is a way
187         // to achieve mirroring.
188         uint32_t layerStack;
189 
190         uint8_t flags;
191         uint8_t reserved[2];
192         int32_t sequence; // changes when visible regions can change
193         bool modified;
194 
195         // Crop is expressed in layer space coordinate.
196         Rect crop_legacy;
197         Rect requestedCrop_legacy;
198 
199         // If set, defers this state update until the identified Layer
200         // receives a frame with the given frameNumber
201         wp<Layer> barrierLayer_legacy;
202         uint64_t frameNumber_legacy;
203 
204         // the transparentRegion hint is a bit special, it's latched only
205         // when we receive a buffer -- this is because it's "content"
206         // dependent.
207         Region activeTransparentRegion_legacy;
208         Region requestedTransparentRegion_legacy;
209 
210         LayerMetadata metadata;
211 
212         // If non-null, a Surface this Surface's Z-order is interpreted relative to.
213         wp<Layer> zOrderRelativeOf;
214         bool isRelativeOf{false};
215 
216         // A list of surfaces whose Z-order is interpreted relative to ours.
217         SortedVector<wp<Layer>> zOrderRelatives;
218 
219         half4 color;
220         float cornerRadius;
221         int backgroundBlurRadius;
222 
223         bool inputInfoChanged;
224         InputWindowInfo inputInfo;
225         wp<Layer> touchableRegionCrop;
226 
227         // dataspace is only used by BufferStateLayer and EffectLayer
228         ui::Dataspace dataspace;
229 
230         // The fields below this point are only used by BufferStateLayer
231         uint64_t frameNumber;
232         Geometry active;
233 
234         uint32_t transform;
235         bool transformToDisplayInverse;
236 
237         Rect crop;
238         Region transparentRegionHint;
239 
240         sp<GraphicBuffer> buffer;
241         client_cache_t clientCacheId;
242         sp<Fence> acquireFence;
243         HdrMetadata hdrMetadata;
244         Region surfaceDamageRegion;
245         int32_t api;
246 
247         sp<NativeHandle> sidebandStream;
248         mat4 colorTransform;
249         bool hasColorTransform;
250 
251         // pointer to background color layer that, if set, appears below the buffer state layer
252         // and the buffer state layer's children.  Z order will be set to
253         // INT_MIN
254         sp<Layer> bgColorLayer;
255 
256         // The deque of callback handles for this frame. The back of the deque contains the most
257         // recent callback handle.
258         std::deque<sp<CallbackHandle>> callbackHandles;
259         bool colorSpaceAgnostic;
260         nsecs_t desiredPresentTime = -1;
261 
262         // Length of the cast shadow. If the radius is > 0, a shadow of length shadowRadius will
263         // be rendered around the layer.
264         float shadowRadius;
265 
266         // Priority of the layer assigned by Window Manager.
267         int32_t frameRateSelectionPriority;
268 
269         FrameRate frameRate;
270 
271         // Indicates whether parents / children of this layer had set FrameRate
272         bool treeHasFrameRateVote;
273 
274         // Set by window manager indicating the layer and all its children are
275         // in a different orientation than the display. The hint suggests that
276         // the graphic producers should receive a transform hint as if the
277         // display was in this orientation. When the display changes to match
278         // the layer orientation, the graphic producer may not need to allocate
279         // a buffer of a different size. ui::Transform::ROT_INVALID means the
280         // a fixed transform hint is not set.
281         ui::Transform::RotationFlags fixedTransformHint;
282     };
283 
284     explicit Layer(const LayerCreationArgs& args);
285     virtual ~Layer();
286 
287     void onFirstRef() override;
288 
getWindowType()289     int getWindowType() const { return mWindowType; }
290 
setPrimaryDisplayOnly()291     void setPrimaryDisplayOnly() { mPrimaryDisplayOnly = true; }
getPrimaryDisplayOnly()292     bool getPrimaryDisplayOnly() const { return mPrimaryDisplayOnly; }
293 
294     // ------------------------------------------------------------------------
295     // Geometry setting functions.
296     //
297     // The following group of functions are used to specify the layers
298     // bounds, and the mapping of the texture on to those bounds. According
299     // to various settings changes to them may apply immediately, or be delayed until
300     // a pending resize is completed by the producer submitting a buffer. For example
301     // if we were to change the buffer size, and update the matrix ahead of the
302     // new buffer arriving, then we would be stretching the buffer to a different
303     // aspect before and after the buffer arriving, which probably isn't what we wanted.
304     //
305     // The first set of geometry functions are controlled by the scaling mode, described
306     // in window.h. The scaling mode may be set by the client, as it submits buffers.
307     // This value may be overriden through SurfaceControl, with setOverrideScalingMode.
308     //
309     // Put simply, if our scaling mode is SCALING_MODE_FREEZE, then
310     // matrix updates will not be applied while a resize is pending
311     // and the size and transform will remain in their previous state
312     // until a new buffer is submitted. If the scaling mode is another value
313     // then the old-buffer will immediately be scaled to the pending size
314     // and the new matrix will be immediately applied following this scaling
315     // transformation.
316 
317     // Set the default buffer size for the assosciated Producer, in pixels. This is
318     // also the rendered size of the layer prior to any transformations. Parent
319     // or local matrix transformations will not affect the size of the buffer,
320     // but may affect it's on-screen size or clipping.
321     virtual bool setSize(uint32_t w, uint32_t h);
322     // Set a 2x2 transformation matrix on the layer. This transform
323     // will be applied after parent transforms, but before any final
324     // producer specified transform.
325     virtual bool setMatrix(const layer_state_t::matrix22_t& matrix,
326                            bool allowNonRectPreservingTransforms);
327 
328     // This second set of geometry attributes are controlled by
329     // setGeometryAppliesWithResize, and their default mode is to be
330     // immediate. If setGeometryAppliesWithResize is specified
331     // while a resize is pending, then update of these attributes will
332     // be delayed until the resize completes.
333 
334     // setPosition operates in parent buffer space (pre parent-transform) or display
335     // space for top-level layers.
336     virtual bool setPosition(float x, float y);
337     // Buffer space
338     virtual bool setCrop_legacy(const Rect& crop);
339 
340     // TODO(b/38182121): Could we eliminate the various latching modes by
341     // using the layer hierarchy?
342     // -----------------------------------------------------------------------
343     virtual bool setLayer(int32_t z);
344     virtual bool setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ);
345 
346     virtual bool setAlpha(float alpha);
setColor(const half3 &)347     virtual bool setColor(const half3& /*color*/) { return false; };
348 
349     // Set rounded corner radius for this layer and its children.
350     //
351     // We only support 1 radius per layer in the hierarchy, where parent layers have precedence.
352     // The shape of the rounded corner rectangle is specified by the crop rectangle of the layer
353     // from which we inferred the rounded corner radius.
354     virtual bool setCornerRadius(float cornerRadius);
355     // When non-zero, everything below this layer will be blurred by backgroundBlurRadius, which
356     // is specified in pixels.
357     virtual bool setBackgroundBlurRadius(int backgroundBlurRadius);
358     virtual bool setTransparentRegionHint(const Region& transparent);
359     virtual bool setFlags(uint8_t flags, uint8_t mask);
360     virtual bool setLayerStack(uint32_t layerStack);
361     virtual uint32_t getLayerStack() const;
362     virtual void deferTransactionUntil_legacy(const sp<IBinder>& barrierHandle,
363                                               uint64_t frameNumber);
364     virtual void deferTransactionUntil_legacy(const sp<Layer>& barrierLayer, uint64_t frameNumber);
365     virtual bool setOverrideScalingMode(int32_t overrideScalingMode);
366     virtual bool setMetadata(const LayerMetadata& data);
367     bool reparentChildren(const sp<IBinder>& newParentHandle);
368     void reparentChildren(const sp<Layer>& newParent);
369     virtual void setChildrenDrawingParent(const sp<Layer>& layer);
370     virtual bool reparent(const sp<IBinder>& newParentHandle);
371     virtual bool detachChildren();
372     bool attachChildren();
isLayerDetached()373     bool isLayerDetached() const { return mLayerDetached; }
374     virtual bool setColorTransform(const mat4& matrix);
375     virtual mat4 getColorTransform() const;
376     virtual bool hasColorTransform() const;
isColorSpaceAgnostic()377     virtual bool isColorSpaceAgnostic() const { return mDrawingState.colorSpaceAgnostic; }
378 
379     // Used only to set BufferStateLayer state
setTransform(uint32_t)380     virtual bool setTransform(uint32_t /*transform*/) { return false; };
setTransformToDisplayInverse(bool)381     virtual bool setTransformToDisplayInverse(bool /*transformToDisplayInverse*/) { return false; };
setCrop(const Rect &)382     virtual bool setCrop(const Rect& /*crop*/) { return false; };
setFrame(const Rect &)383     virtual bool setFrame(const Rect& /*frame*/) { return false; };
setBuffer(const sp<GraphicBuffer> &,const sp<Fence> &,nsecs_t,nsecs_t,const client_cache_t &)384     virtual bool setBuffer(const sp<GraphicBuffer>& /*buffer*/, const sp<Fence>& /*acquireFence*/,
385                            nsecs_t /*postTime*/, nsecs_t /*desiredPresentTime*/,
386                            const client_cache_t& /*clientCacheId*/) {
387         return false;
388     };
setAcquireFence(const sp<Fence> &)389     virtual bool setAcquireFence(const sp<Fence>& /*fence*/) { return false; };
setDataspace(ui::Dataspace)390     virtual bool setDataspace(ui::Dataspace /*dataspace*/) { return false; };
setHdrMetadata(const HdrMetadata &)391     virtual bool setHdrMetadata(const HdrMetadata& /*hdrMetadata*/) { return false; };
setSurfaceDamageRegion(const Region &)392     virtual bool setSurfaceDamageRegion(const Region& /*surfaceDamage*/) { return false; };
setApi(int32_t)393     virtual bool setApi(int32_t /*api*/) { return false; };
setSidebandStream(const sp<NativeHandle> &)394     virtual bool setSidebandStream(const sp<NativeHandle>& /*sidebandStream*/) { return false; };
setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>> &)395     virtual bool setTransactionCompletedListeners(
396             const std::vector<sp<CallbackHandle>>& /*handles*/) {
397         return false;
398     };
forceSendCallbacks()399     virtual void forceSendCallbacks() {}
addFrameEvent(const sp<Fence> &,nsecs_t,nsecs_t)400     virtual bool addFrameEvent(const sp<Fence>& /*acquireFence*/, nsecs_t /*postedTime*/,
401                                nsecs_t /*requestedPresentTime*/) {
402         return false;
403     }
404     virtual bool setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace);
405     virtual bool setColorSpaceAgnostic(const bool agnostic);
406     bool setShadowRadius(float shadowRadius);
407     virtual bool setFrameRateSelectionPriority(int32_t priority);
408     virtual bool setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint);
409     //  If the variable is not set on the layer, it traverses up the tree to inherit the frame
410     //  rate priority from its parent.
411     virtual int32_t getFrameRateSelectionPriority() const;
412     static bool isLayerFocusedBasedOnPriority(int32_t priority);
413 
getDataSpace()414     virtual ui::Dataspace getDataSpace() const { return ui::Dataspace::UNKNOWN; }
415 
416     // Before color management is introduced, contents on Android have to be
417     // desaturated in order to match what they appears like visually.
418     // With color management, these contents will appear desaturated, thus
419     // needed to be saturated so that they match what they are designed for
420     // visually.
421     bool isLegacyDataSpace() const;
422 
423     virtual sp<compositionengine::LayerFE> getCompositionEngineLayerFE() const;
424     virtual compositionengine::LayerFECompositionState* editCompositionState();
425 
426     // If we have received a new buffer this frame, we will pass its surface
427     // damage down to hardware composer. Otherwise, we must send a region with
428     // one empty rect.
useSurfaceDamage()429     virtual void useSurfaceDamage() {}
useEmptyDamage()430     virtual void useEmptyDamage() {}
431 
getTransactionFlags()432     uint32_t getTransactionFlags() const { return mTransactionFlags; }
433     uint32_t getTransactionFlags(uint32_t flags);
434     uint32_t setTransactionFlags(uint32_t flags);
435 
436     // Deprecated, please use compositionengine::Output::belongsInOutput()
437     // instead.
438     // TODO(lpique): Move the remaining callers (screencap) to the new function.
belongsToDisplay(uint32_t layerStack,bool isPrimaryDisplay)439     bool belongsToDisplay(uint32_t layerStack, bool isPrimaryDisplay) const {
440         return getLayerStack() == layerStack && (!mPrimaryDisplayOnly || isPrimaryDisplay);
441     }
442 
443     FloatRect getBounds(const Region& activeTransparentRegion) const;
444     FloatRect getBounds() const;
445 
446     // Compute bounds for the layer and cache the results.
447     void computeBounds(FloatRect parentBounds, ui::Transform parentTransform, float shadowRadius);
448 
449     // Returns the buffer scale transform if a scaling mode is set.
450     ui::Transform getBufferScaleTransform() const;
451 
452     // Get effective layer transform, taking into account all its parent transform with any
453     // scaling if the parent scaling more is not NATIVE_WINDOW_SCALING_MODE_FREEZE.
454     ui::Transform getTransformWithScale(const ui::Transform& bufferScaleTransform) const;
455 
456     // Returns the bounds of the layer without any buffer scaling.
457     FloatRect getBoundsPreScaling(const ui::Transform& bufferScaleTransform) const;
458 
getSequence()459     int32_t getSequence() const { return sequence; }
460 
461     // For tracing.
462     // TODO: Replace with raw buffer id from buffer metadata when that becomes available.
463     // GraphicBuffer::getId() does not provide a reliable global identifier. Since the traces
464     // creates its tracks by buffer id and has no way of associating a buffer back to the process
465     // that created it, the current implementation is only sufficient for cases where a buffer is
466     // only used within a single layer.
getCurrentBufferId()467     uint64_t getCurrentBufferId() const { return getBuffer() ? getBuffer()->getId() : 0; }
468 
469     // -----------------------------------------------------------------------
470     // Virtuals
471 
472     // Provide unique string for each class type in the Layer hierarchy
473     virtual const char* getType() const = 0;
474 
475     /*
476      * isOpaque - true if this surface is opaque
477      *
478      * This takes into account the buffer format (i.e. whether or not the
479      * pixel format includes an alpha channel) and the "opaque" flag set
480      * on the layer.  It does not examine the current plane alpha value.
481      */
isOpaque(const Layer::State &)482     virtual bool isOpaque(const Layer::State&) const { return false; }
483 
484     /*
485      * isSecure - true if this surface is secure, that is if it prevents
486      * screenshots or VNC servers.
487      */
488     bool isSecure() const;
489 
490     /*
491      * isVisible - true if this layer is visible, false otherwise
492      */
493     virtual bool isVisible() const = 0;
494 
495     /*
496      * isHiddenByPolicy - true if this layer has been forced invisible.
497      * just because this is false, doesn't mean isVisible() is true.
498      * For example if this layer has no active buffer, it may not be hidden by
499      * policy, but it still can not be visible.
500      */
501     bool isHiddenByPolicy() const;
502 
503     /*
504      * Returns whether this layer can receive input.
505      */
506     virtual bool canReceiveInput() const;
507 
508     /*
509      * isProtected - true if the layer may contain protected content in the
510      * GRALLOC_USAGE_PROTECTED sense.
511      */
isProtected()512     virtual bool isProtected() const { return false; }
513 
514     /*
515      * isFixedSize - true if content has a fixed size
516      */
isFixedSize()517     virtual bool isFixedSize() const { return true; }
518 
519     /*
520      * usesSourceCrop - true if content should use a source crop
521      */
usesSourceCrop()522     virtual bool usesSourceCrop() const { return false; }
523 
524     // Most layers aren't created from the main thread, and therefore need to
525     // grab the SF state lock to access HWC, but ContainerLayer does, so we need
526     // to avoid grabbing the lock again to avoid deadlock
isCreatedFromMainThread()527     virtual bool isCreatedFromMainThread() const { return false; }
528 
529     bool isRemovedFromCurrentState() const;
530 
531     LayerProto* writeToProto(LayersProto& layersProto, uint32_t traceFlags,
532                              const DisplayDevice*) const;
533 
534     // Write states that are modified by the main thread. This includes drawing
535     // state as well as buffer data. This should be called in the main or tracing
536     // thread.
537     void writeToProtoDrawingState(LayerProto* layerInfo, uint32_t traceFlags,
538                                   const DisplayDevice*) const;
539     // Write drawing or current state. If writing current state, the caller should hold the
540     // external mStateLock. If writing drawing state, this function should be called on the
541     // main or tracing thread.
542     void writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
543                                  uint32_t traceFlags = SurfaceTracing::TRACE_ALL) const;
544 
getActiveGeometry(const Layer::State & s)545     virtual Geometry getActiveGeometry(const Layer::State& s) const { return s.active_legacy; }
getActiveWidth(const Layer::State & s)546     virtual uint32_t getActiveWidth(const Layer::State& s) const { return s.active_legacy.w; }
getActiveHeight(const Layer::State & s)547     virtual uint32_t getActiveHeight(const Layer::State& s) const { return s.active_legacy.h; }
getActiveTransform(const Layer::State & s)548     virtual ui::Transform getActiveTransform(const Layer::State& s) const {
549         return s.active_legacy.transform;
550     }
getActiveTransparentRegion(const Layer::State & s)551     virtual Region getActiveTransparentRegion(const Layer::State& s) const {
552         return s.activeTransparentRegion_legacy;
553     }
getCrop(const Layer::State & s)554     virtual Rect getCrop(const Layer::State& s) const { return s.crop_legacy; }
needsFiltering(const DisplayDevice *)555     virtual bool needsFiltering(const DisplayDevice*) const { return false; }
556     // True if this layer requires filtering
557     // This method is distinct from needsFiltering() in how the filter
558     // requirement is computed. needsFiltering() compares displayFrame and crop,
559     // where as this method transforms the displayFrame to layer-stack space
560     // first. This method should be used if there is no physical display to
561     // project onto when taking screenshots, as the filtering requirements are
562     // different.
563     // If the parent transform needs to be undone when capturing the layer, then
564     // the inverse parent transform is also required.
needsFilteringForScreenshots(const DisplayDevice *,const ui::Transform &)565     virtual bool needsFilteringForScreenshots(const DisplayDevice*, const ui::Transform&) const {
566         return false;
567     }
568 
569     // This layer is not a clone, but it's the parent to the cloned hierarchy. The
570     // variable mClonedChild represents the top layer that will be cloned so this
571     // layer will be the parent of mClonedChild.
572     // The layers in the cloned hierarchy will match the lifetime of the real layers. That is
573     // if the real layer is destroyed, then the clone layer will also be destroyed.
574     sp<Layer> mClonedChild;
575 
576     virtual sp<Layer> createClone() = 0;
577     void updateMirrorInfo();
updateCloneBufferInfo()578     virtual void updateCloneBufferInfo(){};
579 
580 protected:
581     sp<compositionengine::LayerFE> asLayerFE() const;
getClonedFrom()582     sp<Layer> getClonedFrom() { return mClonedFrom != nullptr ? mClonedFrom.promote() : nullptr; }
isClone()583     bool isClone() { return mClonedFrom != nullptr; }
isClonedFromAlive()584     bool isClonedFromAlive() { return getClonedFrom() != nullptr; }
585 
586     virtual void setInitialValuesForClone(const sp<Layer>& clonedFrom);
587 
588     void updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap);
589     void updateClonedChildren(const sp<Layer>& mirrorRoot,
590                               std::map<sp<Layer>, sp<Layer>>& clonedLayersMap);
591     void updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap);
592     void addChildToDrawing(const sp<Layer>& layer);
593     void updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap);
594     virtual std::optional<compositionengine::LayerFE::LayerSettings> prepareClientComposition(
595             compositionengine::LayerFE::ClientCompositionTargetSettings&);
596     virtual std::optional<compositionengine::LayerFE::LayerSettings> prepareShadowClientComposition(
597             const LayerFE::LayerSettings& layerSettings, const Rect& displayViewport,
598             ui::Dataspace outputDataspace);
599     // Modifies the passed in layer settings to clear the contents. If the blackout flag is set,
600     // the settings clears the content with a solid black fill.
601     void prepareClearClientComposition(LayerFE::LayerSettings& layerSettings, bool blackout) const;
602 
603 public:
604     /*
605      * compositionengine::LayerFE overrides
606      */
607     const compositionengine::LayerFECompositionState* getCompositionState() const override;
608     bool onPreComposition(nsecs_t) override;
609     void prepareCompositionState(compositionengine::LayerFE::StateSubset subset) override;
610     std::vector<compositionengine::LayerFE::LayerSettings> prepareClientCompositionList(
611             compositionengine::LayerFE::ClientCompositionTargetSettings&) override;
612     void onLayerDisplayed(const sp<Fence>& releaseFence) override;
613     const char* getDebugName() const override;
614 
615 protected:
616     void prepareBasicGeometryCompositionState();
617     void prepareGeometryCompositionState();
618     virtual void preparePerFrameCompositionState();
619     void prepareCursorCompositionState();
620 
621 public:
setDefaultBufferSize(uint32_t,uint32_t)622     virtual void setDefaultBufferSize(uint32_t /*w*/, uint32_t /*h*/) {}
623 
isHdrY410()624     virtual bool isHdrY410() const { return false; }
625 
shouldPresentNow(nsecs_t)626     virtual bool shouldPresentNow(nsecs_t /*expectedPresentTime*/) const { return false; }
627 
628     /*
629      * called after composition.
630      * returns true if the layer latched a new buffer this frame.
631      */
onPostComposition(const DisplayDevice *,const std::shared_ptr<FenceTime> &,const std::shared_ptr<FenceTime> &,const CompositorTiming &)632     virtual bool onPostComposition(const DisplayDevice*,
633                                    const std::shared_ptr<FenceTime>& /*glDoneFence*/,
634                                    const std::shared_ptr<FenceTime>& /*presentFence*/,
635                                    const CompositorTiming&) {
636         return false;
637     }
638 
639     // If a buffer was replaced this frame, release the former buffer
releasePendingBuffer(nsecs_t)640     virtual void releasePendingBuffer(nsecs_t /*dequeueReadyTime*/) { }
641 
finalizeFrameEventHistory(const std::shared_ptr<FenceTime> &,const CompositorTiming &)642     virtual void finalizeFrameEventHistory(const std::shared_ptr<FenceTime>& /*glDoneFence*/,
643                                            const CompositorTiming& /*compositorTiming*/) {}
644     /*
645      * doTransaction - process the transaction. This is a good place to figure
646      * out which attributes of the surface have changed.
647      */
648     uint32_t doTransaction(uint32_t transactionFlags);
649 
650     /*
651      * latchBuffer - called each time the screen is redrawn and returns whether
652      * the visible regions need to be recomputed (this is a fairly heavy
653      * operation, so this should be set only if needed). Typically this is used
654      * to figure out if the content or size of a surface has changed.
655      */
latchBuffer(bool &,nsecs_t,nsecs_t)656     virtual bool latchBuffer(bool& /*recomputeVisibleRegions*/, nsecs_t /*latchTime*/,
657                              nsecs_t /*expectedPresentTime*/) {
658         return false;
659     }
660 
isBufferLatched()661     virtual bool isBufferLatched() const { return false; }
662 
latchAndReleaseBuffer()663     virtual void latchAndReleaseBuffer() {}
664 
665     /*
666      * Remove relative z for the layer if its relative parent is not part of the
667      * provided layer tree.
668      */
669     void removeRelativeZ(const std::vector<Layer*>& layersInTree);
670 
671     /*
672      * Remove from current state and mark for removal.
673      */
674     void removeFromCurrentState();
675 
676     /*
677      * called with the state lock from a binder thread when the layer is
678      * removed from the current list to the pending removal list
679      */
680     void onRemovedFromCurrentState();
681 
682     /*
683      * Called when the layer is added back to the current state list.
684      */
685     void addToCurrentState();
686 
687     /*
688      * Sets display transform hint on BufferLayerConsumer.
689      */
690     void updateTransformHint(ui::Transform::RotationFlags);
691 
692     /*
693      * returns the rectangle that crops the content of the layer and scales it
694      * to the layer's size.
695      */
getBufferCrop()696     virtual Rect getBufferCrop() const { return Rect(); }
697 
698     /*
699      * Returns the transform applied to the buffer.
700      */
getBufferTransform()701     virtual uint32_t getBufferTransform() const { return 0; }
702 
getBuffer()703     virtual sp<GraphicBuffer> getBuffer() const { return nullptr; }
704 
getTransformHint()705     virtual ui::Transform::RotationFlags getTransformHint() const { return ui::Transform::ROT_0; }
706 
707     /*
708      * Returns if a frame is ready
709      */
hasReadyFrame()710     virtual bool hasReadyFrame() const { return false; }
711 
getQueuedFrameCount()712     virtual int32_t getQueuedFrameCount() const { return 0; }
713 
714     // -----------------------------------------------------------------------
getDrawingState()715     inline const State& getDrawingState() const { return mDrawingState; }
getCurrentState()716     inline const State& getCurrentState() const { return mCurrentState; }
getCurrentState()717     inline State& getCurrentState() { return mCurrentState; }
718 
719     LayerDebugInfo getLayerDebugInfo(const DisplayDevice*) const;
720 
721     static void miniDumpHeader(std::string& result);
722     void miniDump(std::string& result, const DisplayDevice&) const;
723     void dumpFrameStats(std::string& result) const;
724     void dumpFrameEvents(std::string& result);
725     void dumpCallingUidPid(std::string& result) const;
726     void clearFrameStats();
727     void logFrameStats();
728     void getFrameStats(FrameStats* outStats) const;
729 
getOccupancyHistory(bool)730     virtual std::vector<OccupancyTracker::Segment> getOccupancyHistory(bool /*forceFlush*/) {
731         return {};
732     }
733 
734     void onDisconnect();
735     void addAndGetFrameTimestamps(const NewFrameEventsEntry* newEntry,
736                                   FrameEventHistoryDelta* outDelta);
737 
getTransformToDisplayInverse()738     virtual bool getTransformToDisplayInverse() const { return false; }
739 
740     ui::Transform getTransform() const;
741 
742     // Returns the Alpha of the Surface, accounting for the Alpha
743     // of parent Surfaces in the hierarchy (alpha's will be multiplied
744     // down the hierarchy).
745     half getAlpha() const;
746     half4 getColor() const;
747     int32_t getBackgroundBlurRadius() const;
drawShadows()748     bool drawShadows() const { return mEffectiveShadowRadius > 0.f; };
749 
750     // Returns the transform hint set by Window Manager on the layer or one of its parents.
751     // This traverses the current state because the data is needed when creating
752     // the layer(off drawing thread) and the hint should be available before the producer
753     // is ready to acquire a buffer.
754     ui::Transform::RotationFlags getFixedTransformHint() const;
755 
756     // Returns how rounded corners should be drawn for this layer.
757     // This will traverse the hierarchy until it reaches its root, finding topmost rounded
758     // corner definition and converting it into current layer's coordinates.
759     // As of now, only 1 corner radius per display list is supported. Subsequent ones will be
760     // ignored.
761     virtual RoundedCornerState getRoundedCornerState() const;
762 
763     renderengine::ShadowSettings getShadowSettings(const Rect& viewport) const;
764 
765     /**
766      * Traverse this layer and it's hierarchy of children directly. Unlike traverseInZOrder
767      * which will not emit children who have relativeZOrder to another layer, this method
768      * just directly emits all children. It also emits them in no particular order.
769      * So this method is not suitable for graphical operations, as it doesn't represent
770      * the scene state, but it's also more efficient than traverseInZOrder and so useful for
771      * book-keeping.
772      */
773     void traverse(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor);
774     void traverseInReverseZOrder(LayerVector::StateSet stateSet,
775                                  const LayerVector::Visitor& visitor);
776     void traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor);
777 
778     /**
779      * Traverse only children in z order, ignoring relative layers that are not children of the
780      * parent.
781      */
782     void traverseChildrenInZOrder(LayerVector::StateSet stateSet,
783                                   const LayerVector::Visitor& visitor);
784 
785     size_t getChildrenCount() const;
786 
787     // ONLY CALL THIS FROM THE LAYER DTOR!
788     // See b/141111965.  We need to add current children to offscreen layers in
789     // the layer dtor so as not to dangle layers.  Since the layer has not
790     // committed its transaction when the layer is destroyed, we must add
791     // current children.  This is safe in the dtor as we will no longer update
792     // the current state, but should not be called anywhere else!
getCurrentChildren()793     LayerVector& getCurrentChildren() { return mCurrentChildren; }
794 
795     void addChild(const sp<Layer>& layer);
796     // Returns index if removed, or negative value otherwise
797     // for symmetry with Vector::remove
798     ssize_t removeChild(const sp<Layer>& layer);
getParent()799     sp<Layer> getParent() const { return mCurrentParent.promote(); }
hasParent()800     bool hasParent() const { return getParent() != nullptr; }
801     Rect getScreenBounds(bool reduceTransparentRegion = true) const;
802     bool setChildLayer(const sp<Layer>& childLayer, int32_t z);
803     bool setChildRelativeLayer(const sp<Layer>& childLayer,
804             const sp<IBinder>& relativeToHandle, int32_t relativeZ);
805 
806     // Copy the current list of children to the drawing state. Called by
807     // SurfaceFlinger to complete a transaction.
808     void commitChildList();
809     int32_t getZ(LayerVector::StateSet stateSet) const;
810     virtual void pushPendingState();
811 
812     /**
813      * Returns active buffer size in the correct orientation. Buffer size is determined by undoing
814      * any buffer transformations. If the layer has no buffer then return INVALID_RECT.
815      */
getBufferSize(const Layer::State &)816     virtual Rect getBufferSize(const Layer::State&) const { return Rect::INVALID_RECT; }
817 
818     /**
819      * Returns the source bounds. If the bounds are not defined, it is inferred from the
820      * buffer size. Failing that, the bounds are determined from the passed in parent bounds.
821      * For the root layer, this is the display viewport size.
822      */
computeSourceBounds(const FloatRect & parentBounds)823     virtual FloatRect computeSourceBounds(const FloatRect& parentBounds) const {
824         return parentBounds;
825     }
826 
827     /**
828      * Returns the cropped buffer size or the layer crop if the layer has no buffer. Return
829      * INVALID_RECT if the layer has no buffer and no crop.
830      * A layer with an invalid buffer size and no crop is considered to be boundless. The layer
831      * bounds are constrained by its parent bounds.
832      */
833     Rect getCroppedBufferSize(const Layer::State& s) const;
834 
835     bool setFrameRate(FrameRate frameRate);
836     virtual FrameRate getFrameRateForLayerTree() const;
837     static std::string frameRateCompatibilityString(FrameRateCompatibility compatibility);
838 
839 protected:
840     // constant
841     sp<SurfaceFlinger> mFlinger;
842     /*
843      * Trivial class, used to ensure that mFlinger->onLayerDestroyed(mLayer)
844      * is called.
845      */
846     class LayerCleaner {
847         sp<SurfaceFlinger> mFlinger;
848         sp<Layer> mLayer;
849 
850     protected:
~LayerCleaner()851         ~LayerCleaner() {
852             // destroy client resources
853             mFlinger->onHandleDestroyed(mLayer);
854         }
855 
856     public:
LayerCleaner(const sp<SurfaceFlinger> & flinger,const sp<Layer> & layer)857         LayerCleaner(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
858               : mFlinger(flinger), mLayer(layer) {}
859     };
860 
861     friend class impl::SurfaceInterceptor;
862 
863     // For unit tests
864     friend class TestableSurfaceFlinger;
865     friend class RefreshRateSelectionTest;
866     friend class SetFrameRateTest;
867 
868     virtual void commitTransaction(const State& stateToCommit);
869 
870     uint32_t getEffectiveUsage(uint32_t usage) const;
871 
872     /**
873      * Setup rounded corners coordinates of this layer, taking into account the layer bounds and
874      * crop coordinates, transforming them into layer space.
875      */
876     void setupRoundedCornersCropCoordinates(Rect win, const FloatRect& roundedCornersCrop) const;
877     void setParent(const sp<Layer>& layer);
878     LayerVector makeTraversalList(LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers);
879     void addZOrderRelative(const wp<Layer>& relative);
880     void removeZOrderRelative(const wp<Layer>& relative);
881 
882     class SyncPoint {
883     public:
SyncPoint(uint64_t frameNumber,wp<Layer> requestedSyncLayer)884         explicit SyncPoint(uint64_t frameNumber, wp<Layer> requestedSyncLayer)
885               : mFrameNumber(frameNumber),
886                 mFrameIsAvailable(false),
887                 mTransactionIsApplied(false),
888                 mRequestedSyncLayer(requestedSyncLayer) {}
889 
getFrameNumber()890         uint64_t getFrameNumber() const { return mFrameNumber; }
891 
frameIsAvailable()892         bool frameIsAvailable() const { return mFrameIsAvailable; }
893 
setFrameAvailable()894         void setFrameAvailable() { mFrameIsAvailable = true; }
895 
transactionIsApplied()896         bool transactionIsApplied() const { return mTransactionIsApplied; }
897 
setTransactionApplied()898         void setTransactionApplied() { mTransactionIsApplied = true; }
899 
getRequestedSyncLayer()900         sp<Layer> getRequestedSyncLayer() { return mRequestedSyncLayer.promote(); }
901 
902     private:
903         const uint64_t mFrameNumber;
904         std::atomic<bool> mFrameIsAvailable;
905         std::atomic<bool> mTransactionIsApplied;
906         wp<Layer> mRequestedSyncLayer;
907     };
908 
909     // SyncPoints which will be signaled when the correct frame is at the head
910     // of the queue and dropped after the frame has been latched. Protected by
911     // mLocalSyncPointMutex.
912     Mutex mLocalSyncPointMutex;
913     std::list<std::shared_ptr<SyncPoint>> mLocalSyncPoints;
914 
915     // SyncPoints which will be signaled and then dropped when the transaction
916     // is applied
917     std::list<std::shared_ptr<SyncPoint>> mRemoteSyncPoints;
918 
919     // Returns false if the relevant frame has already been latched
920     bool addSyncPoint(const std::shared_ptr<SyncPoint>& point);
921 
922     void popPendingState(State* stateToCommit);
923     virtual bool applyPendingStates(State* stateToCommit);
924     virtual uint32_t doTransactionResize(uint32_t flags, Layer::State* stateToCommit);
925 
926     // Returns mCurrentScaling mode (originating from the
927     // Client) or mOverrideScalingMode mode (originating from
928     // the Surface Controller) if set.
getEffectiveScalingMode()929     virtual uint32_t getEffectiveScalingMode() const { return 0; }
930 
931 public:
932     /*
933      * The layer handle is just a BBinder object passed to the client
934      * (remote process) -- we don't keep any reference on our side such that
935      * the dtor is called when the remote side let go of its reference.
936      *
937      * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
938      * this layer when the handle is destroyed.
939      */
940     class Handle : public BBinder, public LayerCleaner {
941     public:
Handle(const sp<SurfaceFlinger> & flinger,const sp<Layer> & layer)942         Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
943               : LayerCleaner(flinger, layer), owner(layer) {}
944 
945         wp<Layer> owner;
946     };
947 
948     // Creates a new handle each time, so we only expect
949     // this to be called once.
950     sp<IBinder> getHandle();
getName()951     const std::string& getName() const { return mName; }
notifyAvailableFrames(nsecs_t)952     virtual void notifyAvailableFrames(nsecs_t /*expectedPresentTime*/) {}
getPixelFormat()953     virtual PixelFormat getPixelFormat() const { return PIXEL_FORMAT_NONE; }
954     bool getPremultipledAlpha() const;
955 
956     bool mPendingHWCDestroy{false};
957     void setInputInfo(const InputWindowInfo& info);
958 
959     InputWindowInfo fillInputInfo();
960     /**
961      * Returns whether this layer has an explicitly set input-info.
962      */
963     bool hasInputInfo() const;
964     /**
965      * Return whether this layer needs an input info. For most layer types
966      * this is only true if they explicitly set an input-info but BufferLayer
967      * overrides this so we can generate input-info for Buffered layers that don't
968      * have them (for input occlusion detection checks).
969      */
needsInputInfo()970     virtual bool needsInputInfo() const { return hasInputInfo(); }
971 
972 protected:
973     compositionengine::OutputLayer* findOutputLayerForDisplay(const DisplayDevice*) const;
974 
975     bool usingRelativeZ(LayerVector::StateSet stateSet) const;
976 
977     bool mPremultipliedAlpha{true};
978     const std::string mName;
979     const std::string mTransactionName{"TX - " + mName};
980 
981     bool mPrimaryDisplayOnly = false;
982 
983     // These are only accessed by the main thread or the tracing thread.
984     State mDrawingState;
985     // Store a copy of the pending state so that the drawing thread can access the
986     // states without a lock.
987     Vector<State> mPendingStatesSnapshot;
988 
989     // these are protected by an external lock (mStateLock)
990     State mCurrentState;
991     std::atomic<uint32_t> mTransactionFlags{0};
992     Vector<State> mPendingStates;
993 
994     // Timestamp history for UIAutomation. Thread safe.
995     FrameTracker mFrameTracker;
996 
997     // Timestamp history for the consumer to query.
998     // Accessed by both consumer and producer on main and binder threads.
999     Mutex mFrameEventHistoryMutex;
1000     ConsumerFrameEventHistory mFrameEventHistory;
1001     FenceTimeline mAcquireTimeline;
1002     FenceTimeline mReleaseTimeline;
1003 
1004     // main thread
1005     sp<NativeHandle> mSidebandStream;
1006     // False if the buffer and its contents have been previously used for GPU
1007     // composition, true otherwise.
1008     bool mIsActiveBufferUpdatedForGpu = true;
1009 
1010     // We encode unset as -1.
1011     int32_t mOverrideScalingMode{-1};
1012     std::atomic<uint64_t> mCurrentFrameNumber{0};
1013     // Whether filtering is needed b/c of the drawingstate
1014     bool mNeedsFiltering{false};
1015 
1016     std::atomic<bool> mRemovedFromCurrentState{false};
1017 
1018     // page-flip thread (currently main thread)
1019     bool mProtectedByApp{false}; // application requires protected path to external sink
1020 
1021     // protected by mLock
1022     mutable Mutex mLock;
1023 
1024     const wp<Client> mClientRef;
1025 
1026     // This layer can be a cursor on some displays.
1027     bool mPotentialCursor{false};
1028 
1029     // Child list about to be committed/used for editing.
1030     LayerVector mCurrentChildren{LayerVector::StateSet::Current};
1031     // Child list used for rendering.
1032     LayerVector mDrawingChildren{LayerVector::StateSet::Drawing};
1033 
1034     wp<Layer> mCurrentParent;
1035     wp<Layer> mDrawingParent;
1036 
1037     // Can only be accessed with the SF state lock held.
1038     bool mLayerDetached{false};
1039     // Can only be accessed with the SF state lock held.
1040     bool mChildrenChanged{false};
1041 
1042     // Window types from WindowManager.LayoutParams
1043     const int mWindowType;
1044 
1045 private:
setTransformHint(ui::Transform::RotationFlags)1046     virtual void setTransformHint(ui::Transform::RotationFlags) {}
1047 
1048     Hwc2::IComposerClient::Composition getCompositionType(const DisplayDevice&) const;
1049     Region getVisibleRegion(const DisplayDevice*) const;
1050 
1051     /**
1052      * Returns an unsorted vector of all layers that are part of this tree.
1053      * That includes the current layer and all its descendants.
1054      */
1055     std::vector<Layer*> getLayersInTree(LayerVector::StateSet stateSet);
1056     /**
1057      * Traverses layers that are part of this tree in the correct z order.
1058      * layersInTree must be sorted before calling this method.
1059      */
1060     void traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1061                                        LayerVector::StateSet stateSet,
1062                                        const LayerVector::Visitor& visitor);
1063     LayerVector makeChildrenTraversalList(LayerVector::StateSet stateSet,
1064                                           const std::vector<Layer*>& layersInTree);
1065 
1066     void updateTreeHasFrameRateVote();
1067 
1068     // Cached properties computed from drawing state
1069     // Effective transform taking into account parent transforms and any parent scaling.
1070     ui::Transform mEffectiveTransform;
1071 
1072     // Bounds of the layer before any transformation is applied and before it has been cropped
1073     // by its parents.
1074     FloatRect mSourceBounds;
1075 
1076     // Bounds of the layer in layer space. This is the mSourceBounds cropped by its layer crop and
1077     // its parent bounds.
1078     FloatRect mBounds;
1079 
1080     // Layer bounds in screen space.
1081     FloatRect mScreenBounds;
1082 
1083     void setZOrderRelativeOf(const wp<Layer>& relativeOf);
1084 
1085     bool mGetHandleCalled = false;
1086 
1087     void removeRemoteSyncPoints();
1088 
1089     // Tracks the process and user id of the caller when creating this layer
1090     // to help debugging.
1091     pid_t mCallingPid;
1092     uid_t mCallingUid;
1093 
1094     // The current layer is a clone of mClonedFrom. This means that this layer will update it's
1095     // properties based on mClonedFrom. When mClonedFrom latches a new buffer for BufferLayers,
1096     // this layer will update it's buffer. When mClonedFrom updates it's drawing state, children,
1097     // and relatives, this layer will update as well.
1098     wp<Layer> mClonedFrom;
1099 
1100     // The inherited shadow radius after taking into account the layer hierarchy. This is the
1101     // final shadow radius for this layer. If a shadow is specified for a layer, then effective
1102     // shadow radius is the set shadow radius, otherwise its the parent's shadow radius.
1103     float mEffectiveShadowRadius = 0.f;
1104 
1105     // Returns true if the layer can draw shadows on its border.
canDrawShadows()1106     virtual bool canDrawShadows() const { return true; }
1107 
1108     // Find the root of the cloned hierarchy, this means the first non cloned parent.
1109     // This will return null if first non cloned parent is not found.
1110     sp<Layer> getClonedRoot();
1111 
1112     // Finds the top most layer in the hierarchy. This will find the root Layer where the parent is
1113     // null.
1114     sp<Layer> getRootLayer();
1115 };
1116 
1117 } // namespace android
1118