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