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