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 #ifndef ANDROID_LAYER_H
18 #define ANDROID_LAYER_H
19 
20 #include <compositionengine/LayerFE.h>
21 #include <gui/BufferQueue.h>
22 #include <gui/ISurfaceComposerClient.h>
23 #include <gui/LayerState.h>
24 #include <input/InputWindow.h>
25 #include <layerproto/LayerProtoHeader.h>
26 #include <math/vec4.h>
27 #include <renderengine/Mesh.h>
28 #include <renderengine/Texture.h>
29 #include <sys/types.h>
30 #include <ui/FloatRect.h>
31 #include <ui/FrameStats.h>
32 #include <ui/GraphicBuffer.h>
33 #include <ui/PixelFormat.h>
34 #include <ui/Region.h>
35 #include <ui/Transform.h>
36 #include <utils/RefBase.h>
37 #include <utils/String8.h>
38 #include <utils/Timers.h>
39 
40 #include <cstdint>
41 #include <list>
42 #include <optional>
43 #include <vector>
44 
45 #include "Client.h"
46 #include "ClientCache.h"
47 #include "DisplayHardware/ComposerHal.h"
48 #include "DisplayHardware/HWComposer.h"
49 #include "FrameTracker.h"
50 #include "LayerVector.h"
51 #include "MonitoredProducer.h"
52 #include "RenderArea.h"
53 #include "SurfaceFlinger.h"
54 #include "TransactionCompletedThread.h"
55 
56 using namespace android::surfaceflinger;
57 
58 namespace android {
59 
60 // ---------------------------------------------------------------------------
61 
62 class Client;
63 class Colorizer;
64 class DisplayDevice;
65 class GraphicBuffer;
66 class SurfaceFlinger;
67 class LayerDebugInfo;
68 
69 namespace compositionengine {
70 class Layer;
71 class OutputLayer;
72 struct LayerFECompositionState;
73 }
74 
75 namespace impl {
76 class SurfaceInterceptor;
77 }
78 
79 // ---------------------------------------------------------------------------
80 
81 struct LayerCreationArgs {
LayerCreationArgsLayerCreationArgs82     LayerCreationArgs(SurfaceFlinger* flinger, const sp<Client>& client, const String8& name,
83                       uint32_t w, uint32_t h, uint32_t flags, LayerMetadata metadata)
84           : flinger(flinger), client(client), name(name), w(w), h(h), flags(flags),
85             metadata(std::move(metadata)) {}
86 
87     SurfaceFlinger* flinger;
88     const sp<Client>& client;
89     const String8& name;
90     uint32_t w;
91     uint32_t h;
92     uint32_t flags;
93     LayerMetadata metadata;
94 };
95 
96 class Layer : public virtual compositionengine::LayerFE {
97     static std::atomic<int32_t> sSequence;
98 
99 public:
100     mutable bool contentDirty{false};
101     // regions below are in window-manager space
102     Region visibleRegion;
103     Region coveredRegion;
104     Region visibleNonTransparentRegion;
105     Region surfaceDamageRegion;
106 
107     // Layer serial number.  This gives layers an explicit ordering, so we
108     // have a stable sort order when their layer stack and Z-order are
109     // the same.
110     int32_t sequence{sSequence++};
111 
112     enum { // flags for doTransaction()
113         eDontUpdateGeometryState = 0x00000001,
114         eVisibleRegion = 0x00000002,
115         eInputInfoChanged = 0x00000004
116     };
117 
118     struct Geometry {
119         uint32_t w;
120         uint32_t h;
121         ui::Transform transform;
122 
123         inline bool operator==(const Geometry& rhs) const {
124             return (w == rhs.w && h == rhs.h) && (transform.tx() == rhs.transform.tx()) &&
125                     (transform.ty() == rhs.transform.ty());
126         }
127         inline bool operator!=(const Geometry& rhs) const { return !operator==(rhs); }
128     };
129 
130     struct RoundedCornerState {
131         RoundedCornerState() = default;
RoundedCornerStateRoundedCornerState132         RoundedCornerState(FloatRect cropRect, float radius)
133               : cropRect(cropRect), radius(radius) {}
134 
135         // Rounded rectangle in local layer coordinate space.
136         FloatRect cropRect = FloatRect();
137         // Radius of the rounded rectangle.
138         float radius = 0.0f;
139     };
140 
141     struct State {
142         Geometry active_legacy;
143         Geometry requested_legacy;
144         int32_t z;
145 
146         // The identifier of the layer stack this layer belongs to. A layer can
147         // only be associated to a single layer stack. A layer stack is a
148         // z-ordered group of layers which can be associated to one or more
149         // displays. Using the same layer stack on different displays is a way
150         // to achieve mirroring.
151         uint32_t layerStack;
152 
153         uint8_t flags;
154         uint8_t reserved[2];
155         int32_t sequence; // changes when visible regions can change
156         bool modified;
157 
158         // Crop is expressed in layer space coordinate.
159         Rect crop_legacy;
160         Rect requestedCrop_legacy;
161 
162         // If set, defers this state update until the identified Layer
163         // receives a frame with the given frameNumber
164         wp<Layer> barrierLayer_legacy;
165         uint64_t frameNumber_legacy;
166 
167         // the transparentRegion hint is a bit special, it's latched only
168         // when we receive a buffer -- this is because it's "content"
169         // dependent.
170         Region activeTransparentRegion_legacy;
171         Region requestedTransparentRegion_legacy;
172 
173         LayerMetadata metadata;
174 
175         // If non-null, a Surface this Surface's Z-order is interpreted relative to.
176         wp<Layer> zOrderRelativeOf;
177 
178         // A list of surfaces whose Z-order is interpreted relative to ours.
179         SortedVector<wp<Layer>> zOrderRelatives;
180 
181         half4 color;
182         float cornerRadius;
183 
184         bool inputInfoChanged;
185         InputWindowInfo inputInfo;
186         wp<Layer> touchableRegionCrop;
187 
188         // dataspace is only used by BufferStateLayer and ColorLayer
189         ui::Dataspace dataspace;
190 
191         // The fields below this point are only used by BufferStateLayer
192         Geometry active;
193 
194         uint32_t transform;
195         bool transformToDisplayInverse;
196 
197         Rect crop;
198         Region transparentRegionHint;
199 
200         sp<GraphicBuffer> buffer;
201         client_cache_t clientCacheId;
202         sp<Fence> acquireFence;
203         HdrMetadata hdrMetadata;
204         Region surfaceDamageRegion;
205         int32_t api;
206 
207         sp<NativeHandle> sidebandStream;
208         mat4 colorTransform;
209         bool hasColorTransform;
210 
211         // pointer to background color layer that, if set, appears below the buffer state layer
212         // and the buffer state layer's children.  Z order will be set to
213         // INT_MIN
214         sp<Layer> bgColorLayer;
215 
216         // The deque of callback handles for this frame. The back of the deque contains the most
217         // recent callback handle.
218         std::deque<sp<CallbackHandle>> callbackHandles;
219         bool colorSpaceAgnostic;
220     };
221 
222     explicit Layer(const LayerCreationArgs& args);
223     virtual ~Layer();
224 
setPrimaryDisplayOnly()225     void setPrimaryDisplayOnly() { mPrimaryDisplayOnly = true; }
getPrimaryDisplayOnly()226     bool getPrimaryDisplayOnly() const { return mPrimaryDisplayOnly; }
227 
228     // ------------------------------------------------------------------------
229     // Geometry setting functions.
230     //
231     // The following group of functions are used to specify the layers
232     // bounds, and the mapping of the texture on to those bounds. According
233     // to various settings changes to them may apply immediately, or be delayed until
234     // a pending resize is completed by the producer submitting a buffer. For example
235     // if we were to change the buffer size, and update the matrix ahead of the
236     // new buffer arriving, then we would be stretching the buffer to a different
237     // aspect before and after the buffer arriving, which probably isn't what we wanted.
238     //
239     // The first set of geometry functions are controlled by the scaling mode, described
240     // in window.h. The scaling mode may be set by the client, as it submits buffers.
241     // This value may be overriden through SurfaceControl, with setOverrideScalingMode.
242     //
243     // Put simply, if our scaling mode is SCALING_MODE_FREEZE, then
244     // matrix updates will not be applied while a resize is pending
245     // and the size and transform will remain in their previous state
246     // until a new buffer is submitted. If the scaling mode is another value
247     // then the old-buffer will immediately be scaled to the pending size
248     // and the new matrix will be immediately applied following this scaling
249     // transformation.
250 
251     // Set the default buffer size for the assosciated Producer, in pixels. This is
252     // also the rendered size of the layer prior to any transformations. Parent
253     // or local matrix transformations will not affect the size of the buffer,
254     // but may affect it's on-screen size or clipping.
255     virtual bool setSize(uint32_t w, uint32_t h);
256     // Set a 2x2 transformation matrix on the layer. This transform
257     // will be applied after parent transforms, but before any final
258     // producer specified transform.
259     virtual bool setMatrix(const layer_state_t::matrix22_t& matrix,
260                            bool allowNonRectPreservingTransforms);
261 
262     // This second set of geometry attributes are controlled by
263     // setGeometryAppliesWithResize, and their default mode is to be
264     // immediate. If setGeometryAppliesWithResize is specified
265     // while a resize is pending, then update of these attributes will
266     // be delayed until the resize completes.
267 
268     // setPosition operates in parent buffer space (pre parent-transform) or display
269     // space for top-level layers.
270     virtual bool setPosition(float x, float y, bool immediate);
271     // Buffer space
272     virtual bool setCrop_legacy(const Rect& crop, bool immediate);
273 
274     // TODO(b/38182121): Could we eliminate the various latching modes by
275     // using the layer hierarchy?
276     // -----------------------------------------------------------------------
277     virtual bool setLayer(int32_t z);
278     virtual bool setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ);
279 
280     virtual bool setAlpha(float alpha);
setColor(const half3 &)281     virtual bool setColor(const half3& /*color*/) { return false; };
282 
283     // Set rounded corner radius for this layer and its children.
284     //
285     // We only support 1 radius per layer in the hierarchy, where parent layers have precedence.
286     // The shape of the rounded corner rectangle is specified by the crop rectangle of the layer
287     // from which we inferred the rounded corner radius.
288     virtual bool setCornerRadius(float cornerRadius);
289     virtual bool setTransparentRegionHint(const Region& transparent);
290     virtual bool setFlags(uint8_t flags, uint8_t mask);
291     virtual bool setLayerStack(uint32_t layerStack);
292     virtual uint32_t getLayerStack() const;
293     virtual void deferTransactionUntil_legacy(const sp<IBinder>& barrierHandle,
294                                               uint64_t frameNumber);
295     virtual void deferTransactionUntil_legacy(const sp<Layer>& barrierLayer, uint64_t frameNumber);
296     virtual bool setOverrideScalingMode(int32_t overrideScalingMode);
297     virtual bool setMetadata(const LayerMetadata& data);
298     virtual bool reparentChildren(const sp<IBinder>& layer);
299     virtual void setChildrenDrawingParent(const sp<Layer>& layer);
300     virtual bool reparent(const sp<IBinder>& newParentHandle);
301     virtual bool detachChildren();
302     bool attachChildren();
isLayerDetached()303     bool isLayerDetached() const { return mLayerDetached; }
304     virtual bool setColorTransform(const mat4& matrix);
305     virtual mat4 getColorTransform() const;
306     virtual bool hasColorTransform() const;
isColorSpaceAgnostic()307     virtual bool isColorSpaceAgnostic() const { return mDrawingState.colorSpaceAgnostic; }
308 
309     // Used only to set BufferStateLayer state
setTransform(uint32_t)310     virtual bool setTransform(uint32_t /*transform*/) { return false; };
setTransformToDisplayInverse(bool)311     virtual bool setTransformToDisplayInverse(bool /*transformToDisplayInverse*/) { return false; };
setCrop(const Rect &)312     virtual bool setCrop(const Rect& /*crop*/) { return false; };
setFrame(const Rect &)313     virtual bool setFrame(const Rect& /*frame*/) { return false; };
setBuffer(const sp<GraphicBuffer> &,nsecs_t,nsecs_t,const client_cache_t &)314     virtual bool setBuffer(const sp<GraphicBuffer>& /*buffer*/, nsecs_t /*postTime*/,
315                            nsecs_t /*desiredPresentTime*/,
316                            const client_cache_t& /*clientCacheId*/) {
317         return false;
318     };
setAcquireFence(const sp<Fence> &)319     virtual bool setAcquireFence(const sp<Fence>& /*fence*/) { return false; };
setDataspace(ui::Dataspace)320     virtual bool setDataspace(ui::Dataspace /*dataspace*/) { return false; };
setHdrMetadata(const HdrMetadata &)321     virtual bool setHdrMetadata(const HdrMetadata& /*hdrMetadata*/) { return false; };
setSurfaceDamageRegion(const Region &)322     virtual bool setSurfaceDamageRegion(const Region& /*surfaceDamage*/) { return false; };
setApi(int32_t)323     virtual bool setApi(int32_t /*api*/) { return false; };
setSidebandStream(const sp<NativeHandle> &)324     virtual bool setSidebandStream(const sp<NativeHandle>& /*sidebandStream*/) { return false; };
setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>> &)325     virtual bool setTransactionCompletedListeners(
326             const std::vector<sp<CallbackHandle>>& /*handles*/) {
327         return false;
328     };
329     virtual bool setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace);
330     virtual bool setColorSpaceAgnostic(const bool agnostic);
331 
getDataSpace()332     ui::Dataspace getDataSpace() const { return mCurrentDataSpace; }
333 
334     // Before color management is introduced, contents on Android have to be
335     // desaturated in order to match what they appears like visually.
336     // With color management, these contents will appear desaturated, thus
337     // needed to be saturated so that they match what they are designed for
338     // visually.
339     bool isLegacyDataSpace() const;
340 
341     virtual std::shared_ptr<compositionengine::Layer> getCompositionLayer() const;
342 
343     // If we have received a new buffer this frame, we will pass its surface
344     // damage down to hardware composer. Otherwise, we must send a region with
345     // one empty rect.
useSurfaceDamage()346     virtual void useSurfaceDamage() {}
useEmptyDamage()347     virtual void useEmptyDamage() {}
348 
getTransactionFlags()349     uint32_t getTransactionFlags() const { return mTransactionFlags; }
350     uint32_t getTransactionFlags(uint32_t flags);
351     uint32_t setTransactionFlags(uint32_t flags);
352 
353     // Deprecated, please use compositionengine::Output::belongsInOutput()
354     // instead.
355     // TODO(lpique): Move the remaining callers (screencap) to the new function.
belongsToDisplay(uint32_t layerStack,bool isPrimaryDisplay)356     bool belongsToDisplay(uint32_t layerStack, bool isPrimaryDisplay) const {
357         return getLayerStack() == layerStack && (!mPrimaryDisplayOnly || isPrimaryDisplay);
358     }
359 
360     void computeGeometry(const RenderArea& renderArea, renderengine::Mesh& mesh,
361                          bool useIdentityTransform) const;
362     FloatRect getBounds(const Region& activeTransparentRegion) const;
363     FloatRect getBounds() const;
364 
365     // Compute bounds for the layer and cache the results.
366     void computeBounds(FloatRect parentBounds, ui::Transform parentTransform);
367 
368     // Returns the buffer scale transform if a scaling mode is set.
369     ui::Transform getBufferScaleTransform() const;
370 
371     // Get effective layer transform, taking into account all its parent transform with any
372     // scaling if the parent scaling more is not NATIVE_WINDOW_SCALING_MODE_FREEZE.
373     ui::Transform getTransformWithScale(const ui::Transform& bufferScaleTransform) const;
374 
375     // Returns the bounds of the layer without any buffer scaling.
376     FloatRect getBoundsPreScaling(const ui::Transform& bufferScaleTransform) const;
377 
getSequence()378     int32_t getSequence() const { return sequence; }
379 
380     // -----------------------------------------------------------------------
381     // Virtuals
382     virtual const char* getTypeId() const = 0;
383 
384     /*
385      * isOpaque - true if this surface is opaque
386      *
387      * This takes into account the buffer format (i.e. whether or not the
388      * pixel format includes an alpha channel) and the "opaque" flag set
389      * on the layer.  It does not examine the current plane alpha value.
390      */
isOpaque(const Layer::State &)391     virtual bool isOpaque(const Layer::State&) const { return false; }
392 
393     /*
394      * isSecure - true if this surface is secure, that is if it prevents
395      * screenshots or VNC servers.
396      */
397     bool isSecure() const;
398 
399     /*
400      * isVisible - true if this layer is visible, false otherwise
401      */
402     virtual bool isVisible() const = 0;
403 
404     /*
405      * isHiddenByPolicy - true if this layer has been forced invisible.
406      * just because this is false, doesn't mean isVisible() is true.
407      * For example if this layer has no active buffer, it may not be hidden by
408      * policy, but it still can not be visible.
409      */
410     bool isHiddenByPolicy() const;
411 
412     /*
413      * Returns whether this layer can receive input.
414      */
415     virtual bool canReceiveInput() const;
416 
417     /*
418      * isProtected - true if the layer may contain protected content in the
419      * GRALLOC_USAGE_PROTECTED sense.
420      */
isProtected()421     virtual bool isProtected() const { return false; }
422 
423     /*
424      * isFixedSize - true if content has a fixed size
425      */
isFixedSize()426     virtual bool isFixedSize() const { return true; }
427 
428     /*
429      * usesSourceCrop - true if content should use a source crop
430      */
usesSourceCrop()431     virtual bool usesSourceCrop() const { return false; }
432 
433     // Most layers aren't created from the main thread, and therefore need to
434     // grab the SF state lock to access HWC, but ContainerLayer does, so we need
435     // to avoid grabbing the lock again to avoid deadlock
isCreatedFromMainThread()436     virtual bool isCreatedFromMainThread() const { return false; }
437 
438     bool isRemovedFromCurrentState() const;
439 
440     // Write states that are modified by the main thread. This includes drawing
441     // state as well as buffer data. This should be called in the main or tracing
442     // thread.
443     void writeToProtoDrawingState(LayerProto* layerInfo,
444                                   uint32_t traceFlags = SurfaceTracing::TRACE_ALL) const;
445     // Write states that are modified by the main thread. This includes drawing
446     // state as well as buffer data and composition data for layers on the specified
447     // display. This should be called in the main or tracing thread.
448     void writeToProtoCompositionState(LayerProto* layerInfo, const sp<DisplayDevice>& displayDevice,
449                                       uint32_t traceFlags = SurfaceTracing::TRACE_ALL) const;
450     // Write drawing or current state. If writing current state, the caller should hold the
451     // external mStateLock. If writing drawing state, this function should be called on the
452     // main or tracing thread.
453     void writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
454                                  uint32_t traceFlags = SurfaceTracing::TRACE_ALL) const;
455 
getActiveGeometry(const Layer::State & s)456     virtual Geometry getActiveGeometry(const Layer::State& s) const { return s.active_legacy; }
getActiveWidth(const Layer::State & s)457     virtual uint32_t getActiveWidth(const Layer::State& s) const { return s.active_legacy.w; }
getActiveHeight(const Layer::State & s)458     virtual uint32_t getActiveHeight(const Layer::State& s) const { return s.active_legacy.h; }
getActiveTransform(const Layer::State & s)459     virtual ui::Transform getActiveTransform(const Layer::State& s) const {
460         return s.active_legacy.transform;
461     }
getActiveTransparentRegion(const Layer::State & s)462     virtual Region getActiveTransparentRegion(const Layer::State& s) const {
463         return s.activeTransparentRegion_legacy;
464     }
getCrop(const Layer::State & s)465     virtual Rect getCrop(const Layer::State& s) const { return s.crop_legacy; }
466 
467 protected:
468     virtual bool prepareClientLayer(const RenderArea& renderArea, const Region& clip,
469                                     bool useIdentityTransform, Region& clearRegion,
470                                     const bool supportProtectedContent,
471                                     renderengine::LayerSettings& layer);
472 
473 public:
474     /*
475      * compositionengine::LayerFE overrides
476      */
477     void latchCompositionState(compositionengine::LayerFECompositionState&,
478                                bool includeGeometry) const override;
479     void onLayerDisplayed(const sp<Fence>& releaseFence) override;
480     const char* getDebugName() const override;
481 
482 protected:
483     void latchGeometry(compositionengine::LayerFECompositionState& outState) const;
484 
485 public:
setDefaultBufferSize(uint32_t,uint32_t)486     virtual void setDefaultBufferSize(uint32_t /*w*/, uint32_t /*h*/) {}
487 
isHdrY410()488     virtual bool isHdrY410() const { return false; }
489 
490     void forceClientComposition(const sp<DisplayDevice>& display);
491     bool getForceClientComposition(const sp<DisplayDevice>& display);
492     virtual void setPerFrameData(const sp<const DisplayDevice>& display,
493                                  const ui::Transform& transform, const Rect& viewport,
494                                  int32_t supportedPerFrameMetadata,
495                                  const ui::Dataspace targetDataspace) = 0;
496 
497     // callIntoHwc exists so we can update our local state and call
498     // acceptDisplayChanges without unnecessarily updating the device's state
499     void setCompositionType(const sp<const DisplayDevice>& display,
500                             Hwc2::IComposerClient::Composition type);
501     Hwc2::IComposerClient::Composition getCompositionType(
502             const sp<const DisplayDevice>& display) const;
503     bool getClearClientTarget(const sp<const DisplayDevice>& display) const;
504     void updateCursorPosition(const sp<const DisplayDevice>& display);
505 
shouldPresentNow(nsecs_t)506     virtual bool shouldPresentNow(nsecs_t /*expectedPresentTime*/) const { return false; }
setTransformHint(uint32_t)507     virtual void setTransformHint(uint32_t /*orientation*/) const { }
508 
509     /*
510      * called before composition.
511      * returns true if the layer has pending updates.
512      */
513     virtual bool onPreComposition(nsecs_t refreshStartTime) = 0;
514 
515     /*
516      * called after composition.
517      * returns true if the layer latched a new buffer this frame.
518      */
onPostComposition(const std::optional<DisplayId> &,const std::shared_ptr<FenceTime> &,const std::shared_ptr<FenceTime> &,const CompositorTiming &)519     virtual bool onPostComposition(const std::optional<DisplayId>& /*displayId*/,
520                                    const std::shared_ptr<FenceTime>& /*glDoneFence*/,
521                                    const std::shared_ptr<FenceTime>& /*presentFence*/,
522                                    const CompositorTiming& /*compositorTiming*/) {
523         return false;
524     }
525 
526     // If a buffer was replaced this frame, release the former buffer
releasePendingBuffer(nsecs_t)527     virtual void releasePendingBuffer(nsecs_t /*dequeueReadyTime*/) { }
528 
529     /*
530      * prepareClientLayer - populates a renderengine::LayerSettings to passed to
531      * RenderEngine::drawLayers. Returns true if the layer can be used, and
532      * false otherwise.
533      */
534     bool prepareClientLayer(const RenderArea& renderArea, const Region& clip, Region& clearRegion,
535                             const bool supportProtectedContent, renderengine::LayerSettings& layer);
536     bool prepareClientLayer(const RenderArea& renderArea, bool useIdentityTransform,
537                             Region& clearRegion, const bool supportProtectedContent,
538                             renderengine::LayerSettings& layer);
539 
540     /*
541      * doTransaction - process the transaction. This is a good place to figure
542      * out which attributes of the surface have changed.
543      */
544     uint32_t doTransaction(uint32_t transactionFlags);
545 
546     /*
547      * setVisibleRegion - called to set the new visible region. This gives
548      * a chance to update the new visible region or record the fact it changed.
549      */
550     void setVisibleRegion(const Region& visibleRegion);
551 
552     /*
553      * setCoveredRegion - called when the covered region changes. The covered
554      * region corresponds to any area of the surface that is covered
555      * (transparently or not) by another surface.
556      */
557     void setCoveredRegion(const Region& coveredRegion);
558 
559     /*
560      * setVisibleNonTransparentRegion - called when the visible and
561      * non-transparent region changes.
562      */
563     void setVisibleNonTransparentRegion(const Region& visibleNonTransparentRegion);
564 
565     /*
566      * Clear the visible, covered, and non-transparent regions.
567      */
568     void clearVisibilityRegions();
569 
570     /*
571      * latchBuffer - called each time the screen is redrawn and returns whether
572      * the visible regions need to be recomputed (this is a fairly heavy
573      * operation, so this should be set only if needed). Typically this is used
574      * to figure out if the content or size of a surface has changed.
575      */
latchBuffer(bool &,nsecs_t)576     virtual bool latchBuffer(bool& /*recomputeVisibleRegions*/, nsecs_t /*latchTime*/) {
577         return {};
578     }
579 
isBufferLatched()580     virtual bool isBufferLatched() const { return false; }
581 
582     /*
583      * Remove relative z for the layer if its relative parent is not part of the
584      * provided layer tree.
585      */
586     void removeRelativeZ(const std::vector<Layer*>& layersInTree);
587 
588     /*
589      * Remove from current state and mark for removal.
590      */
591     void removeFromCurrentState();
592 
593     /*
594      * called with the state lock from a binder thread when the layer is
595      * removed from the current list to the pending removal list
596      */
597     void onRemovedFromCurrentState();
598 
599     /*
600      * Called when the layer is added back to the current state list.
601      */
602     void addToCurrentState();
603 
604     // Updates the transform hint in our SurfaceFlingerConsumer to match
605     // the current orientation of the display device.
606     void updateTransformHint(const sp<const DisplayDevice>& display) const;
607 
608     /*
609      * returns the rectangle that crops the content of the layer and scales it
610      * to the layer's size.
611      */
612     Rect getContentCrop() const;
613 
614     /*
615      * Returns if a frame is ready
616      */
hasReadyFrame()617     virtual bool hasReadyFrame() const { return false; }
618 
getQueuedFrameCount()619     virtual int32_t getQueuedFrameCount() const { return 0; }
620 
621     // -----------------------------------------------------------------------
622 
623     bool hasHwcLayer(const sp<const DisplayDevice>& displayDevice);
624     HWC2::Layer* getHwcLayer(const sp<const DisplayDevice>& displayDevice);
625 
getDrawingState()626     inline const State& getDrawingState() const { return mDrawingState; }
getCurrentState()627     inline const State& getCurrentState() const { return mCurrentState; }
getCurrentState()628     inline State& getCurrentState() { return mCurrentState; }
629 
630     LayerDebugInfo getLayerDebugInfo() const;
631 
632     /* always call base class first */
633     static void miniDumpHeader(std::string& result);
634     void miniDump(std::string& result, const sp<DisplayDevice>& display) const;
635     void dumpFrameStats(std::string& result) const;
636     void dumpFrameEvents(std::string& result);
637     void clearFrameStats();
638     void logFrameStats();
639     void getFrameStats(FrameStats* outStats) const;
640 
getOccupancyHistory(bool)641     virtual std::vector<OccupancyTracker::Segment> getOccupancyHistory(bool /*forceFlush*/) {
642         return {};
643     }
644 
645     void onDisconnect();
646     void addAndGetFrameTimestamps(const NewFrameEventsEntry* newEntry,
647                                   FrameEventHistoryDelta* outDelta);
648 
getTransformToDisplayInverse()649     virtual bool getTransformToDisplayInverse() const { return false; }
650 
651     ui::Transform getTransform() const;
652 
653     // Returns the Alpha of the Surface, accounting for the Alpha
654     // of parent Surfaces in the hierarchy (alpha's will be multiplied
655     // down the hierarchy).
656     half getAlpha() const;
657     half4 getColor() const;
658 
659     // Returns how rounded corners should be drawn for this layer.
660     // This will traverse the hierarchy until it reaches its root, finding topmost rounded
661     // corner definition and converting it into current layer's coordinates.
662     // As of now, only 1 corner radius per display list is supported. Subsequent ones will be
663     // ignored.
664     RoundedCornerState getRoundedCornerState() const;
665 
666     void traverseInReverseZOrder(LayerVector::StateSet stateSet,
667                                  const LayerVector::Visitor& visitor);
668     void traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor);
669 
670     /**
671      * Traverse only children in z order, ignoring relative layers that are not children of the
672      * parent.
673      */
674     void traverseChildrenInZOrder(LayerVector::StateSet stateSet,
675                                   const LayerVector::Visitor& visitor);
676 
677     size_t getChildrenCount() const;
678     void addChild(const sp<Layer>& layer);
679     // Returns index if removed, or negative value otherwise
680     // for symmetry with Vector::remove
681     ssize_t removeChild(const sp<Layer>& layer);
getParent()682     sp<Layer> getParent() const { return mCurrentParent.promote(); }
hasParent()683     bool hasParent() const { return getParent() != nullptr; }
684     Rect getScreenBounds(bool reduceTransparentRegion = true) const;
685     bool setChildLayer(const sp<Layer>& childLayer, int32_t z);
686     bool setChildRelativeLayer(const sp<Layer>& childLayer,
687             const sp<IBinder>& relativeToHandle, int32_t relativeZ);
688 
689     // Copy the current list of children to the drawing state. Called by
690     // SurfaceFlinger to complete a transaction.
691     void commitChildList();
692     int32_t getZ() const;
693     virtual void pushPendingState();
694 
695     /**
696      * Returns active buffer size in the correct orientation. Buffer size is determined by undoing
697      * any buffer transformations. If the layer has no buffer then return INVALID_RECT.
698      */
getBufferSize(const Layer::State &)699     virtual Rect getBufferSize(const Layer::State&) const { return Rect::INVALID_RECT; }
700 
701     /**
702      * Returns the source bounds. If the bounds are not defined, it is inferred from the
703      * buffer size. Failing that, the bounds are determined from the passed in parent bounds.
704      * For the root layer, this is the display viewport size.
705      */
computeSourceBounds(const FloatRect & parentBounds)706     virtual FloatRect computeSourceBounds(const FloatRect& parentBounds) const {
707         return parentBounds;
708     }
709 
710     compositionengine::OutputLayer* findOutputLayerForDisplay(
711             const sp<const DisplayDevice>& display) const;
712 
713 protected:
714     // constant
715     sp<SurfaceFlinger> mFlinger;
716     /*
717      * Trivial class, used to ensure that mFlinger->onLayerDestroyed(mLayer)
718      * is called.
719      */
720     class LayerCleaner {
721         sp<SurfaceFlinger> mFlinger;
722         sp<Layer> mLayer;
723 
724     protected:
~LayerCleaner()725         ~LayerCleaner() {
726             // destroy client resources
727             mFlinger->onHandleDestroyed(mLayer);
728         }
729 
730     public:
LayerCleaner(const sp<SurfaceFlinger> & flinger,const sp<Layer> & layer)731         LayerCleaner(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
732               : mFlinger(flinger), mLayer(layer) {}
733     };
734 
735     friend class impl::SurfaceInterceptor;
736 
737     // For unit tests
738     friend class TestableSurfaceFlinger;
739 
740     virtual void commitTransaction(const State& stateToCommit);
741 
742     uint32_t getEffectiveUsage(uint32_t usage) const;
743 
744     /**
745      * Setup rounded corners coordinates of this layer, taking into account the layer bounds and
746      * crop coordinates, transforming them into layer space.
747      */
748     void setupRoundedCornersCropCoordinates(Rect win, const FloatRect& roundedCornersCrop) const;
749     void setParent(const sp<Layer>& layer);
750     LayerVector makeTraversalList(LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers);
751     void addZOrderRelative(const wp<Layer>& relative);
752     void removeZOrderRelative(const wp<Layer>& relative);
753 
754     class SyncPoint {
755     public:
SyncPoint(uint64_t frameNumber,wp<Layer> requestedSyncLayer)756         explicit SyncPoint(uint64_t frameNumber, wp<Layer> requestedSyncLayer)
757               : mFrameNumber(frameNumber),
758                 mFrameIsAvailable(false),
759                 mTransactionIsApplied(false),
760                 mRequestedSyncLayer(requestedSyncLayer) {}
761 
getFrameNumber()762         uint64_t getFrameNumber() const { return mFrameNumber; }
763 
frameIsAvailable()764         bool frameIsAvailable() const { return mFrameIsAvailable; }
765 
setFrameAvailable()766         void setFrameAvailable() { mFrameIsAvailable = true; }
767 
transactionIsApplied()768         bool transactionIsApplied() const { return mTransactionIsApplied; }
769 
setTransactionApplied()770         void setTransactionApplied() { mTransactionIsApplied = true; }
771 
getRequestedSyncLayer()772         sp<Layer> getRequestedSyncLayer() { return mRequestedSyncLayer.promote(); }
773 
774     private:
775         const uint64_t mFrameNumber;
776         std::atomic<bool> mFrameIsAvailable;
777         std::atomic<bool> mTransactionIsApplied;
778         wp<Layer> mRequestedSyncLayer;
779     };
780 
781     // SyncPoints which will be signaled when the correct frame is at the head
782     // of the queue and dropped after the frame has been latched. Protected by
783     // mLocalSyncPointMutex.
784     Mutex mLocalSyncPointMutex;
785     std::list<std::shared_ptr<SyncPoint>> mLocalSyncPoints;
786 
787     // SyncPoints which will be signaled and then dropped when the transaction
788     // is applied
789     std::list<std::shared_ptr<SyncPoint>> mRemoteSyncPoints;
790 
791     // Returns false if the relevant frame has already been latched
792     bool addSyncPoint(const std::shared_ptr<SyncPoint>& point);
793 
794     void popPendingState(State* stateToCommit);
795     virtual bool applyPendingStates(State* stateToCommit);
796     virtual uint32_t doTransactionResize(uint32_t flags, Layer::State* stateToCommit);
797 
798     // Returns mCurrentScaling mode (originating from the
799     // Client) or mOverrideScalingMode mode (originating from
800     // the Surface Controller) if set.
getEffectiveScalingMode()801     virtual uint32_t getEffectiveScalingMode() const { return 0; }
802 
803 public:
804     /*
805      * The layer handle is just a BBinder object passed to the client
806      * (remote process) -- we don't keep any reference on our side such that
807      * the dtor is called when the remote side let go of its reference.
808      *
809      * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
810      * this layer when the handle is destroyed.
811      */
812     class Handle : public BBinder, public LayerCleaner {
813     public:
Handle(const sp<SurfaceFlinger> & flinger,const sp<Layer> & layer)814         Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
815               : LayerCleaner(flinger, layer), owner(layer) {}
816 
817         wp<Layer> owner;
818     };
819 
820     // Creates a new handle each time, so we only expect
821     // this to be called once.
822     sp<IBinder> getHandle();
823     const String8& getName() const;
notifyAvailableFrames()824     virtual void notifyAvailableFrames() {}
getPixelFormat()825     virtual PixelFormat getPixelFormat() const { return PIXEL_FORMAT_NONE; }
826     bool getPremultipledAlpha() const;
827 
828     bool mPendingHWCDestroy{false};
829     void setInputInfo(const InputWindowInfo& info);
830 
831     InputWindowInfo fillInputInfo();
832     bool hasInput() const;
833 
834 protected:
835     // -----------------------------------------------------------------------
836     bool usingRelativeZ(LayerVector::StateSet stateSet) const;
837 
838     bool mPremultipliedAlpha{true};
839     String8 mName;
840     String8 mTransactionName; // A cached version of "TX - " + mName for systraces
841 
842     bool mPrimaryDisplayOnly = false;
843 
844     // These are only accessed by the main thread or the tracing thread.
845     State mDrawingState;
846     // Store a copy of the pending state so that the drawing thread can access the
847     // states without a lock.
848     Vector<State> mPendingStatesSnapshot;
849 
850     // these are protected by an external lock (mStateLock)
851     State mCurrentState;
852     std::atomic<uint32_t> mTransactionFlags{0};
853     Vector<State> mPendingStates;
854 
855     // Timestamp history for UIAutomation. Thread safe.
856     FrameTracker mFrameTracker;
857 
858     // Timestamp history for the consumer to query.
859     // Accessed by both consumer and producer on main and binder threads.
860     Mutex mFrameEventHistoryMutex;
861     ConsumerFrameEventHistory mFrameEventHistory;
862     FenceTimeline mAcquireTimeline;
863     FenceTimeline mReleaseTimeline;
864 
865     // main thread
866     sp<NativeHandle> mSidebandStream;
867     // Active buffer fields
868     sp<GraphicBuffer> mActiveBuffer;
869     sp<Fence> mActiveBufferFence;
870     // False if the buffer and its contents have been previously used for GPU
871     // composition, true otherwise.
872     bool mIsActiveBufferUpdatedForGpu = true;
873 
874     ui::Dataspace mCurrentDataSpace = ui::Dataspace::UNKNOWN;
875     Rect mCurrentCrop;
876     uint32_t mCurrentTransform{0};
877     // We encode unset as -1.
878     int32_t mOverrideScalingMode{-1};
879     std::atomic<uint64_t> mCurrentFrameNumber{0};
880     bool mFrameLatencyNeeded{false};
881     // Whether filtering is needed b/c of the drawingstate
882     bool mNeedsFiltering{false};
883 
884     std::atomic<bool> mRemovedFromCurrentState{false};
885 
886     // page-flip thread (currently main thread)
887     bool mProtectedByApp{false}; // application requires protected path to external sink
888 
889     // protected by mLock
890     mutable Mutex mLock;
891 
892     const wp<Client> mClientRef;
893 
894     // This layer can be a cursor on some displays.
895     bool mPotentialCursor{false};
896 
897     bool mFreezeGeometryUpdates{false};
898 
899     // Child list about to be committed/used for editing.
900     LayerVector mCurrentChildren{LayerVector::StateSet::Current};
901     // Child list used for rendering.
902     LayerVector mDrawingChildren{LayerVector::StateSet::Drawing};
903 
904     wp<Layer> mCurrentParent;
905     wp<Layer> mDrawingParent;
906 
907     // Can only be accessed with the SF state lock held.
908     bool mLayerDetached{false};
909     // Can only be accessed with the SF state lock held.
910     bool mChildrenChanged{false};
911 
912     // Window types from WindowManager.LayoutParams
913     const int mWindowType;
914 
915     // This is populated if the layer is registered with Scheduler for tracking purposes.
916     std::unique_ptr<scheduler::LayerHistory::LayerHandle> mSchedulerLayerHandle;
917 
918 private:
919     /**
920      * Returns an unsorted vector of all layers that are part of this tree.
921      * That includes the current layer and all its descendants.
922      */
923     std::vector<Layer*> getLayersInTree(LayerVector::StateSet stateSet);
924     /**
925      * Traverses layers that are part of this tree in the correct z order.
926      * layersInTree must be sorted before calling this method.
927      */
928     void traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
929                                        LayerVector::StateSet stateSet,
930                                        const LayerVector::Visitor& visitor);
931     LayerVector makeChildrenTraversalList(LayerVector::StateSet stateSet,
932                                           const std::vector<Layer*>& layersInTree);
933     /**
934      * Returns the cropped buffer size or the layer crop if the layer has no buffer. Return
935      * INVALID_RECT if the layer has no buffer and no crop.
936      * A layer with an invalid buffer size and no crop is considered to be boundless. The layer
937      * bounds are constrained by its parent bounds.
938      */
939     Rect getCroppedBufferSize(const Layer::State& s) const;
940 
941     // Cached properties computed from drawing state
942     // Effective transform taking into account parent transforms and any parent scaling.
943     ui::Transform mEffectiveTransform;
944 
945     // Bounds of the layer before any transformation is applied and before it has been cropped
946     // by its parents.
947     FloatRect mSourceBounds;
948 
949     // Bounds of the layer in layer space. This is the mSourceBounds cropped by its layer crop and
950     // its parent bounds.
951     FloatRect mBounds;
952 
953     // Layer bounds in screen space.
954     FloatRect mScreenBounds;
955 
956     void setZOrderRelativeOf(const wp<Layer>& relativeOf);
957 
958     bool mGetHandleCalled = false;
959 
960     void removeRemoteSyncPoints();
961 };
962 
963 } // namespace android
964 
965 #define RETURN_IF_NO_HWC_LAYER(displayDevice, ...)                                     \
966     do {                                                                               \
967         if (!hasHwcLayer(displayDevice)) {                                             \
968             ALOGE("[%s] %s failed: no HWC layer found for display %s", mName.string(), \
969                   __FUNCTION__, displayDevice->getDebugName().c_str());                \
970             return __VA_ARGS__;                                                        \
971         }                                                                              \
972     } while (false)
973 
974 #endif // ANDROID_LAYER_H
975