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 
54 namespace android {
55 
56 // ---------------------------------------------------------------------------
57 
58 class Client;
59 class Colorizer;
60 class DisplayDevice;
61 class GraphicBuffer;
62 class SurfaceFlinger;
63 
64 // ---------------------------------------------------------------------------
65 
66 /*
67  * A new BufferQueue and a new SurfaceFlingerConsumer are created when the
68  * Layer is first referenced.
69  *
70  * This also implements onFrameAvailable(), which notifies SurfaceFlinger
71  * that new data has arrived.
72  */
73 class Layer : public SurfaceFlingerConsumer::ContentsChangedListener {
74     static int32_t sSequence;
75 
76 public:
77     mutable bool contentDirty;
78     // regions below are in window-manager space
79     Region visibleRegion;
80     Region coveredRegion;
81     Region visibleNonTransparentRegion;
82     Region surfaceDamageRegion;
83 
84     // Layer serial number.  This gives layers an explicit ordering, so we
85     // have a stable sort order when their layer stack and Z-order are
86     // the same.
87     int32_t sequence;
88 
89     enum { // flags for doTransaction()
90         eDontUpdateGeometryState = 0x00000001,
91         eVisibleRegion = 0x00000002,
92     };
93 
94     struct Geometry {
95         uint32_t w;
96         uint32_t h;
97         Transform transform;
98 
99         inline bool operator ==(const Geometry& rhs) const {
100             return (w == rhs.w && h == rhs.h) &&
101                     (transform.tx() == rhs.transform.tx()) &&
102                     (transform.ty() == rhs.transform.ty());
103         }
104         inline bool operator !=(const Geometry& rhs) const {
105             return !operator ==(rhs);
106         }
107     };
108 
109     struct State {
110         Geometry active;
111         Geometry requested;
112         int32_t z;
113 
114         // The identifier of the layer stack this layer belongs to. A layer can
115         // only be associated to a single layer stack. A layer stack is a
116         // z-ordered group of layers which can be associated to one or more
117         // displays. Using the same layer stack on different displays is a way
118         // to achieve mirroring.
119         uint32_t layerStack;
120 
121 #ifdef USE_HWC2
122         float alpha;
123 #else
124         uint8_t alpha;
125 #endif
126         uint8_t flags;
127         uint8_t mask;
128         uint8_t reserved[2];
129         int32_t sequence; // changes when visible regions can change
130         bool modified;
131 
132         // Crop is expressed in layer space coordinate.
133         Rect crop;
134         Rect requestedCrop;
135 
136         // finalCrop is expressed in display space coordinate.
137         Rect finalCrop;
138         Rect requestedFinalCrop;
139 
140         // If set, defers this state update until the identified Layer
141         // receives a frame with the given frameNumber
142         wp<Layer> barrierLayer;
143         uint64_t frameNumber;
144 
145         // the transparentRegion hint is a bit special, it's latched only
146         // when we receive a buffer -- this is because it's "content"
147         // dependent.
148         Region activeTransparentRegion;
149         Region requestedTransparentRegion;
150         android_dataspace dataSpace;
151 
152         uint32_t appId;
153         uint32_t type;
154 
155         // If non-null, a Surface this Surface's Z-order is interpreted relative to.
156         wp<Layer> zOrderRelativeOf;
157 
158         // A list of surfaces whose Z-order is interpreted relative to ours.
159         SortedVector<wp<Layer>> zOrderRelatives;
160     };
161 
162     // -----------------------------------------------------------------------
163 
164     Layer(SurfaceFlinger* flinger, const sp<Client>& client,
165             const String8& name, uint32_t w, uint32_t h, uint32_t flags);
166 
167     virtual ~Layer();
168 
169     // the this layer's size and format
170     status_t setBuffers(uint32_t w, uint32_t h, PixelFormat format, uint32_t flags);
171 
172     // ------------------------------------------------------------------------
173     // Geometry setting functions.
174     //
175     // The following group of functions are used to specify the layers
176     // bounds, and the mapping of the texture on to those bounds. According
177     // to various settings changes to them may apply immediately, or be delayed until
178     // a pending resize is completed by the producer submitting a buffer. For example
179     // if we were to change the buffer size, and update the matrix ahead of the
180     // new buffer arriving, then we would be stretching the buffer to a different
181     // aspect before and after the buffer arriving, which probably isn't what we wanted.
182     //
183     // The first set of geometry functions are controlled by the scaling mode, described
184     // in window.h. The scaling mode may be set by the client, as it submits buffers.
185     // This value may be overriden through SurfaceControl, with setOverrideScalingMode.
186     //
187     // Put simply, if our scaling mode is SCALING_MODE_FREEZE, then
188     // matrix updates will not be applied while a resize is pending
189     // and the size and transform will remain in their previous state
190     // until a new buffer is submitted. If the scaling mode is another value
191     // then the old-buffer will immediately be scaled to the pending size
192     // and the new matrix will be immediately applied following this scaling
193     // transformation.
194 
195     // Set the default buffer size for the assosciated Producer, in pixels. This is
196     // also the rendered size of the layer prior to any transformations. Parent
197     // or local matrix transformations will not affect the size of the buffer,
198     // but may affect it's on-screen size or clipping.
199     bool setSize(uint32_t w, uint32_t h);
200     // Set a 2x2 transformation matrix on the layer. This transform
201     // will be applied after parent transforms, but before any final
202     // producer specified transform.
203     bool setMatrix(const layer_state_t::matrix22_t& matrix);
204 
205     // This second set of geometry attributes are controlled by
206     // setGeometryAppliesWithResize, and their default mode is to be
207     // immediate. If setGeometryAppliesWithResize is specified
208     // while a resize is pending, then update of these attributes will
209     // be delayed until the resize completes.
210 
211     // setPosition operates in parent buffer space (pre parent-transform) or display
212     // space for top-level layers.
213     bool setPosition(float x, float y, bool immediate);
214     // Buffer space
215     bool setCrop(const Rect& crop, bool immediate);
216     // Parent buffer space/display space
217     bool setFinalCrop(const Rect& crop, bool immediate);
218 
219     // TODO(b/38182121): Could we eliminate the various latching modes by
220     // using the layer hierarchy?
221     // -----------------------------------------------------------------------
222     bool setLayer(int32_t z);
223     bool setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ);
224 
225 #ifdef USE_HWC2
226     bool setAlpha(float alpha);
227 #else
228     bool setAlpha(uint8_t alpha);
229 #endif
230     bool setTransparentRegionHint(const Region& transparent);
231     bool setFlags(uint8_t flags, uint8_t mask);
232     bool setLayerStack(uint32_t layerStack);
233     bool setDataSpace(android_dataspace dataSpace);
234     uint32_t getLayerStack() const;
235     void deferTransactionUntil(const sp<IBinder>& barrierHandle, uint64_t frameNumber);
236     void deferTransactionUntil(const sp<Layer>& barrierLayer, uint64_t frameNumber);
237     bool setOverrideScalingMode(int32_t overrideScalingMode);
238     void setInfo(uint32_t type, uint32_t appId);
239     bool reparentChildren(const sp<IBinder>& layer);
240     bool detachChildren();
241 
242     // If we have received a new buffer this frame, we will pass its surface
243     // damage down to hardware composer. Otherwise, we must send a region with
244     // one empty rect.
245     void useSurfaceDamage();
246     void useEmptyDamage();
247 
248     uint32_t getTransactionFlags(uint32_t flags);
249     uint32_t setTransactionFlags(uint32_t flags);
250 
251     void computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
252             bool useIdentityTransform) const;
253     Rect computeBounds(const Region& activeTransparentRegion) const;
254     Rect computeBounds() const;
255 
getSequence()256     int32_t getSequence() const { return sequence; }
257 
258     // -----------------------------------------------------------------------
259     // Virtuals
260 
getTypeId()261     virtual const char* getTypeId() const { return "Layer"; }
262 
263     /*
264      * isOpaque - true if this surface is opaque
265      *
266      * This takes into account the buffer format (i.e. whether or not the
267      * pixel format includes an alpha channel) and the "opaque" flag set
268      * on the layer.  It does not examine the current plane alpha value.
269      */
270     virtual bool isOpaque(const Layer::State& s) const;
271 
272     /*
273      * isSecure - true if this surface is secure, that is if it prevents
274      * screenshots or VNC servers.
275      */
276     virtual bool isSecure() const;
277 
278     /*
279      * isProtected - true if the layer may contain protected content in the
280      * GRALLOC_USAGE_PROTECTED sense.
281      */
282     virtual bool isProtected() const;
283 
284     /*
285      * isVisible - true if this layer is visible, false otherwise
286      */
287     virtual bool isVisible() const;
288 
289     /*
290      * isHiddenByPolicy - true if this layer has been forced invisible.
291      * just because this is false, doesn't mean isVisible() is true.
292      * For example if this layer has no active buffer, it may not be hidden by
293      * policy, but it still can not be visible.
294      */
295     virtual bool isHiddenByPolicy() const;
296 
297     /*
298      * isFixedSize - true if content has a fixed size
299      */
300     virtual bool isFixedSize() const;
301 
302 protected:
303     /*
304      * onDraw - draws the surface.
305      */
306     virtual void onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
307             bool useIdentityTransform) const;
308 
309 public:
310     // -----------------------------------------------------------------------
311 
312 #ifdef USE_HWC2
313     void setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z);
314     void forceClientComposition(int32_t hwcId);
315     void setPerFrameData(const sp<const DisplayDevice>& displayDevice);
316 
317     android_dataspace getDataSpace() const;
318 
319     // callIntoHwc exists so we can update our local state and call
320     // acceptDisplayChanges without unnecessarily updating the device's state
321     void setCompositionType(int32_t hwcId, HWC2::Composition type,
322             bool callIntoHwc = true);
323     HWC2::Composition getCompositionType(int32_t hwcId) const;
324 
325     void setClearClientTarget(int32_t hwcId, bool clear);
326     bool getClearClientTarget(int32_t hwcId) const;
327 
328     void updateCursorPosition(const sp<const DisplayDevice>& hw);
329 #else
330     void setGeometry(const sp<const DisplayDevice>& hw,
331             HWComposer::HWCLayerInterface& layer);
332     void setPerFrameData(const sp<const DisplayDevice>& hw,
333             HWComposer::HWCLayerInterface& layer);
334     void setAcquireFence(const sp<const DisplayDevice>& hw,
335             HWComposer::HWCLayerInterface& layer);
336 
337     Rect getPosition(const sp<const DisplayDevice>& hw);
338 #endif
339 
340     /*
341      * called after page-flip
342      */
343 #ifdef USE_HWC2
344     void onLayerDisplayed(const sp<Fence>& releaseFence);
345 #else
346     void onLayerDisplayed(const sp<const DisplayDevice>& hw,
347             HWComposer::HWCLayerInterface* layer);
348 #endif
349 
350     bool shouldPresentNow(const DispSync& dispSync) const;
351 
352     /*
353      * called before composition.
354      * returns true if the layer has pending updates.
355      */
356     bool onPreComposition(nsecs_t refreshStartTime);
357 
358     /*
359      * called after composition.
360      * returns true if the layer latched a new buffer this frame.
361      */
362     bool onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
363             const std::shared_ptr<FenceTime>& presentFence,
364             const CompositorTiming& compositorTiming);
365 
366 #ifdef USE_HWC2
367     // If a buffer was replaced this frame, release the former buffer
368     void releasePendingBuffer(nsecs_t dequeueReadyTime);
369 #endif
370 
371     /*
372      * draw - performs some global clipping optimizations
373      * and calls onDraw().
374      */
375     void draw(const sp<const DisplayDevice>& hw, const Region& clip) const;
376     void draw(const sp<const DisplayDevice>& hw, bool useIdentityTransform) const;
377     void draw(const sp<const DisplayDevice>& hw) const;
378 
379     /*
380      * doTransaction - process the transaction. This is a good place to figure
381      * out which attributes of the surface have changed.
382      */
383     uint32_t doTransaction(uint32_t transactionFlags);
384 
385     /*
386      * setVisibleRegion - called to set the new visible region. This gives
387      * a chance to update the new visible region or record the fact it changed.
388      */
389     void setVisibleRegion(const Region& visibleRegion);
390 
391     /*
392      * setCoveredRegion - called when the covered region changes. The covered
393      * region corresponds to any area of the surface that is covered
394      * (transparently or not) by another surface.
395      */
396     void setCoveredRegion(const Region& coveredRegion);
397 
398     /*
399      * setVisibleNonTransparentRegion - called when the visible and
400      * non-transparent region changes.
401      */
402     void setVisibleNonTransparentRegion(const Region&
403             visibleNonTransparentRegion);
404 
405     /*
406      * latchBuffer - called each time the screen is redrawn and returns whether
407      * the visible regions need to be recomputed (this is a fairly heavy
408      * operation, so this should be set only if needed). Typically this is used
409      * to figure out if the content or size of a surface has changed.
410      */
411     Region latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime);
412 
isPotentialCursor()413     bool isPotentialCursor() const { return mPotentialCursor;}
414 
415     /*
416      * called with the state lock when the surface is removed from the
417      * current list
418      */
419     void onRemoved();
420 
421 
422     // Updates the transform hint in our SurfaceFlingerConsumer to match
423     // the current orientation of the display device.
424     void updateTransformHint(const sp<const DisplayDevice>& hw) const;
425 
426     /*
427      * returns the rectangle that crops the content of the layer and scales it
428      * to the layer's size.
429      */
430     Rect getContentCrop() const;
431 
432     /*
433      * Returns if a frame is queued.
434      */
hasQueuedFrame()435     bool hasQueuedFrame() const { return mQueuedFrames > 0 ||
436             mSidebandStreamChanged || mAutoRefresh; }
437 
438 #ifdef USE_HWC2
439     // -----------------------------------------------------------------------
440 
hasHwcLayer(int32_t hwcId)441     bool hasHwcLayer(int32_t hwcId) {
442         if (mHwcLayers.count(hwcId) == 0) {
443             return false;
444         }
445         if (mHwcLayers[hwcId].layer->isAbandoned()) {
446             ALOGI("Erasing abandoned layer %s on %d", mName.string(), hwcId);
447             mHwcLayers.erase(hwcId);
448             return false;
449         }
450         return true;
451     }
452 
getHwcLayer(int32_t hwcId)453     std::shared_ptr<HWC2::Layer> getHwcLayer(int32_t hwcId) {
454         if (mHwcLayers.count(hwcId) == 0) {
455             return nullptr;
456         }
457         return mHwcLayers[hwcId].layer;
458     }
459 
setHwcLayer(int32_t hwcId,std::shared_ptr<HWC2::Layer> && layer)460     void setHwcLayer(int32_t hwcId, std::shared_ptr<HWC2::Layer>&& layer) {
461         if (layer) {
462             mHwcLayers[hwcId].layer = layer;
463         } else {
464             mHwcLayers.erase(hwcId);
465         }
466     }
467 
clearHwcLayers()468     void clearHwcLayers() {
469         mHwcLayers.clear();
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
getActiveBuffer()480     inline const sp<GraphicBuffer>& getActiveBuffer() const { return mActiveBuffer; }
481 
getDrawingState()482     inline  const State&    getDrawingState() const { return mDrawingState; }
getCurrentState()483     inline  const State&    getCurrentState() const { return mCurrentState; }
getCurrentState()484     inline  State&          getCurrentState()       { return mCurrentState; }
485 
486 
487     /* always call base class first */
488     void dump(String8& result, Colorizer& colorizer) const;
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);
getParent()527     sp<Layer> getParent() const { return mCurrentParent.promote(); }
hasParent()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;
538 protected:
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:
~LayerCleaner()549         ~LayerCleaner() {
550             // destroy client resources
551             mFlinger->onLayerDestroyed(mLayer);
552         }
553     public:
LayerCleaner(const sp<SurfaceFlinger> & flinger,const sp<Layer> & layer)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 
565 private:
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:
SyncPoint(uint64_t frameNumber)610         explicit SyncPoint(uint64_t frameNumber) : mFrameNumber(frameNumber),
611                 mFrameIsAvailable(false), mTransactionIsApplied(false) {}
612 
getFrameNumber()613         uint64_t getFrameNumber() const {
614             return mFrameNumber;
615         }
616 
frameIsAvailable()617         bool frameIsAvailable() const {
618             return mFrameIsAvailable;
619         }
620 
setFrameAvailable()621         void setFrameAvailable() {
622             mFrameIsAvailable = true;
623         }
624 
transactionIsApplied()625         bool transactionIsApplied() const {
626             return mTransactionIsApplied;
627         }
628 
setTransactionApplied()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;
665 public:
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:
Handle(const sp<SurfaceFlinger> & flinger,const sp<Layer> & layer)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 private:
687 
688     // -----------------------------------------------------------------------
689 
690     // Check all of the local sync points to ensure that all transactions
691     // which need to have been applied prior to the frame which is about to
692     // be latched have signaled
693     bool allTransactionsSignaled();
694 
695     // constants
696     sp<SurfaceFlingerConsumer> mSurfaceFlingerConsumer;
697     sp<IGraphicBufferProducer> mProducer;
698     uint32_t mTextureName;      // from GLES
699     bool mPremultipliedAlpha;
700     String8 mName;
701     PixelFormat mFormat;
702 
703     // these are protected by an external lock
704     State mCurrentState;
705     State mDrawingState;
706     volatile int32_t mTransactionFlags;
707 
708     // Accessed from main thread and binder threads
709     Mutex mPendingStateMutex;
710     Vector<State> mPendingStates;
711 
712     // thread-safe
713     volatile int32_t mQueuedFrames;
714     volatile int32_t mSidebandStreamChanged; // used like an atomic boolean
715 
716     // Timestamp history for UIAutomation. Thread safe.
717     FrameTracker mFrameTracker;
718 
719     // Timestamp history for the consumer to query.
720     // Accessed by both consumer and producer on main and binder threads.
721     Mutex mFrameEventHistoryMutex;
722     ConsumerFrameEventHistory mFrameEventHistory;
723     FenceTimeline mAcquireTimeline;
724     FenceTimeline mReleaseTimeline;
725 
726     // main thread
727     int mActiveBufferSlot;
728     sp<GraphicBuffer> mActiveBuffer;
729     sp<NativeHandle> mSidebandStream;
730     Rect mCurrentCrop;
731     uint32_t mCurrentTransform;
732     uint32_t mCurrentScalingMode;
733     // We encode unset as -1.
734     int32_t mOverrideScalingMode;
735     bool mCurrentOpacity;
736     bool mBufferLatched = false;  // TODO: Use mActiveBuffer?
737     std::atomic<uint64_t> mCurrentFrameNumber;
738     uint64_t mPreviousFrameNumber; // Only accessed on the main thread.
739     bool mRefreshPending;
740     bool mFrameLatencyNeeded;
741     // Whether filtering is forced on or not
742     bool mFiltering;
743     // Whether filtering is needed b/c of the drawingstate
744     bool mNeedsFiltering;
745     // The mesh used to draw the layer in GLES composition mode
746     mutable Mesh mMesh;
747     // The texture used to draw the layer in GLES composition mode
748     mutable Texture mTexture;
749 
750 #ifdef USE_HWC2
751     // HWC items, accessed from the main thread
752     struct HWCInfo {
HWCInfoHWCInfo753         HWCInfo()
754           : layer(),
755             forceClientComposition(false),
756             compositionType(HWC2::Composition::Invalid),
757             clearClientTarget(false) {}
758 
759         std::shared_ptr<HWC2::Layer> layer;
760         bool forceClientComposition;
761         HWC2::Composition compositionType;
762         bool clearClientTarget;
763         Rect displayFrame;
764         FloatRect sourceCrop;
765         HWComposerBufferCache bufferCache;
766     };
767 
768     // A layer can be attached to multiple displays when operating in mirror mode
769     // (a.k.a: when several displays are attached with equal layerStack). In this
770     // case we need to keep track. In non-mirror mode, a layer will have only one
771     // HWCInfo. This map key is a display layerStack.
772     std::unordered_map<int32_t, HWCInfo> mHwcLayers;
773 #else
774     bool mIsGlesComposition;
775 #endif
776 
777     // page-flip thread (currently main thread)
778     bool mProtectedByApp; // application requires protected path to external sink
779 
780     // protected by mLock
781     mutable Mutex mLock;
782     // Set to true once we've returned this surface's handle
783     mutable bool mHasSurface;
784     const wp<Client> mClientRef;
785 
786     // This layer can be a cursor on some displays.
787     bool mPotentialCursor;
788 
789     // Local copy of the queued contents of the incoming BufferQueue
790     mutable Mutex mQueueItemLock;
791     Condition mQueueItemCondition;
792     Vector<BufferItem> mQueueItems;
793     std::atomic<uint64_t> mLastFrameNumberReceived;
794     bool mUpdateTexImageFailed; // This is only accessed on the main thread.
795 
796     bool mAutoRefresh;
797     bool mFreezeGeometryUpdates;
798 
799     // Child list about to be committed/used for editing.
800     LayerVector mCurrentChildren;
801     // Child list used for rendering.
802     LayerVector mDrawingChildren;
803 
804     wp<Layer> mCurrentParent;
805     wp<Layer> mDrawingParent;
806 };
807 
808 // ---------------------------------------------------------------------------
809 
810 }; // namespace android
811 
812 #endif // ANDROID_LAYER_H
813