Home | History | Annotate | Download | only in surfaceflinger
      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 <sys/types.h>
     21 
     22 #include <utils/RefBase.h>
     23 #include <utils/String8.h>
     24 #include <utils/Timers.h>
     25 
     26 #include <ui/FloatRect.h>
     27 #include <ui/FrameStats.h>
     28 #include <ui/GraphicBuffer.h>
     29 #include <ui/PixelFormat.h>
     30 #include <ui/Region.h>
     31 
     32 #include <gui/ISurfaceComposerClient.h>
     33 #include <gui/LayerState.h>
     34 #include <gui/BufferQueue.h>
     35 
     36 #include <list>
     37 #include <cstdint>
     38 
     39 #include "Client.h"
     40 #include "FrameTracker.h"
     41 #include "LayerVector.h"
     42 #include "MonitoredProducer.h"
     43 #include "SurfaceFlinger.h"
     44 #include "TimeStats/TimeStats.h"
     45 #include "Transform.h"
     46 
     47 #include <layerproto/LayerProtoHeader.h>
     48 #include "DisplayHardware/HWComposer.h"
     49 #include "DisplayHardware/HWComposerBufferCache.h"
     50 #include "RenderArea.h"
     51 #include "RenderEngine/Mesh.h"
     52 #include "RenderEngine/Texture.h"
     53 
     54 #include <math/vec4.h>
     55 #include <vector>
     56 
     57 using namespace android::surfaceflinger;
     58 
     59 namespace android {
     60 
     61 // ---------------------------------------------------------------------------
     62 
     63 class Client;
     64 class Colorizer;
     65 class DisplayDevice;
     66 class GraphicBuffer;
     67 class SurfaceFlinger;
     68 class LayerDebugInfo;
     69 class LayerBE;
     70 
     71 namespace impl {
     72 class SurfaceInterceptor;
     73 }
     74 
     75 // ---------------------------------------------------------------------------
     76 
     77 struct CompositionInfo {
     78     HWC2::Composition compositionType;
     79     sp<GraphicBuffer> mBuffer = nullptr;
     80     int mBufferSlot = BufferQueue::INVALID_BUFFER_SLOT;
     81     struct {
     82         HWComposer* hwc;
     83         sp<Fence> fence;
     84         HWC2::BlendMode blendMode;
     85         Rect displayFrame;
     86         float alpha;
     87         FloatRect sourceCrop;
     88         HWC2::Transform transform;
     89         int z;
     90         int type;
     91         int appId;
     92         Region visibleRegion;
     93         Region surfaceDamage;
     94         sp<NativeHandle> sidebandStream;
     95         android_dataspace dataspace;
     96         hwc_color_t color;
     97     } hwc;
     98     struct {
     99         RE::RenderEngine* renderEngine;
    100         Mesh* mesh;
    101     } renderEngine;
    102 };
    103 
    104 class LayerBE {
    105 public:
    106     LayerBE();
    107 
    108     // The mesh used to draw the layer in GLES composition mode
    109     Mesh mMesh;
    110 
    111     // HWC items, accessed from the main thread
    112     struct HWCInfo {
    113         HWCInfo()
    114               : hwc(nullptr),
    115                 layer(nullptr),
    116                 forceClientComposition(false),
    117                 compositionType(HWC2::Composition::Invalid),
    118                 clearClientTarget(false),
    119                 transform(HWC2::Transform::None) {}
    120 
    121         HWComposer* hwc;
    122         HWC2::Layer* layer;
    123         bool forceClientComposition;
    124         HWC2::Composition compositionType;
    125         bool clearClientTarget;
    126         Rect displayFrame;
    127         FloatRect sourceCrop;
    128         HWComposerBufferCache bufferCache;
    129         HWC2::Transform transform;
    130     };
    131 
    132     // A layer can be attached to multiple displays when operating in mirror mode
    133     // (a.k.a: when several displays are attached with equal layerStack). In this
    134     // case we need to keep track. In non-mirror mode, a layer will have only one
    135     // HWCInfo. This map key is a display layerStack.
    136     std::unordered_map<int32_t, HWCInfo> mHwcLayers;
    137 
    138     CompositionInfo compositionInfo;
    139 };
    140 
    141 class Layer : public virtual RefBase {
    142     static int32_t sSequence;
    143 
    144 public:
    145     LayerBE& getBE() { return mBE; }
    146     LayerBE& getBE() const { return mBE; }
    147     mutable bool contentDirty;
    148     // regions below are in window-manager space
    149     Region visibleRegion;
    150     Region coveredRegion;
    151     Region visibleNonTransparentRegion;
    152     Region surfaceDamageRegion;
    153 
    154     // Layer serial number.  This gives layers an explicit ordering, so we
    155     // have a stable sort order when their layer stack and Z-order are
    156     // the same.
    157     int32_t sequence;
    158 
    159     enum { // flags for doTransaction()
    160         eDontUpdateGeometryState = 0x00000001,
    161         eVisibleRegion = 0x00000002,
    162     };
    163 
    164     struct Geometry {
    165         uint32_t w;
    166         uint32_t h;
    167         Transform transform;
    168 
    169         inline bool operator==(const Geometry& rhs) const {
    170             return (w == rhs.w && h == rhs.h) && (transform.tx() == rhs.transform.tx()) &&
    171                     (transform.ty() == rhs.transform.ty());
    172         }
    173         inline bool operator!=(const Geometry& rhs) const { return !operator==(rhs); }
    174     };
    175 
    176     struct State {
    177         Geometry active;
    178         Geometry requested;
    179         int32_t z;
    180 
    181         // The identifier of the layer stack this layer belongs to. A layer can
    182         // only be associated to a single layer stack. A layer stack is a
    183         // z-ordered group of layers which can be associated to one or more
    184         // displays. Using the same layer stack on different displays is a way
    185         // to achieve mirroring.
    186         uint32_t layerStack;
    187 
    188         uint8_t flags;
    189         uint8_t reserved[2];
    190         int32_t sequence; // changes when visible regions can change
    191         bool modified;
    192 
    193         // Crop is expressed in layer space coordinate.
    194         Rect crop;
    195         Rect requestedCrop;
    196 
    197         // finalCrop is expressed in display space coordinate.
    198         Rect finalCrop;
    199         Rect requestedFinalCrop;
    200 
    201         // If set, defers this state update until the identified Layer
    202         // receives a frame with the given frameNumber
    203         wp<Layer> barrierLayer;
    204         uint64_t frameNumber;
    205 
    206         // the transparentRegion hint is a bit special, it's latched only
    207         // when we receive a buffer -- this is because it's "content"
    208         // dependent.
    209         Region activeTransparentRegion;
    210         Region requestedTransparentRegion;
    211 
    212         int32_t appId;
    213         int32_t type;
    214 
    215         // If non-null, a Surface this Surface's Z-order is interpreted relative to.
    216         wp<Layer> zOrderRelativeOf;
    217 
    218         // A list of surfaces whose Z-order is interpreted relative to ours.
    219         SortedVector<wp<Layer>> zOrderRelatives;
    220 
    221         half4 color;
    222     };
    223 
    224     Layer(SurfaceFlinger* flinger, const sp<Client>& client, const String8& name, uint32_t w,
    225           uint32_t h, uint32_t flags);
    226     virtual ~Layer();
    227 
    228     void setPrimaryDisplayOnly() { mPrimaryDisplayOnly = true; }
    229 
    230     // ------------------------------------------------------------------------
    231     // Geometry setting functions.
    232     //
    233     // The following group of functions are used to specify the layers
    234     // bounds, and the mapping of the texture on to those bounds. According
    235     // to various settings changes to them may apply immediately, or be delayed until
    236     // a pending resize is completed by the producer submitting a buffer. For example
    237     // if we were to change the buffer size, and update the matrix ahead of the
    238     // new buffer arriving, then we would be stretching the buffer to a different
    239     // aspect before and after the buffer arriving, which probably isn't what we wanted.
    240     //
    241     // The first set of geometry functions are controlled by the scaling mode, described
    242     // in window.h. The scaling mode may be set by the client, as it submits buffers.
    243     // This value may be overriden through SurfaceControl, with setOverrideScalingMode.
    244     //
    245     // Put simply, if our scaling mode is SCALING_MODE_FREEZE, then
    246     // matrix updates will not be applied while a resize is pending
    247     // and the size and transform will remain in their previous state
    248     // until a new buffer is submitted. If the scaling mode is another value
    249     // then the old-buffer will immediately be scaled to the pending size
    250     // and the new matrix will be immediately applied following this scaling
    251     // transformation.
    252 
    253     // Set the default buffer size for the assosciated Producer, in pixels. This is
    254     // also the rendered size of the layer prior to any transformations. Parent
    255     // or local matrix transformations will not affect the size of the buffer,
    256     // but may affect it's on-screen size or clipping.
    257     bool setSize(uint32_t w, uint32_t h);
    258     // Set a 2x2 transformation matrix on the layer. This transform
    259     // will be applied after parent transforms, but before any final
    260     // producer specified transform.
    261     bool setMatrix(const layer_state_t::matrix22_t& matrix);
    262 
    263     // This second set of geometry attributes are controlled by
    264     // setGeometryAppliesWithResize, and their default mode is to be
    265     // immediate. If setGeometryAppliesWithResize is specified
    266     // while a resize is pending, then update of these attributes will
    267     // be delayed until the resize completes.
    268 
    269     // setPosition operates in parent buffer space (pre parent-transform) or display
    270     // space for top-level layers.
    271     bool setPosition(float x, float y, bool immediate);
    272     // Buffer space
    273     bool setCrop(const Rect& crop, bool immediate);
    274     // Parent buffer space/display space
    275     bool setFinalCrop(const Rect& crop, bool immediate);
    276 
    277     // TODO(b/38182121): Could we eliminate the various latching modes by
    278     // using the layer hierarchy?
    279     // -----------------------------------------------------------------------
    280     bool setLayer(int32_t z);
    281     bool setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ);
    282 
    283     bool setAlpha(float alpha);
    284     bool setColor(const half3& color);
    285     bool setTransparentRegionHint(const Region& transparent);
    286     bool setFlags(uint8_t flags, uint8_t mask);
    287     bool setLayerStack(uint32_t layerStack);
    288     uint32_t getLayerStack() const;
    289     void deferTransactionUntil(const sp<IBinder>& barrierHandle, uint64_t frameNumber);
    290     void deferTransactionUntil(const sp<Layer>& barrierLayer, uint64_t frameNumber);
    291     bool setOverrideScalingMode(int32_t overrideScalingMode);
    292     void setInfo(int32_t type, int32_t appId);
    293     bool reparentChildren(const sp<IBinder>& layer);
    294     void setChildrenDrawingParent(const sp<Layer>& layer);
    295     bool reparent(const sp<IBinder>& newParentHandle);
    296     bool detachChildren();
    297 
    298     ui::Dataspace getDataSpace() const { return mCurrentDataSpace; }
    299 
    300     // Before color management is introduced, contents on Android have to be
    301     // desaturated in order to match what they appears like visually.
    302     // With color management, these contents will appear desaturated, thus
    303     // needed to be saturated so that they match what they are designed for
    304     // visually.
    305     bool isLegacyDataSpace() const;
    306 
    307     // If we have received a new buffer this frame, we will pass its surface
    308     // damage down to hardware composer. Otherwise, we must send a region with
    309     // one empty rect.
    310     virtual void useSurfaceDamage() {}
    311     virtual void useEmptyDamage() {}
    312 
    313     uint32_t getTransactionFlags(uint32_t flags);
    314     uint32_t setTransactionFlags(uint32_t flags);
    315 
    316     bool belongsToDisplay(uint32_t layerStack, bool isPrimaryDisplay) const {
    317         return getLayerStack() == layerStack && (!mPrimaryDisplayOnly || isPrimaryDisplay);
    318     }
    319 
    320     void computeGeometry(const RenderArea& renderArea, Mesh& mesh, bool useIdentityTransform) const;
    321     FloatRect computeBounds(const Region& activeTransparentRegion) const;
    322     FloatRect computeBounds() const;
    323 
    324     int32_t getSequence() const { return sequence; }
    325 
    326     // -----------------------------------------------------------------------
    327     // Virtuals
    328     virtual const char* getTypeId() const = 0;
    329 
    330     /*
    331      * isOpaque - true if this surface is opaque
    332      *
    333      * This takes into account the buffer format (i.e. whether or not the
    334      * pixel format includes an alpha channel) and the "opaque" flag set
    335      * on the layer.  It does not examine the current plane alpha value.
    336      */
    337     virtual bool isOpaque(const Layer::State&) const { return false; }
    338 
    339     /*
    340      * isSecure - true if this surface is secure, that is if it prevents
    341      * screenshots or VNC servers.
    342      */
    343     bool isSecure() const;
    344 
    345     /*
    346      * isVisible - true if this layer is visible, false otherwise
    347      */
    348     virtual bool isVisible() const = 0;
    349 
    350     /*
    351      * isHiddenByPolicy - true if this layer has been forced invisible.
    352      * just because this is false, doesn't mean isVisible() is true.
    353      * For example if this layer has no active buffer, it may not be hidden by
    354      * policy, but it still can not be visible.
    355      */
    356     bool isHiddenByPolicy() const;
    357 
    358     /*
    359      * isFixedSize - true if content has a fixed size
    360      */
    361     virtual bool isFixedSize() const { return true; }
    362 
    363 
    364     bool isPendingRemoval() const { return mPendingRemoval; }
    365 
    366     void writeToProto(LayerProto* layerInfo,
    367                       LayerVector::StateSet stateSet = LayerVector::StateSet::Drawing);
    368 
    369     void writeToProto(LayerProto* layerInfo, int32_t hwcId);
    370 
    371 protected:
    372     /*
    373      * onDraw - draws the surface.
    374      */
    375     virtual void onDraw(const RenderArea& renderArea, const Region& clip,
    376                         bool useIdentityTransform) const = 0;
    377 
    378 public:
    379     virtual void setDefaultBufferSize(uint32_t /*w*/, uint32_t /*h*/) {}
    380 
    381     virtual bool isHdrY410() const { return false; }
    382 
    383     void setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z);
    384     void forceClientComposition(int32_t hwcId);
    385     bool getForceClientComposition(int32_t hwcId);
    386     virtual void setPerFrameData(const sp<const DisplayDevice>& displayDevice) = 0;
    387 
    388     // callIntoHwc exists so we can update our local state and call
    389     // acceptDisplayChanges without unnecessarily updating the device's state
    390     void setCompositionType(int32_t hwcId, HWC2::Composition type, bool callIntoHwc = true);
    391     HWC2::Composition getCompositionType(int32_t hwcId) const;
    392     void setClearClientTarget(int32_t hwcId, bool clear);
    393     bool getClearClientTarget(int32_t hwcId) const;
    394     void updateCursorPosition(const sp<const DisplayDevice>& hw);
    395 
    396     /*
    397      * called after page-flip
    398      */
    399     virtual void onLayerDisplayed(const sp<Fence>& releaseFence);
    400 
    401     virtual void abandon() {}
    402 
    403     virtual bool shouldPresentNow(const DispSync& /*dispSync*/) const { return false; }
    404     virtual void setTransformHint(uint32_t /*orientation*/) const { }
    405 
    406     /*
    407      * called before composition.
    408      * returns true if the layer has pending updates.
    409      */
    410     virtual bool onPreComposition(nsecs_t /*refreshStartTime*/) { return true; }
    411 
    412     /*
    413      * called after composition.
    414      * returns true if the layer latched a new buffer this frame.
    415      */
    416     virtual bool onPostComposition(const std::shared_ptr<FenceTime>& /*glDoneFence*/,
    417                                    const std::shared_ptr<FenceTime>& /*presentFence*/,
    418                                    const CompositorTiming& /*compositorTiming*/) {
    419         return false;
    420     }
    421 
    422     // If a buffer was replaced this frame, release the former buffer
    423     virtual void releasePendingBuffer(nsecs_t /*dequeueReadyTime*/) { }
    424 
    425 
    426     /*
    427      * draw - performs some global clipping optimizations
    428      * and calls onDraw().
    429      */
    430     void draw(const RenderArea& renderArea, const Region& clip) const;
    431     void draw(const RenderArea& renderArea, bool useIdentityTransform) const;
    432     void draw(const RenderArea& renderArea) const;
    433 
    434     /*
    435      * doTransaction - process the transaction. This is a good place to figure
    436      * out which attributes of the surface have changed.
    437      */
    438     uint32_t doTransaction(uint32_t transactionFlags);
    439 
    440     /*
    441      * setVisibleRegion - called to set the new visible region. This gives
    442      * a chance to update the new visible region or record the fact it changed.
    443      */
    444     void setVisibleRegion(const Region& visibleRegion);
    445 
    446     /*
    447      * setCoveredRegion - called when the covered region changes. The covered
    448      * region corresponds to any area of the surface that is covered
    449      * (transparently or not) by another surface.
    450      */
    451     void setCoveredRegion(const Region& coveredRegion);
    452 
    453     /*
    454      * setVisibleNonTransparentRegion - called when the visible and
    455      * non-transparent region changes.
    456      */
    457     void setVisibleNonTransparentRegion(const Region& visibleNonTransparentRegion);
    458 
    459     /*
    460      * Clear the visible, covered, and non-transparent regions.
    461      */
    462     void clearVisibilityRegions();
    463 
    464     /*
    465      * latchBuffer - called each time the screen is redrawn and returns whether
    466      * the visible regions need to be recomputed (this is a fairly heavy
    467      * operation, so this should be set only if needed). Typically this is used
    468      * to figure out if the content or size of a surface has changed.
    469      */
    470     virtual Region latchBuffer(bool& /*recomputeVisibleRegions*/, nsecs_t /*latchTime*/) {
    471         return {};
    472     }
    473 
    474     virtual bool isBufferLatched() const { return false; }
    475 
    476     bool isPotentialCursor() const { return mPotentialCursor; }
    477     /*
    478      * called with the state lock from a binder thread when the layer is
    479      * removed from the current list to the pending removal list
    480      */
    481     void onRemovedFromCurrentState();
    482 
    483     /*
    484      * called with the state lock from the main thread when the layer is
    485      * removed from the pending removal list
    486      */
    487     void onRemoved();
    488 
    489     // Updates the transform hint in our SurfaceFlingerConsumer to match
    490     // the current orientation of the display device.
    491     void updateTransformHint(const sp<const DisplayDevice>& hw) const;
    492 
    493     /*
    494      * returns the rectangle that crops the content of the layer and scales it
    495      * to the layer's size.
    496      */
    497     Rect getContentCrop() const;
    498 
    499     /*
    500      * Returns if a frame is queued.
    501      */
    502     bool hasQueuedFrame() const {
    503         return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
    504     }
    505 
    506     int32_t getQueuedFrameCount() const { return mQueuedFrames; }
    507 
    508     // -----------------------------------------------------------------------
    509 
    510     bool createHwcLayer(HWComposer* hwc, int32_t hwcId);
    511     bool destroyHwcLayer(int32_t hwcId);
    512     void destroyAllHwcLayers();
    513 
    514     bool hasHwcLayer(int32_t hwcId) {
    515         return getBE().mHwcLayers.count(hwcId) > 0;
    516     }
    517 
    518     HWC2::Layer* getHwcLayer(int32_t hwcId) {
    519         if (getBE().mHwcLayers.count(hwcId) == 0) {
    520             return nullptr;
    521         }
    522         return getBE().mHwcLayers[hwcId].layer;
    523     }
    524 
    525     // -----------------------------------------------------------------------
    526 
    527     void clearWithOpenGL(const RenderArea& renderArea) const;
    528     void setFiltering(bool filtering);
    529     bool getFiltering() const;
    530 
    531 
    532     inline const State& getDrawingState() const { return mDrawingState; }
    533     inline const State& getCurrentState() const { return mCurrentState; }
    534     inline State& getCurrentState() { return mCurrentState; }
    535 
    536     LayerDebugInfo getLayerDebugInfo() const;
    537 
    538     /* always call base class first */
    539     static void miniDumpHeader(String8& result);
    540     void miniDump(String8& result, int32_t hwcId) const;
    541     void dumpFrameStats(String8& result) const;
    542     void dumpFrameEvents(String8& result);
    543     void clearFrameStats();
    544     void logFrameStats();
    545     void getFrameStats(FrameStats* outStats) const;
    546 
    547     virtual std::vector<OccupancyTracker::Segment> getOccupancyHistory(bool /*forceFlush*/) {
    548         return {};
    549     }
    550 
    551     void onDisconnect();
    552     void addAndGetFrameTimestamps(const NewFrameEventsEntry* newEntry,
    553                                   FrameEventHistoryDelta* outDelta);
    554 
    555     virtual bool getTransformToDisplayInverse() const { return false; }
    556 
    557     Transform getTransform() const;
    558 
    559     // Returns the Alpha of the Surface, accounting for the Alpha
    560     // of parent Surfaces in the hierarchy (alpha's will be multiplied
    561     // down the hierarchy).
    562     half getAlpha() const;
    563     half4 getColor() const;
    564 
    565     void traverseInReverseZOrder(LayerVector::StateSet stateSet,
    566                                  const LayerVector::Visitor& visitor);
    567     void traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor);
    568 
    569     /**
    570      * Traverse only children in z order, ignoring relative layers that are not children of the
    571      * parent.
    572      */
    573     void traverseChildrenInZOrder(LayerVector::StateSet stateSet,
    574                                   const LayerVector::Visitor& visitor);
    575 
    576     size_t getChildrenCount() const;
    577     void addChild(const sp<Layer>& layer);
    578     // Returns index if removed, or negative value otherwise
    579     // for symmetry with Vector::remove
    580     ssize_t removeChild(const sp<Layer>& layer);
    581     sp<Layer> getParent() const { return mCurrentParent.promote(); }
    582     bool hasParent() const { return getParent() != nullptr; }
    583     Rect computeScreenBounds(bool reduceTransparentRegion = true) const;
    584     bool setChildLayer(const sp<Layer>& childLayer, int32_t z);
    585     bool setChildRelativeLayer(const sp<Layer>& childLayer,
    586             const sp<IBinder>& relativeToHandle, int32_t relativeZ);
    587 
    588     // Copy the current list of children to the drawing state. Called by
    589     // SurfaceFlinger to complete a transaction.
    590     void commitChildList();
    591     int32_t getZ() const;
    592     void pushPendingState();
    593 
    594 protected:
    595     // constant
    596     sp<SurfaceFlinger> mFlinger;
    597     /*
    598      * Trivial class, used to ensure that mFlinger->onLayerDestroyed(mLayer)
    599      * is called.
    600      */
    601     class LayerCleaner {
    602         sp<SurfaceFlinger> mFlinger;
    603         wp<Layer> mLayer;
    604 
    605     protected:
    606         ~LayerCleaner() {
    607             // destroy client resources
    608             mFlinger->onLayerDestroyed(mLayer);
    609         }
    610 
    611     public:
    612         LayerCleaner(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
    613               : mFlinger(flinger), mLayer(layer) {}
    614     };
    615 
    616     virtual void onFirstRef();
    617 
    618     friend class impl::SurfaceInterceptor;
    619 
    620     void commitTransaction(const State& stateToCommit);
    621 
    622     uint32_t getEffectiveUsage(uint32_t usage) const;
    623 
    624     FloatRect computeCrop(const sp<const DisplayDevice>& hw) const;
    625     // Compute the initial crop as specified by parent layers and the
    626     // SurfaceControl for this layer. Does not include buffer crop from the
    627     // IGraphicBufferProducer client, as that should not affect child clipping.
    628     // Returns in screen space.
    629     Rect computeInitialCrop(const sp<const DisplayDevice>& hw) const;
    630 
    631     // drawing
    632     void clearWithOpenGL(const RenderArea& renderArea, float r, float g, float b,
    633                          float alpha) const;
    634 
    635     void setParent(const sp<Layer>& layer);
    636 
    637     LayerVector makeTraversalList(LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers);
    638     void addZOrderRelative(const wp<Layer>& relative);
    639     void removeZOrderRelative(const wp<Layer>& relative);
    640 
    641     class SyncPoint {
    642     public:
    643         explicit SyncPoint(uint64_t frameNumber)
    644               : mFrameNumber(frameNumber), mFrameIsAvailable(false), mTransactionIsApplied(false) {}
    645 
    646         uint64_t getFrameNumber() const { return mFrameNumber; }
    647 
    648         bool frameIsAvailable() const { return mFrameIsAvailable; }
    649 
    650         void setFrameAvailable() { mFrameIsAvailable = true; }
    651 
    652         bool transactionIsApplied() const { return mTransactionIsApplied; }
    653 
    654         void setTransactionApplied() { mTransactionIsApplied = true; }
    655 
    656     private:
    657         const uint64_t mFrameNumber;
    658         std::atomic<bool> mFrameIsAvailable;
    659         std::atomic<bool> mTransactionIsApplied;
    660     };
    661 
    662     // SyncPoints which will be signaled when the correct frame is at the head
    663     // of the queue and dropped after the frame has been latched. Protected by
    664     // mLocalSyncPointMutex.
    665     Mutex mLocalSyncPointMutex;
    666     std::list<std::shared_ptr<SyncPoint>> mLocalSyncPoints;
    667 
    668     // SyncPoints which will be signaled and then dropped when the transaction
    669     // is applied
    670     std::list<std::shared_ptr<SyncPoint>> mRemoteSyncPoints;
    671 
    672     // Returns false if the relevant frame has already been latched
    673     bool addSyncPoint(const std::shared_ptr<SyncPoint>& point);
    674 
    675     void popPendingState(State* stateToCommit);
    676     bool applyPendingStates(State* stateToCommit);
    677 
    678     void clearSyncPoints();
    679 
    680     // Returns mCurrentScaling mode (originating from the
    681     // Client) or mOverrideScalingMode mode (originating from
    682     // the Surface Controller) if set.
    683     virtual uint32_t getEffectiveScalingMode() const { return 0; }
    684 
    685 public:
    686     /*
    687      * The layer handle is just a BBinder object passed to the client
    688      * (remote process) -- we don't keep any reference on our side such that
    689      * the dtor is called when the remote side let go of its reference.
    690      *
    691      * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
    692      * this layer when the handle is destroyed.
    693      */
    694     class Handle : public BBinder, public LayerCleaner {
    695     public:
    696         Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
    697               : LayerCleaner(flinger, layer), owner(layer) {}
    698 
    699         wp<Layer> owner;
    700     };
    701 
    702     sp<IBinder> getHandle();
    703     const String8& getName() const;
    704     virtual void notifyAvailableFrames() {}
    705     virtual PixelFormat getPixelFormat() const { return PIXEL_FORMAT_NONE; }
    706     bool getPremultipledAlpha() const;
    707 
    708 protected:
    709     // -----------------------------------------------------------------------
    710     bool usingRelativeZ(LayerVector::StateSet stateSet);
    711 
    712     bool mPremultipliedAlpha;
    713     String8 mName;
    714     String8 mTransactionName; // A cached version of "TX - " + mName for systraces
    715 
    716     bool mPrimaryDisplayOnly = false;
    717 
    718     // these are protected by an external lock
    719     State mCurrentState;
    720     State mDrawingState;
    721     volatile int32_t mTransactionFlags;
    722 
    723     // Accessed from main thread and binder threads
    724     Mutex mPendingStateMutex;
    725     Vector<State> mPendingStates;
    726 
    727     // thread-safe
    728     volatile int32_t mQueuedFrames;
    729     volatile int32_t mSidebandStreamChanged; // used like an atomic boolean
    730 
    731     // Timestamp history for UIAutomation. Thread safe.
    732     FrameTracker mFrameTracker;
    733 
    734     // Timestamp history for the consumer to query.
    735     // Accessed by both consumer and producer on main and binder threads.
    736     Mutex mFrameEventHistoryMutex;
    737     ConsumerFrameEventHistory mFrameEventHistory;
    738     FenceTimeline mAcquireTimeline;
    739     FenceTimeline mReleaseTimeline;
    740 
    741     TimeStats& mTimeStats = TimeStats::getInstance();
    742 
    743     // main thread
    744     int mActiveBufferSlot;
    745     sp<GraphicBuffer> mActiveBuffer;
    746     sp<NativeHandle> mSidebandStream;
    747     ui::Dataspace mCurrentDataSpace = ui::Dataspace::UNKNOWN;
    748     Rect mCurrentCrop;
    749     uint32_t mCurrentTransform;
    750     // We encode unset as -1.
    751     int32_t mOverrideScalingMode;
    752     bool mCurrentOpacity;
    753     std::atomic<uint64_t> mCurrentFrameNumber;
    754     bool mFrameLatencyNeeded;
    755     // Whether filtering is forced on or not
    756     bool mFiltering;
    757     // Whether filtering is needed b/c of the drawingstate
    758     bool mNeedsFiltering;
    759 
    760     bool mPendingRemoval = false;
    761 
    762     // page-flip thread (currently main thread)
    763     bool mProtectedByApp; // application requires protected path to external sink
    764 
    765     // protected by mLock
    766     mutable Mutex mLock;
    767 
    768     const wp<Client> mClientRef;
    769 
    770     // This layer can be a cursor on some displays.
    771     bool mPotentialCursor;
    772 
    773     // Local copy of the queued contents of the incoming BufferQueue
    774     mutable Mutex mQueueItemLock;
    775     Condition mQueueItemCondition;
    776     Vector<BufferItem> mQueueItems;
    777     std::atomic<uint64_t> mLastFrameNumberReceived;
    778     bool mAutoRefresh;
    779     bool mFreezeGeometryUpdates;
    780 
    781     // Child list about to be committed/used for editing.
    782     LayerVector mCurrentChildren;
    783     // Child list used for rendering.
    784     LayerVector mDrawingChildren;
    785 
    786     wp<Layer> mCurrentParent;
    787     wp<Layer> mDrawingParent;
    788 
    789     mutable LayerBE mBE;
    790 
    791 private:
    792     /**
    793      * Returns an unsorted vector of all layers that are part of this tree.
    794      * That includes the current layer and all its descendants.
    795      */
    796     std::vector<Layer*> getLayersInTree(LayerVector::StateSet stateSet);
    797     /**
    798      * Traverses layers that are part of this tree in the correct z order.
    799      * layersInTree must be sorted before calling this method.
    800      */
    801     void traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
    802                                        LayerVector::StateSet stateSet,
    803                                        const LayerVector::Visitor& visitor);
    804     LayerVector makeChildrenTraversalList(LayerVector::StateSet stateSet,
    805                                           const std::vector<Layer*>& layersInTree);
    806 };
    807 
    808 // ---------------------------------------------------------------------------
    809 
    810 }; // namespace android
    811 
    812 #endif // ANDROID_LAYER_H
    813