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