Layer.h revision f1961f713de2b3f54c8ce7653964b969e1a02bc8
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 reparent(const sp<IBinder>& newParentHandle);
245    bool detachChildren();
246
247    // If we have received a new buffer this frame, we will pass its surface
248    // damage down to hardware composer. Otherwise, we must send a region with
249    // one empty rect.
250    void useSurfaceDamage();
251    void useEmptyDamage();
252
253    uint32_t getTransactionFlags(uint32_t flags);
254    uint32_t setTransactionFlags(uint32_t flags);
255
256    bool belongsToDisplay(uint32_t layerStack, bool isPrimaryDisplay) const {
257        return getLayerStack() == layerStack && (!mPrimaryDisplayOnly || isPrimaryDisplay);
258    }
259
260    void computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
261            bool useIdentityTransform) const;
262    Rect computeBounds(const Region& activeTransparentRegion) const;
263    Rect computeBounds() const;
264
265    int32_t getSequence() const { return sequence; }
266
267    // -----------------------------------------------------------------------
268    // Virtuals
269
270    virtual const char* getTypeId() const { return "Layer"; }
271
272    /*
273     * isOpaque - true if this surface is opaque
274     *
275     * This takes into account the buffer format (i.e. whether or not the
276     * pixel format includes an alpha channel) and the "opaque" flag set
277     * on the layer.  It does not examine the current plane alpha value.
278     */
279    virtual bool isOpaque(const Layer::State& s) const;
280
281    /*
282     * isSecure - true if this surface is secure, that is if it prevents
283     * screenshots or VNC servers.
284     */
285    virtual bool isSecure() const;
286
287    /*
288     * isProtected - true if the layer may contain protected content in the
289     * GRALLOC_USAGE_PROTECTED sense.
290     */
291    virtual bool isProtected() const;
292
293    /*
294     * isVisible - true if this layer is visible, false otherwise
295     */
296    virtual bool isVisible() const;
297
298    /*
299     * isHiddenByPolicy - true if this layer has been forced invisible.
300     * just because this is false, doesn't mean isVisible() is true.
301     * For example if this layer has no active buffer, it may not be hidden by
302     * policy, but it still can not be visible.
303     */
304    virtual bool isHiddenByPolicy() const;
305
306    /*
307     * isFixedSize - true if content has a fixed size
308     */
309    virtual bool isFixedSize() const;
310
311protected:
312    /*
313     * onDraw - draws the surface.
314     */
315    virtual void onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
316            bool useIdentityTransform) const;
317
318public:
319    // -----------------------------------------------------------------------
320
321#ifdef USE_HWC2
322    void setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z);
323    void forceClientComposition(int32_t hwcId);
324    void setPerFrameData(const sp<const DisplayDevice>& displayDevice);
325
326    // callIntoHwc exists so we can update our local state and call
327    // acceptDisplayChanges without unnecessarily updating the device's state
328    void setCompositionType(int32_t hwcId, HWC2::Composition type,
329            bool callIntoHwc = true);
330    HWC2::Composition getCompositionType(int32_t hwcId) const;
331
332    void setClearClientTarget(int32_t hwcId, bool clear);
333    bool getClearClientTarget(int32_t hwcId) const;
334
335    void updateCursorPosition(const sp<const DisplayDevice>& hw);
336#else
337    void setGeometry(const sp<const DisplayDevice>& hw,
338            HWComposer::HWCLayerInterface& layer);
339    void setPerFrameData(const sp<const DisplayDevice>& hw,
340            HWComposer::HWCLayerInterface& layer);
341    void setAcquireFence(const sp<const DisplayDevice>& hw,
342            HWComposer::HWCLayerInterface& layer);
343
344    Rect getPosition(const sp<const DisplayDevice>& hw);
345#endif
346
347    /*
348     * called after page-flip
349     */
350#ifdef USE_HWC2
351    void onLayerDisplayed(const sp<Fence>& releaseFence);
352#else
353    void onLayerDisplayed(const sp<const DisplayDevice>& hw,
354            HWComposer::HWCLayerInterface* layer);
355#endif
356
357    bool shouldPresentNow(const DispSync& dispSync) const;
358
359    /*
360     * called before composition.
361     * returns true if the layer has pending updates.
362     */
363    bool onPreComposition(nsecs_t refreshStartTime);
364
365    /*
366     * called after composition.
367     * returns true if the layer latched a new buffer this frame.
368     */
369    bool onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
370            const std::shared_ptr<FenceTime>& presentFence,
371            const CompositorTiming& compositorTiming);
372
373#ifdef USE_HWC2
374    // If a buffer was replaced this frame, release the former buffer
375    void releasePendingBuffer(nsecs_t dequeueReadyTime);
376#endif
377
378    /*
379     * draw - performs some global clipping optimizations
380     * and calls onDraw().
381     */
382    void draw(const sp<const DisplayDevice>& hw, const Region& clip) const;
383    void draw(const sp<const DisplayDevice>& hw, bool useIdentityTransform) const;
384    void draw(const sp<const DisplayDevice>& hw) const;
385
386    /*
387     * doTransaction - process the transaction. This is a good place to figure
388     * out which attributes of the surface have changed.
389     */
390    uint32_t doTransaction(uint32_t transactionFlags);
391
392    /*
393     * setVisibleRegion - called to set the new visible region. This gives
394     * a chance to update the new visible region or record the fact it changed.
395     */
396    void setVisibleRegion(const Region& visibleRegion);
397
398    /*
399     * setCoveredRegion - called when the covered region changes. The covered
400     * region corresponds to any area of the surface that is covered
401     * (transparently or not) by another surface.
402     */
403    void setCoveredRegion(const Region& coveredRegion);
404
405    /*
406     * setVisibleNonTransparentRegion - called when the visible and
407     * non-transparent region changes.
408     */
409    void setVisibleNonTransparentRegion(const Region&
410            visibleNonTransparentRegion);
411
412    /*
413     * latchBuffer - called each time the screen is redrawn and returns whether
414     * the visible regions need to be recomputed (this is a fairly heavy
415     * operation, so this should be set only if needed). Typically this is used
416     * to figure out if the content or size of a surface has changed.
417     */
418    Region latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime);
419    bool isBufferLatched() const { return mRefreshPending; }
420
421    bool isPotentialCursor() const { return mPotentialCursor;}
422
423    /*
424     * called with the state lock from a binder thread when the layer is
425     * removed from the current list to the pending removal list
426     */
427    void onRemovedFromCurrentState();
428
429    /*
430     * called with the state lock from the main thread when the layer is
431     * removed from the pending removal list
432     */
433    void onRemoved();
434
435
436    // Updates the transform hint in our SurfaceFlingerConsumer to match
437    // the current orientation of the display device.
438    void updateTransformHint(const sp<const DisplayDevice>& hw) const;
439
440    /*
441     * returns the rectangle that crops the content of the layer and scales it
442     * to the layer's size.
443     */
444    Rect getContentCrop() const;
445
446    /*
447     * Returns if a frame is queued.
448     */
449    bool hasQueuedFrame() const { return mQueuedFrames > 0 ||
450            mSidebandStreamChanged || mAutoRefresh; }
451
452    int32_t getQueuedFrameCount() const { return mQueuedFrames; }
453
454#ifdef USE_HWC2
455    // -----------------------------------------------------------------------
456
457    bool createHwcLayer(HWComposer* hwc, int32_t hwcId);
458    void destroyHwcLayer(int32_t hwcId);
459    void destroyAllHwcLayers();
460
461    bool hasHwcLayer(int32_t hwcId) {
462        return mHwcLayers.count(hwcId) > 0;
463    }
464
465    HWC2::Layer* getHwcLayer(int32_t hwcId) {
466        if (mHwcLayers.count(hwcId) == 0) {
467            return nullptr;
468        }
469        return mHwcLayers[hwcId].layer;
470    }
471
472#endif
473    // -----------------------------------------------------------------------
474
475    void clearWithOpenGL(const sp<const DisplayDevice>& hw) const;
476    void setFiltering(bool filtering);
477    bool getFiltering() const;
478
479    // only for debugging
480    inline const sp<GraphicBuffer>& getActiveBuffer() const { return mActiveBuffer; }
481
482    inline  const State&    getDrawingState() const { return mDrawingState; }
483    inline  const State&    getCurrentState() const { return mCurrentState; }
484    inline  State&          getCurrentState()       { return mCurrentState; }
485
486    LayerDebugInfo getLayerDebugInfo() const;
487
488    /* always call base class first */
489#ifdef USE_HWC2
490    static void miniDumpHeader(String8& result);
491    void miniDump(String8& result, int32_t hwcId) const;
492#endif
493    void dumpFrameStats(String8& result) const;
494    void dumpFrameEvents(String8& result);
495    void clearFrameStats();
496    void logFrameStats();
497    void getFrameStats(FrameStats* outStats) const;
498
499    std::vector<OccupancyTracker::Segment> getOccupancyHistory(bool forceFlush);
500
501    void onDisconnect();
502    void addAndGetFrameTimestamps(const NewFrameEventsEntry* newEntry,
503            FrameEventHistoryDelta* outDelta);
504
505    bool getTransformToDisplayInverse() const;
506
507    Transform getTransform() const;
508
509    // Returns the Alpha of the Surface, accounting for the Alpha
510    // of parent Surfaces in the hierarchy (alpha's will be multiplied
511    // down the hierarchy).
512#ifdef USE_HWC2
513    float getAlpha() const;
514#else
515    uint8_t getAlpha() const;
516#endif
517
518    void traverseInReverseZOrder(LayerVector::StateSet stateSet,
519                                 const LayerVector::Visitor& visitor);
520    void traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor);
521
522    size_t getChildrenCount() const;
523    void addChild(const sp<Layer>& layer);
524    // Returns index if removed, or negative value otherwise
525    // for symmetry with Vector::remove
526    ssize_t removeChild(const sp<Layer>& layer);
527    sp<Layer> getParent() const { return mCurrentParent.promote(); }
528    bool hasParent() const { return getParent() != nullptr; }
529
530    Rect computeScreenBounds(bool reduceTransparentRegion = true) const;
531    bool setChildLayer(const sp<Layer>& childLayer, int32_t z);
532
533    // Copy the current list of children to the drawing state. Called by
534    // SurfaceFlinger to complete a transaction.
535    void commitChildList();
536
537    int32_t getZ() const;
538protected:
539    // constant
540    sp<SurfaceFlinger> mFlinger;
541    /*
542     * Trivial class, used to ensure that mFlinger->onLayerDestroyed(mLayer)
543     * is called.
544     */
545    class LayerCleaner {
546        sp<SurfaceFlinger> mFlinger;
547        wp<Layer> mLayer;
548    protected:
549        ~LayerCleaner() {
550            // destroy client resources
551            mFlinger->onLayerDestroyed(mLayer);
552        }
553    public:
554        LayerCleaner(const sp<SurfaceFlinger>& flinger,
555                const sp<Layer>& layer)
556            : mFlinger(flinger), mLayer(layer) {
557        }
558    };
559
560
561    virtual void onFirstRef();
562
563
564
565private:
566    friend class SurfaceInterceptor;
567    // Interface implementation for SurfaceFlingerConsumer::ContentsChangedListener
568    virtual void onFrameAvailable(const BufferItem& item) override;
569    virtual void onFrameReplaced(const BufferItem& item) override;
570    virtual void onSidebandStreamChanged() override;
571
572    void commitTransaction(const State& stateToCommit);
573
574    // needsLinearFiltering - true if this surface's state requires filtering
575    bool needsFiltering(const sp<const DisplayDevice>& hw) const;
576
577    uint32_t getEffectiveUsage(uint32_t usage) const;
578
579    FloatRect computeCrop(const sp<const DisplayDevice>& hw) const;
580    // Compute the initial crop as specified by parent layers and the SurfaceControl
581    // for this layer. Does not include buffer crop from the IGraphicBufferProducer
582    // client, as that should not affect child clipping. Returns in screen space.
583    Rect computeInitialCrop(const sp<const DisplayDevice>& hw) const;
584    bool isCropped() const;
585    static bool getOpacityForFormat(uint32_t format);
586
587    // drawing
588    void clearWithOpenGL(const sp<const DisplayDevice>& hw,
589            float r, float g, float b, float alpha) const;
590    void drawWithOpenGL(const sp<const DisplayDevice>& hw,
591            bool useIdentityTransform) const;
592
593    // Temporary - Used only for LEGACY camera mode.
594    uint32_t getProducerStickyTransform() const;
595
596    // Loads the corresponding system property once per process
597    static bool latchUnsignaledBuffers();
598
599    void setParent(const sp<Layer>& layer);
600
601    LayerVector makeTraversalList(LayerVector::StateSet stateSet);
602    void addZOrderRelative(const wp<Layer>& relative);
603    void removeZOrderRelative(const wp<Layer>& relative);
604
605    // -----------------------------------------------------------------------
606
607    class SyncPoint
608    {
609    public:
610        explicit SyncPoint(uint64_t frameNumber) : mFrameNumber(frameNumber),
611                mFrameIsAvailable(false), mTransactionIsApplied(false) {}
612
613        uint64_t getFrameNumber() const {
614            return mFrameNumber;
615        }
616
617        bool frameIsAvailable() const {
618            return mFrameIsAvailable;
619        }
620
621        void setFrameAvailable() {
622            mFrameIsAvailable = true;
623        }
624
625        bool transactionIsApplied() const {
626            return mTransactionIsApplied;
627        }
628
629        void setTransactionApplied() {
630            mTransactionIsApplied = true;
631        }
632
633    private:
634        const uint64_t mFrameNumber;
635        std::atomic<bool> mFrameIsAvailable;
636        std::atomic<bool> mTransactionIsApplied;
637    };
638
639    // SyncPoints which will be signaled when the correct frame is at the head
640    // of the queue and dropped after the frame has been latched. Protected by
641    // mLocalSyncPointMutex.
642    Mutex mLocalSyncPointMutex;
643    std::list<std::shared_ptr<SyncPoint>> mLocalSyncPoints;
644
645    // SyncPoints which will be signaled and then dropped when the transaction
646    // is applied
647    std::list<std::shared_ptr<SyncPoint>> mRemoteSyncPoints;
648
649    uint64_t getHeadFrameNumber() const;
650    bool headFenceHasSignaled() const;
651
652    // Returns false if the relevant frame has already been latched
653    bool addSyncPoint(const std::shared_ptr<SyncPoint>& point);
654
655    void pushPendingState();
656    void popPendingState(State* stateToCommit);
657    bool applyPendingStates(State* stateToCommit);
658
659    void clearSyncPoints();
660
661    // Returns mCurrentScaling mode (originating from the
662    // Client) or mOverrideScalingMode mode (originating from
663    // the Surface Controller) if set.
664    uint32_t getEffectiveScalingMode() const;
665public:
666    /*
667     * The layer handle is just a BBinder object passed to the client
668     * (remote process) -- we don't keep any reference on our side such that
669     * the dtor is called when the remote side let go of its reference.
670     *
671     * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
672     * this layer when the handle is destroyed.
673     */
674    class Handle : public BBinder, public LayerCleaner {
675        public:
676            Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
677                : LayerCleaner(flinger, layer), owner(layer) {}
678
679            wp<Layer> owner;
680    };
681
682    sp<IBinder> getHandle();
683    sp<IGraphicBufferProducer> getProducer() const;
684    const String8& getName() const;
685    void notifyAvailableFrames();
686
687    PixelFormat getPixelFormat() const { return mFormat; }
688
689private:
690
691    // -----------------------------------------------------------------------
692
693    // Check all of the local sync points to ensure that all transactions
694    // which need to have been applied prior to the frame which is about to
695    // be latched have signaled
696    bool allTransactionsSignaled();
697
698    // constants
699    sp<SurfaceFlingerConsumer> mSurfaceFlingerConsumer;
700    sp<IGraphicBufferProducer> mProducer;
701    uint32_t mTextureName;      // from GLES
702    bool mPremultipliedAlpha;
703    String8 mName;
704    String8 mTransactionName; // A cached version of "TX - " + mName for systraces
705    PixelFormat mFormat;
706
707    bool mPrimaryDisplayOnly = false;
708
709    // these are protected by an external lock
710    State mCurrentState;
711    State mDrawingState;
712    volatile int32_t mTransactionFlags;
713
714    // Accessed from main thread and binder threads
715    Mutex mPendingStateMutex;
716    Vector<State> mPendingStates;
717
718    // thread-safe
719    volatile int32_t mQueuedFrames;
720    volatile int32_t mSidebandStreamChanged; // used like an atomic boolean
721
722    // Timestamp history for UIAutomation. Thread safe.
723    FrameTracker mFrameTracker;
724
725    // Timestamp history for the consumer to query.
726    // Accessed by both consumer and producer on main and binder threads.
727    Mutex mFrameEventHistoryMutex;
728    ConsumerFrameEventHistory mFrameEventHistory;
729    FenceTimeline mAcquireTimeline;
730    FenceTimeline mReleaseTimeline;
731
732    // main thread
733    int mActiveBufferSlot;
734    sp<GraphicBuffer> mActiveBuffer;
735    sp<NativeHandle> mSidebandStream;
736    Rect mCurrentCrop;
737    uint32_t mCurrentTransform;
738    uint32_t mCurrentScalingMode;
739    // We encode unset as -1.
740    int32_t mOverrideScalingMode;
741    bool mCurrentOpacity;
742    bool mBufferLatched = false;  // TODO: Use mActiveBuffer?
743    std::atomic<uint64_t> mCurrentFrameNumber;
744    uint64_t mPreviousFrameNumber; // Only accessed on the main thread.
745    bool mRefreshPending;
746    bool mFrameLatencyNeeded;
747    // Whether filtering is forced on or not
748    bool mFiltering;
749    // Whether filtering is needed b/c of the drawingstate
750    bool mNeedsFiltering;
751    // The mesh used to draw the layer in GLES composition mode
752    mutable Mesh mMesh;
753    // The texture used to draw the layer in GLES composition mode
754    mutable Texture mTexture;
755
756#ifdef USE_HWC2
757    // HWC items, accessed from the main thread
758    struct HWCInfo {
759        HWCInfo()
760          : hwc(nullptr),
761            layer(nullptr),
762            forceClientComposition(false),
763            compositionType(HWC2::Composition::Invalid),
764            clearClientTarget(false) {}
765
766        HWComposer* hwc;
767        HWC2::Layer* layer;
768        bool forceClientComposition;
769        HWC2::Composition compositionType;
770        bool clearClientTarget;
771        Rect displayFrame;
772        FloatRect sourceCrop;
773        HWComposerBufferCache bufferCache;
774    };
775
776    // A layer can be attached to multiple displays when operating in mirror mode
777    // (a.k.a: when several displays are attached with equal layerStack). In this
778    // case we need to keep track. In non-mirror mode, a layer will have only one
779    // HWCInfo. This map key is a display layerStack.
780    std::unordered_map<int32_t, HWCInfo> mHwcLayers;
781#else
782    bool mIsGlesComposition;
783#endif
784
785    // page-flip thread (currently main thread)
786    bool mProtectedByApp; // application requires protected path to external sink
787
788    // protected by mLock
789    mutable Mutex mLock;
790    // Set to true once we've returned this surface's handle
791    mutable bool mHasSurface;
792    const wp<Client> mClientRef;
793
794    // This layer can be a cursor on some displays.
795    bool mPotentialCursor;
796
797    // Local copy of the queued contents of the incoming BufferQueue
798    mutable Mutex mQueueItemLock;
799    Condition mQueueItemCondition;
800    Vector<BufferItem> mQueueItems;
801    std::atomic<uint64_t> mLastFrameNumberReceived;
802    bool mUpdateTexImageFailed; // This is only accessed on the main thread.
803
804    bool mAutoRefresh;
805    bool mFreezeGeometryUpdates;
806
807    // Child list about to be committed/used for editing.
808    LayerVector mCurrentChildren;
809    // Child list used for rendering.
810    LayerVector mDrawingChildren;
811
812    wp<Layer> mCurrentParent;
813    wp<Layer> mDrawingParent;
814};
815
816// ---------------------------------------------------------------------------
817
818}; // namespace android
819
820#endif // ANDROID_LAYER_H
821