• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #pragma once
18 
19 #include <sys/types.h>
20 
21 /*
22  * NOTE: Make sure this file doesn't include  anything from <gl/ > or <gl2/ >
23  */
24 
25 #include <android-base/thread_annotations.h>
26 #include <cutils/atomic.h>
27 #include <cutils/compiler.h>
28 #include <gui/BufferQueue.h>
29 #include <gui/FrameTimestamps.h>
30 #include <gui/ISurfaceComposer.h>
31 #include <gui/ISurfaceComposerClient.h>
32 #include <gui/LayerState.h>
33 #include <gui/OccupancyTracker.h>
34 #include <hardware/hwcomposer_defs.h>
35 #include <input/ISetInputWindowsListener.h>
36 #include <layerproto/LayerProtoHeader.h>
37 #include <math/mat4.h>
38 #include <serviceutils/PriorityDumper.h>
39 #include <system/graphics.h>
40 #include <ui/FenceTime.h>
41 #include <ui/PixelFormat.h>
42 #include <utils/Errors.h>
43 #include <utils/KeyedVector.h>
44 #include <utils/RefBase.h>
45 #include <utils/SortedVector.h>
46 #include <utils/Trace.h>
47 #include <utils/threads.h>
48 
49 #include "ClientCache.h"
50 #include "DisplayDevice.h"
51 #include "DisplayHardware/HWC2.h"
52 #include "DisplayHardware/PowerAdvisor.h"
53 #include "Effects/Daltonizer.h"
54 #include "FrameTracker.h"
55 #include "LayerStats.h"
56 #include "LayerVector.h"
57 #include "Scheduler/RefreshRateConfigs.h"
58 #include "Scheduler/RefreshRateStats.h"
59 #include "Scheduler/Scheduler.h"
60 #include "Scheduler/VSyncModulator.h"
61 #include "SurfaceFlingerFactory.h"
62 #include "SurfaceTracing.h"
63 #include "TransactionCompletedThread.h"
64 
65 #include <atomic>
66 #include <cstdint>
67 #include <functional>
68 #include <map>
69 #include <memory>
70 #include <mutex>
71 #include <queue>
72 #include <set>
73 #include <string>
74 #include <thread>
75 #include <type_traits>
76 #include <unordered_map>
77 #include <unordered_set>
78 #include <utility>
79 
80 using namespace android::surfaceflinger;
81 
82 namespace android {
83 
84 class Client;
85 class EventThread;
86 class HWComposer;
87 class IGraphicBufferProducer;
88 class IInputFlinger;
89 class InjectVSyncSource;
90 class Layer;
91 class MessageBase;
92 class RefreshRateOverlay;
93 class RegionSamplingThread;
94 class TimeStats;
95 
96 namespace compositionengine {
97 class DisplaySurface;
98 } // namespace compositionengine
99 
100 namespace renderengine {
101 class RenderEngine;
102 } // namespace renderengine
103 
104 namespace dvr {
105 class VrFlinger;
106 } // namespace dvr
107 
108 enum {
109     eTransactionNeeded = 0x01,
110     eTraversalNeeded = 0x02,
111     eDisplayTransactionNeeded = 0x04,
112     eDisplayLayerStackChanged = 0x08,
113     eTransactionFlushNeeded = 0x10,
114     eTransactionMask = 0x1f,
115 };
116 
117 enum class DisplayColorSetting : int32_t {
118     MANAGED = 0,
119     UNMANAGED = 1,
120     ENHANCED = 2,
121 };
122 
123 class SurfaceFlingerBE
124 {
125 public:
126     SurfaceFlingerBE();
127 
128     const std::string mHwcServiceName; // "default" for real use, something else for testing.
129 
130     FenceTimeline mGlCompositionDoneTimeline;
131     FenceTimeline mDisplayTimeline;
132 
133     // protected by mCompositorTimingLock;
134     mutable std::mutex mCompositorTimingLock;
135     CompositorTiming mCompositorTiming;
136 
137     // Only accessed from the main thread.
138     struct CompositePresentTime {
139         nsecs_t composite = -1;
140         std::shared_ptr<FenceTime> display = FenceTime::NO_FENCE;
141     };
142     std::queue<CompositePresentTime> mCompositePresentTimes;
143 
144     static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
145     nsecs_t mFrameBuckets[NUM_BUCKETS] = {};
146     nsecs_t mTotalTime = 0;
147     std::atomic<nsecs_t> mLastSwapTime = 0;
148 
149     // Double- vs. triple-buffering stats
150     struct BufferingStats {
151         size_t numSegments = 0;
152         nsecs_t totalTime = 0;
153 
154         // "Two buffer" means that a third buffer was never used, whereas
155         // "double-buffered" means that on average the segment only used two
156         // buffers (though it may have used a third for some part of the
157         // segment)
158         nsecs_t twoBufferTime = 0;
159         nsecs_t doubleBufferedTime = 0;
160         nsecs_t tripleBufferedTime = 0;
161     };
162     mutable Mutex mBufferingStatsMutex;
163     std::unordered_map<std::string, BufferingStats> mBufferingStats;
164 
165     // The composer sequence id is a monotonically increasing integer that we
166     // use to differentiate callbacks from different hardware composer
167     // instances. Each hardware composer instance gets a different sequence id.
168     int32_t mComposerSequenceId = 0;
169 };
170 
171 class SurfaceFlinger : public BnSurfaceComposer,
172                        public PriorityDumper,
173                        private IBinder::DeathRecipient,
174                        private HWC2::ComposerCallback
175 {
176 public:
getBE()177     SurfaceFlingerBE& getBE() { return mBE; }
getBE()178     const SurfaceFlingerBE& getBE() const { return mBE; }
179 
180     // This is the phase offset in nanoseconds of the software vsync event
181     // relative to the vsync event reported by HWComposer.  The software vsync
182     // event is when SurfaceFlinger and Choreographer-based applications run each
183     // frame.
184     //
185     // This phase offset allows adjustment of the minimum latency from application
186     // wake-up time (by Choreographer) to the time at which the resulting window
187     // image is displayed.  This value may be either positive (after the HW vsync)
188     // or negative (before the HW vsync). Setting it to 0 will result in a lower
189     // latency bound of two vsync periods because the app and SurfaceFlinger
190     // will run just after the HW vsync.  Setting it to a positive number will
191     // result in the minimum latency being:
192     //
193     //     (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
194     //
195     // Note that reducing this latency makes it more likely for the applications
196     // to not have their window content image ready in time.  When this happens
197     // the latency will end up being an additional vsync period, and animations
198     // will hiccup.  Therefore, this latency should be tuned somewhat
199     // conservatively (or at least with awareness of the trade-off being made).
200     static int64_t vsyncPhaseOffsetNs;
201     static int64_t sfVsyncPhaseOffsetNs;
202 
203     // If fences from sync Framework are supported.
204     static bool hasSyncFramework;
205 
206     // The offset in nanoseconds to use when DispSync timestamps present fence
207     // signaling time.
208     static int64_t dispSyncPresentTimeOffset;
209 
210     // Some hardware can do RGB->YUV conversion more efficiently in hardware
211     // controlled by HWC than in hardware controlled by the video encoder.
212     // This instruct VirtualDisplaySurface to use HWC for such conversion on
213     // GL composition.
214     static bool useHwcForRgbToYuv;
215 
216     // Maximum dimension supported by HWC for virtual display.
217     // Equal to min(max_height, max_width).
218     static uint64_t maxVirtualDisplaySize;
219 
220     // Controls the number of buffers SurfaceFlinger will allocate for use in
221     // FramebufferSurface
222     static int64_t maxFrameBufferAcquiredBuffers;
223 
224     // Indicate if a device has wide color gamut display. This is typically
225     // found on devices with wide color gamut (e.g. Display-P3) display.
226     static bool hasWideColorDisplay;
227 
228     static int primaryDisplayOrientation;
229 
230     // Indicate if device wants color management on its display.
231     static bool useColorManagement;
232 
233     static bool useContextPriority;
234 
235     // The data space and pixel format that SurfaceFlinger expects hardware composer
236     // to composite efficiently. Meaning under most scenarios, hardware composer
237     // will accept layers with the data space and pixel format.
238     static ui::Dataspace defaultCompositionDataspace;
239     static ui::PixelFormat defaultCompositionPixelFormat;
240 
241     // The data space and pixel format that SurfaceFlinger expects hardware composer
242     // to composite efficiently for wide color gamut surfaces. Meaning under most scenarios,
243     // hardware composer will accept layers with the data space and pixel format.
244     static ui::Dataspace wideColorGamutCompositionDataspace;
245     static ui::PixelFormat wideColorGamutCompositionPixelFormat;
246 
getServiceName()247     static char const* getServiceName() ANDROID_API {
248         return "SurfaceFlinger";
249     }
250 
251     struct SkipInitializationTag {};
252     static constexpr SkipInitializationTag SkipInitialization;
253     SurfaceFlinger(surfaceflinger::Factory&, SkipInitializationTag) ANDROID_API;
254     explicit SurfaceFlinger(surfaceflinger::Factory&) ANDROID_API;
255 
256     // must be called before clients can connect
257     void init() ANDROID_API;
258 
259     // starts SurfaceFlinger main loop in the current thread
260     void run() ANDROID_API;
261 
262     // post an asynchronous message to the main thread
263     status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
264 
265     // post a synchronous message to the main thread
266     status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
267 
268     // force full composition on all displays
269     void repaintEverything();
270 
271     // force full composition on all displays without resetting the scheduler idle timer.
272     void repaintEverythingForHWC();
273 
getFactory()274     surfaceflinger::Factory& getFactory() { return mFactory; }
275 
276     // The CompositionEngine encapsulates all composition related interfaces and actions.
277     compositionengine::CompositionEngine& getCompositionEngine() const;
278 
279     // returns the default Display
getDefaultDisplayDevice()280     sp<const DisplayDevice> getDefaultDisplayDevice() {
281         Mutex::Autolock _l(mStateLock);
282         return getDefaultDisplayDeviceLocked();
283     }
284 
285     // Obtains a name from the texture pool, or, if the pool is empty, posts a
286     // synchronous message to the main thread to obtain one on the fly
287     uint32_t getNewTexture();
288 
289     // utility function to delete a texture on the main thread
290     void deleteTextureAsync(uint32_t texture);
291 
292     // enable/disable h/w composer event
293     // TODO: this should be made accessible only to EventThread
294     void setPrimaryVsyncEnabled(bool enabled);
295 
296     // called on the main thread by MessageQueue when an internal message
297     // is received
298     // TODO: this should be made accessible only to MessageQueue
299     void onMessageReceived(int32_t what);
300 
301     // for debugging only
302     // TODO: this should be made accessible only to HWComposer
303     const Vector<sp<Layer>>& getLayerSortedByZForHwcDisplay(DisplayId displayId);
304 
305     renderengine::RenderEngine& getRenderEngine() const;
306 
307     bool authenticateSurfaceTextureLocked(
308         const sp<IGraphicBufferProducer>& bufferProducer) const;
309 
onLayerCreated()310     inline void onLayerCreated() { mNumLayers++; }
onLayerDestroyed(Layer * layer)311     inline void onLayerDestroyed(Layer* layer) {
312         mNumLayers--;
313         mOffscreenLayers.erase(layer);
314     }
315 
getTransactionCompletedThread()316     TransactionCompletedThread& getTransactionCompletedThread() {
317         return mTransactionCompletedThread;
318     }
319 
320     sp<Layer> fromHandle(const sp<IBinder>& handle) REQUIRES(mStateLock);
321 
322 private:
323     friend class BufferLayer;
324     friend class BufferQueueLayer;
325     friend class BufferStateLayer;
326     friend class Client;
327     friend class Layer;
328     friend class MonitoredProducer;
329     friend class RefreshRateOverlay;
330     friend class RegionSamplingThread;
331     friend class SurfaceTracing;
332 
333     // For unit tests
334     friend class TestableSurfaceFlinger;
335 
336     // This value is specified in number of frames.  Log frame stats at most
337     // every half hour.
338     enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
339 
340     static const size_t MAX_LAYERS = 4096;
341     static const int MAX_TRACING_MEMORY = 100 * 1024 * 1024; // 100MB
342 
343     // We're reference counted, never destroy SurfaceFlinger directly
344     virtual ~SurfaceFlinger();
345 
346     /* ------------------------------------------------------------------------
347      * Internal data structures
348      */
349 
350     class State {
351     public:
State(LayerVector::StateSet set)352         explicit State(LayerVector::StateSet set) : stateSet(set), layersSortedByZ(set) {}
353         State& operator=(const State& other) {
354             // We explicitly don't copy stateSet so that, e.g., mDrawingState
355             // always uses the Drawing StateSet.
356             layersSortedByZ = other.layersSortedByZ;
357             displays = other.displays;
358             colorMatrixChanged = other.colorMatrixChanged;
359             if (colorMatrixChanged) {
360                 colorMatrix = other.colorMatrix;
361             }
362             return *this;
363         }
364 
365         const LayerVector::StateSet stateSet = LayerVector::StateSet::Invalid;
366         LayerVector layersSortedByZ;
367         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
368 
369         bool colorMatrixChanged = true;
370         mat4 colorMatrix;
371 
372         void traverseInZOrder(const LayerVector::Visitor& visitor) const;
373         void traverseInReverseZOrder(const LayerVector::Visitor& visitor) const;
374     };
375 
376     /* ------------------------------------------------------------------------
377      * IBinder interface
378      */
379     status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) override;
dump(int fd,const Vector<String16> & args)380     status_t dump(int fd, const Vector<String16>& args) override { return priorityDump(fd, args); }
381     bool callingThreadHasUnscopedSurfaceFlingerAccess() EXCLUDES(mStateLock);
382 
383     /* ------------------------------------------------------------------------
384      * ISurfaceComposer interface
385      */
386     sp<ISurfaceComposerClient> createConnection() override;
387     sp<IBinder> createDisplay(const String8& displayName, bool secure) override;
388     void destroyDisplay(const sp<IBinder>& displayToken) override;
389     std::vector<PhysicalDisplayId> getPhysicalDisplayIds() const override;
390     sp<IBinder> getPhysicalDisplayToken(PhysicalDisplayId displayId) const override;
391     void setTransactionState(const Vector<ComposerState>& state,
392                              const Vector<DisplayState>& displays, uint32_t flags,
393                              const sp<IBinder>& applyToken,
394                              const InputWindowCommands& inputWindowCommands,
395                              int64_t desiredPresentTime, const client_cache_t& uncacheBuffer,
396                              const std::vector<ListenerCallbacks>& listenerCallbacks) override;
397     void bootFinished() override;
398     bool authenticateSurfaceTexture(
399             const sp<IGraphicBufferProducer>& bufferProducer) const override;
400     status_t getSupportedFrameTimestamps(std::vector<FrameEvent>* outSupported) const override;
401     sp<IDisplayEventConnection> createDisplayEventConnection(
402             ISurfaceComposer::VsyncSource vsyncSource = eVsyncSourceApp) override;
403     status_t captureScreen(const sp<IBinder>& displayToken, sp<GraphicBuffer>* outBuffer,
404             bool& outCapturedSecureLayers, const ui::Dataspace reqDataspace,
405             const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
406             uint32_t reqWidth, uint32_t reqHeight,
407             bool useIdentityTransform, ISurfaceComposer::Rotation rotation, bool captureSecureLayers) override;
408     status_t captureScreen(uint64_t displayOrLayerStack, ui::Dataspace* outDataspace,
409                            sp<GraphicBuffer>* outBuffer) override;
410     status_t captureLayers(
411             const sp<IBinder>& parentHandle, sp<GraphicBuffer>* outBuffer,
412             const ui::Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat,
413             const Rect& sourceCrop,
414             const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& exclude,
415             float frameScale, bool childrenOnly) override;
416 
417     status_t getDisplayStats(const sp<IBinder>& displayToken, DisplayStatInfo* stats) override;
418     status_t getDisplayConfigs(const sp<IBinder>& displayToken,
419                                Vector<DisplayInfo>* configs) override;
420     int getActiveConfig(const sp<IBinder>& displayToken) override;
421     status_t getDisplayColorModes(const sp<IBinder>& displayToken,
422                                   Vector<ui::ColorMode>* configs) override;
423     status_t getDisplayNativePrimaries(const sp<IBinder>& displayToken,
424                                        ui::DisplayPrimaries &primaries);
425     ui::ColorMode getActiveColorMode(const sp<IBinder>& displayToken) override;
426     status_t setActiveColorMode(const sp<IBinder>& displayToken, ui::ColorMode colorMode) override;
427     void setPowerMode(const sp<IBinder>& displayToken, int mode) override;
428     status_t setActiveConfig(const sp<IBinder>& displayToken, int id) override;
429     status_t clearAnimationFrameStats() override;
430     status_t getAnimationFrameStats(FrameStats* outStats) const override;
431     status_t getHdrCapabilities(const sp<IBinder>& displayToken,
432                                 HdrCapabilities* outCapabilities) const override;
433     status_t enableVSyncInjections(bool enable) override;
434     status_t injectVSync(nsecs_t when) override;
435     status_t getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) override;
436     status_t getColorManagement(bool* outGetColorManagement) const override;
437     status_t getCompositionPreference(ui::Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
438                                       ui::Dataspace* outWideColorGamutDataspace,
439                                       ui::PixelFormat* outWideColorGamutPixelFormat) const override;
440     status_t getDisplayedContentSamplingAttributes(const sp<IBinder>& display,
441                                                    ui::PixelFormat* outFormat,
442                                                    ui::Dataspace* outDataspace,
443                                                    uint8_t* outComponentMask) const override;
444     status_t setDisplayContentSamplingEnabled(const sp<IBinder>& display, bool enable,
445                                               uint8_t componentMask,
446                                               uint64_t maxFrames) const override;
447     status_t getDisplayedContentSample(const sp<IBinder>& display, uint64_t maxFrames,
448                                        uint64_t timestamp,
449                                        DisplayedFrameStats* outStats) const override;
450     status_t getProtectedContentSupport(bool* outSupported) const override;
451     status_t isWideColorDisplay(const sp<IBinder>& displayToken,
452                                 bool* outIsWideColorDisplay) const override;
453     status_t addRegionSamplingListener(const Rect& samplingArea, const sp<IBinder>& stopLayerHandle,
454                                        const sp<IRegionSamplingListener>& listener) override;
455     status_t removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) override;
456     status_t setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
457                                       const std::vector<int32_t>& allowedConfigs) override;
458     status_t getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
459                                       std::vector<int32_t>* outAllowedConfigs) override;
460     status_t getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
461                                          bool* outSupport) const override;
462     status_t setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) const override;
463     status_t notifyPowerHint(int32_t hintId) override;
464 
465     /* ------------------------------------------------------------------------
466      * DeathRecipient interface
467      */
468     void binderDied(const wp<IBinder>& who) override;
469 
470     /* ------------------------------------------------------------------------
471      * RefBase interface
472      */
473     void onFirstRef() override;
474 
475     /* ------------------------------------------------------------------------
476      * HWC2::ComposerCallback / HWComposer::EventHandler interface
477      */
478     void onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
479                          int64_t timestamp) override;
480     void onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
481                            HWC2::Connection connection) override;
482     void onRefreshReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId) override;
483 
484     /* ------------------------------------------------------------------------
485      * Message handling
486      */
487     void waitForEvent();
488     // Can only be called from the main thread or with mStateLock held
489     void signalTransaction();
490     // Can only be called from the main thread or with mStateLock held
491     void signalLayerUpdate();
492     void signalRefresh();
493 
494     using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
495 
496     struct ActiveConfigInfo {
497         RefreshRateType type;
498         int configId;
499         Scheduler::ConfigEvent event;
500 
501         bool operator!=(const ActiveConfigInfo& other) const {
502             return type != other.type || configId != other.configId || event != other.event;
503         }
504     };
505 
506     // called on the main thread in response to initializeDisplays()
507     void onInitializeDisplays() REQUIRES(mStateLock);
508     // Sets the desired active config bit. It obtains the lock, and sets mDesiredActiveConfig.
509     void setDesiredActiveConfig(const ActiveConfigInfo& info) REQUIRES(mStateLock);
510     // Once HWC has returned the present fence, this sets the active config and a new refresh
511     // rate in SF. It also triggers HWC vsync.
512     void setActiveConfigInternal() REQUIRES(mStateLock);
513     // Active config is updated on INVALIDATE call in a state machine-like manner. When the
514     // desired config was set, HWC needs to update the panel on the next refresh, and when
515     // we receive the fence back, we know that the process was complete. It returns whether
516     // we need to wait for the next invalidate
517     bool performSetActiveConfig() REQUIRES(mStateLock);
518     // called on the main thread in response to setPowerMode()
519     void setPowerModeInternal(const sp<DisplayDevice>& display, int mode) REQUIRES(mStateLock);
520 
521     // called on the main thread in response to setAllowedDisplayConfigs()
522     void setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
523                                           const std::vector<int32_t>& allowedConfigs)
524             REQUIRES(mStateLock);
525 
526     // Returns whether the transaction actually modified any state
527     bool handleMessageTransaction();
528 
529     // Returns whether a new buffer has been latched (see handlePageFlip())
530     bool handleMessageInvalidate();
531 
532     void handleMessageRefresh();
533 
534     void handleTransaction(uint32_t transactionFlags);
535     void handleTransactionLocked(uint32_t transactionFlags) REQUIRES(mStateLock);
536 
537     void updateInputFlinger();
538     void updateInputWindowInfo();
539     void commitInputWindowCommands() REQUIRES(mStateLock);
540     void executeInputWindowCommands();
541     void setInputWindowsFinished();
542     void updateCursorAsync();
543 
544     /* handlePageFlip - latch a new buffer if available and compute the dirty
545      * region. Returns whether a new buffer has been latched, i.e., whether it
546      * is necessary to perform a refresh during this vsync.
547      */
548     bool handlePageFlip();
549 
550     /* ------------------------------------------------------------------------
551      * Transactions
552      */
553     void applyTransactionState(const Vector<ComposerState>& state,
554                                const Vector<DisplayState>& displays, uint32_t flags,
555                                const InputWindowCommands& inputWindowCommands,
556                                const int64_t desiredPresentTime,
557                                const client_cache_t& uncacheBuffer,
558                                const std::vector<ListenerCallbacks>& listenerCallbacks,
559                                const int64_t postTime, bool privileged, bool isMainThread = false)
560             REQUIRES(mStateLock);
561     // Returns true if at least one transaction was flushed
562     bool flushTransactionQueues();
563     // Returns true if there is at least one transaction that needs to be flushed
564     bool transactionFlushNeeded();
565     uint32_t getTransactionFlags(uint32_t flags);
566     uint32_t peekTransactionFlags();
567     // Can only be called from the main thread or with mStateLock held
568     uint32_t setTransactionFlags(uint32_t flags);
569     uint32_t setTransactionFlags(uint32_t flags, Scheduler::TransactionStart transactionStart);
570     void latchAndReleaseBuffer(const sp<Layer>& layer);
571     void commitTransaction() REQUIRES(mStateLock);
572     void commitOffscreenLayers();
573     bool containsAnyInvalidClientState(const Vector<ComposerState>& states);
574     bool transactionIsReadyToBeApplied(int64_t desiredPresentTime,
575                                        const Vector<ComposerState>& states);
576     uint32_t setClientStateLocked(const ComposerState& composerState, int64_t desiredPresentTime,
577                                   const std::vector<ListenerCallbacks>& listenerCallbacks,
578                                   int64_t postTime, bool privileged) REQUIRES(mStateLock);
579     uint32_t setDisplayStateLocked(const DisplayState& s) REQUIRES(mStateLock);
580     uint32_t addInputWindowCommands(const InputWindowCommands& inputWindowCommands)
581             REQUIRES(mStateLock);
582 
583     /* ------------------------------------------------------------------------
584      * Layer management
585      */
586     status_t createLayer(const String8& name, const sp<Client>& client, uint32_t w, uint32_t h,
587                          PixelFormat format, uint32_t flags, LayerMetadata metadata,
588                          sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp,
589                          const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer = nullptr);
590 
591     status_t createBufferQueueLayer(const sp<Client>& client, const String8& name, uint32_t w,
592                                     uint32_t h, uint32_t flags, LayerMetadata metadata,
593                                     PixelFormat& format, sp<IBinder>* outHandle,
594                                     sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
595 
596     status_t createBufferStateLayer(const sp<Client>& client, const String8& name, uint32_t w,
597                                     uint32_t h, uint32_t flags, LayerMetadata metadata,
598                                     sp<IBinder>* outHandle, sp<Layer>* outLayer);
599 
600     status_t createColorLayer(const sp<Client>& client, const String8& name, uint32_t w, uint32_t h,
601                               uint32_t flags, LayerMetadata metadata, sp<IBinder>* outHandle,
602                               sp<Layer>* outLayer);
603 
604     status_t createContainerLayer(const sp<Client>& client, const String8& name, uint32_t w,
605                                   uint32_t h, uint32_t flags, LayerMetadata metadata,
606                                   sp<IBinder>* outHandle, sp<Layer>* outLayer);
607 
608     String8 getUniqueLayerName(const String8& name);
609 
610     // called when all clients have released all their references to
611     // this layer meaning it is entirely safe to destroy all
612     // resources associated to this layer.
613     void onHandleDestroyed(sp<Layer>& layer);
614     void markLayerPendingRemovalLocked(const sp<Layer>& layer);
615 
616     // add a layer to SurfaceFlinger
617     status_t addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
618                             const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
619                             const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
620                             bool addToCurrentState);
621 
622     // Traverse through all the layers and compute and cache its bounds.
623     void computeLayerBounds();
624 
625     /* ------------------------------------------------------------------------
626      * Boot animation, on/off animations and screen capture
627      */
628 
629     void startBootAnim();
630 
631     using TraverseLayersFunction = std::function<void(const LayerVector::Visitor&)>;
632 
633     void renderScreenImplLocked(const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
634                                 ANativeWindowBuffer* buffer, bool useIdentityTransform,
635                                 int* outSyncFd);
636     status_t captureScreenCommon(RenderArea& renderArea, TraverseLayersFunction traverseLayers,
637                                  sp<GraphicBuffer>* outBuffer, const ui::PixelFormat reqPixelFormat,
638                                  bool useIdentityTransform, bool& outCapturedSecureLayers);
639     status_t captureScreenCommon(RenderArea& renderArea, TraverseLayersFunction traverseLayers,
640                                  const sp<GraphicBuffer>& buffer, bool useIdentityTransform,
641                                  bool& outCapturedSecureLayers);
642     const sp<DisplayDevice> getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack);
643     status_t captureScreenImplLocked(const RenderArea& renderArea,
644                                      TraverseLayersFunction traverseLayers,
645                                      ANativeWindowBuffer* buffer, bool useIdentityTransform,
646                                      bool forSystem, int* outSyncFd, bool& outCapturedSecureLayers);
647     void traverseLayersInDisplay(const sp<const DisplayDevice>& display,
648                                  const LayerVector::Visitor& visitor);
649 
650     sp<StartPropertySetThread> mStartPropertySetThread;
651 
652     /* ------------------------------------------------------------------------
653      * Properties
654      */
655     void readPersistentProperties();
656 
657     /* ------------------------------------------------------------------------
658      * EGL
659      */
660     size_t getMaxTextureSize() const;
661     size_t getMaxViewportDims() const;
662 
663     /* ------------------------------------------------------------------------
664      * Display and layer stack management
665      */
666     // called when starting, or restarting after system_server death
667     void initializeDisplays();
668 
getDisplayDevice(const wp<IBinder> & displayToken)669     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& displayToken) const {
670         Mutex::Autolock _l(mStateLock);
671         return getDisplayDeviceLocked(displayToken);
672     }
673 
getDisplayDevice(const wp<IBinder> & displayToken)674     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& displayToken) {
675         Mutex::Autolock _l(mStateLock);
676         return getDisplayDeviceLocked(displayToken);
677     }
678 
679     // NOTE: can only be called from the main thread or with mStateLock held
getDisplayDeviceLocked(const wp<IBinder> & displayToken)680     sp<const DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& displayToken) const {
681         return const_cast<SurfaceFlinger*>(this)->getDisplayDeviceLocked(displayToken);
682     }
683 
684     // NOTE: can only be called from the main thread or with mStateLock held
getDisplayDeviceLocked(const wp<IBinder> & displayToken)685     sp<DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& displayToken) {
686         const auto it = mDisplays.find(displayToken);
687         return it == mDisplays.end() ? nullptr : it->second;
688     }
689 
getDefaultDisplayDeviceLocked()690     sp<const DisplayDevice> getDefaultDisplayDeviceLocked() const {
691         return const_cast<SurfaceFlinger*>(this)->getDefaultDisplayDeviceLocked();
692     }
693 
getDefaultDisplayDeviceLocked()694     sp<DisplayDevice> getDefaultDisplayDeviceLocked() {
695         if (const auto token = getInternalDisplayTokenLocked()) {
696             return getDisplayDeviceLocked(token);
697         }
698         return nullptr;
699     }
700 
701     // mark a region of a layer stack dirty. this updates the dirty
702     // region of all screens presenting this layer stack.
703     void invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty);
704 
705     /* ------------------------------------------------------------------------
706      * H/W composer
707      */
708 
709     // The current hardware composer interface.
710     //
711     // The following thread safety rules apply when accessing mHwc, either
712     // directly or via getHwComposer():
713     //
714     // 1. When recreating mHwc, acquire mStateLock. We currently recreate mHwc
715     //    only when switching into and out of vr. Recreating mHwc must only be
716     //    done on the main thread.
717     //
718     // 2. When accessing mHwc on the main thread, it's not necessary to acquire
719     //    mStateLock.
720     //
721     // 3. When accessing mHwc on a thread other than the main thread, we always
722     //    need to acquire mStateLock. This is because the main thread could be
723     //    in the process of destroying the current mHwc instance.
724     //
725     // The above thread safety rules only apply to SurfaceFlinger.cpp. In
726     // SurfaceFlinger_hwc1.cpp we create mHwc at surface flinger init and never
727     // destroy it, so it's always safe to access mHwc from any thread without
728     // acquiring mStateLock.
729     HWComposer& getHwComposer() const;
730 
731     /* ------------------------------------------------------------------------
732      * Compositing
733      */
734     void invalidateHwcGeometry();
735     void computeVisibleRegions(const sp<const DisplayDevice>& display, Region& dirtyRegion,
736                                Region& opaqueRegion);
737 
738     void preComposition();
739     void postComposition();
740     void getCompositorTiming(CompositorTiming* compositorTiming);
741     void updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
742                                 std::shared_ptr<FenceTime>& presentFenceTime);
743     void setCompositorTimingSnapped(const DisplayStatInfo& stats,
744                                     nsecs_t compositeToPresentLatency);
745     void rebuildLayerStacks();
746 
747     ui::Dataspace getBestDataspace(const sp<DisplayDevice>& display, ui::Dataspace* outHdrDataSpace,
748                                    bool* outIsHdrClientComposition) const;
749 
750     // Returns the appropriate ColorMode, Dataspace and RenderIntent for the
751     // DisplayDevice. The function only returns the supported ColorMode,
752     // Dataspace and RenderIntent.
753     void pickColorMode(const sp<DisplayDevice>& display, ui::ColorMode* outMode,
754                        ui::Dataspace* outDataSpace, ui::RenderIntent* outRenderIntent) const;
755 
756     void calculateWorkingSet();
757     /*
758      * beginFrame - This function handles any pre-frame processing that needs to be
759      * prior to any CompositionInfo handling and is not dependent on data in
760      * CompositionInfo
761      */
762     void beginFrame(const sp<DisplayDevice>& display);
763     /* prepareFrame - This function will call into the DisplayDevice to prepare a
764      * frame after CompositionInfo has been programmed.   This provides a mechanism
765      * to prepare the hardware composer
766      */
767     void prepareFrame(const sp<DisplayDevice>& display);
768     void doComposition(const sp<DisplayDevice>& display, bool repainEverything);
769     void doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything);
770     void logLayerStats();
771     void doDisplayComposition(const sp<DisplayDevice>& display, const Region& dirtyRegion);
772 
773     // This fails if using GL and the surface has been destroyed. readyFence
774     // will be populated if using GL and native fence sync is supported, to
775     // signal when drawing has completed.
776     bool doComposeSurfaces(const sp<DisplayDevice>& display, const Region& debugRegionm,
777                            base::unique_fd* readyFence);
778 
779     void postFramebuffer(const sp<DisplayDevice>& display);
780     void postFrame();
781     void drawWormhole(const Region& region) const;
782 
783     /* ------------------------------------------------------------------------
784      * Display management
785      */
786     sp<DisplayDevice> setupNewDisplayDeviceInternal(
787             const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
788             const DisplayDeviceState& state,
789             const sp<compositionengine::DisplaySurface>& dispSurface,
790             const sp<IGraphicBufferProducer>& producer);
791     void processDisplayChangesLocked();
792     void processDisplayHotplugEventsLocked();
793 
794     void dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected);
795 
796     /* ------------------------------------------------------------------------
797      * VSync
798      */
799     nsecs_t getVsyncPeriod() const REQUIRES(mStateLock);
800 
801     // Sets the refresh rate by switching active configs, if they are available for
802     // the desired refresh rate.
803     void setRefreshRateTo(RefreshRateType, Scheduler::ConfigEvent event) REQUIRES(mStateLock);
804 
805     bool isDisplayConfigAllowed(int32_t configId) REQUIRES(mStateLock);
806 
807     /*
808      * Display identification
809      */
getPhysicalDisplayTokenLocked(DisplayId displayId)810     sp<IBinder> getPhysicalDisplayTokenLocked(DisplayId displayId) const {
811         const auto it = mPhysicalDisplayTokens.find(displayId);
812         return it != mPhysicalDisplayTokens.end() ? it->second : nullptr;
813     }
814 
getPhysicalDisplayIdLocked(const sp<IBinder> & displayToken)815     std::optional<DisplayId> getPhysicalDisplayIdLocked(const sp<IBinder>& displayToken) const {
816         for (const auto& [id, token] : mPhysicalDisplayTokens) {
817             if (token == displayToken) {
818                 return id;
819             }
820         }
821         return {};
822     }
823 
824     // TODO(b/74619554): Remove special cases for primary display.
getInternalDisplayTokenLocked()825     sp<IBinder> getInternalDisplayTokenLocked() const {
826         const auto displayId = getInternalDisplayIdLocked();
827         return displayId ? getPhysicalDisplayTokenLocked(*displayId) : nullptr;
828     }
829 
getInternalDisplayIdLocked()830     std::optional<DisplayId> getInternalDisplayIdLocked() const {
831         const auto hwcDisplayId = getHwComposer().getInternalHwcDisplayId();
832         return hwcDisplayId ? getHwComposer().toPhysicalDisplayId(*hwcDisplayId) : std::nullopt;
833     }
834 
835     bool previousFrameMissed();
836 
837     /*
838      * Debugging & dumpsys
839      */
840     using DumpArgs = Vector<String16>;
841     using Dumper = std::function<void(const DumpArgs&, bool asProto, std::string&)>;
842 
843     template <typename F, std::enable_if_t<!std::is_member_function_pointer_v<F>>* = nullptr>
dumper(F && dump)844     static Dumper dumper(F&& dump) {
845         using namespace std::placeholders;
846         return std::bind(std::forward<F>(dump), _3);
847     }
848 
849     template <typename F, std::enable_if_t<std::is_member_function_pointer_v<F>>* = nullptr>
dumper(F dump)850     Dumper dumper(F dump) {
851         using namespace std::placeholders;
852         return std::bind(dump, this, _3);
853     }
854 
855     template <typename F>
argsDumper(F dump)856     Dumper argsDumper(F dump) {
857         using namespace std::placeholders;
858         return std::bind(dump, this, _1, _3);
859     }
860 
861     template <typename F>
protoDumper(F dump)862     Dumper protoDumper(F dump) {
863         using namespace std::placeholders;
864         return std::bind(dump, this, _1, _2, _3);
865     }
866 
867     void dumpAllLocked(const DumpArgs& args, std::string& result) const REQUIRES(mStateLock);
868 
869     void appendSfConfigString(std::string& result) const;
870     void listLayersLocked(std::string& result) const;
871     void dumpStatsLocked(const DumpArgs& args, std::string& result) const REQUIRES(mStateLock);
872     void clearStatsLocked(const DumpArgs& args, std::string& result);
873     void dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const;
874     void logFrameStats();
875 
876     void dumpVSync(std::string& result) const REQUIRES(mStateLock);
877     void dumpStaticScreenStats(std::string& result) const;
878     // Not const because each Layer needs to query Fences and cache timestamps.
879     void dumpFrameEventsLocked(std::string& result);
880 
881     void recordBufferingStats(const char* layerName,
882             std::vector<OccupancyTracker::Segment>&& history);
883     void dumpBufferingStats(std::string& result) const;
884     void dumpDisplayIdentificationData(std::string& result) const;
885     void dumpWideColorInfo(std::string& result) const;
886     LayersProto dumpProtoInfo(LayerVector::StateSet stateSet,
887                               uint32_t traceFlags = SurfaceTracing::TRACE_ALL) const;
888     void withTracingLock(std::function<void()> operation) REQUIRES(mStateLock);
889     LayersProto dumpVisibleLayersProtoInfo(const sp<DisplayDevice>& display) const;
890 
isLayerTripleBufferingDisabled()891     bool isLayerTripleBufferingDisabled() const {
892         return this->mLayerTripleBufferingDisabled;
893     }
894 
895     status_t doDump(int fd, const DumpArgs& args, bool asProto);
896 
897     status_t dumpCritical(int fd, const DumpArgs&, bool asProto);
898 
dumpAll(int fd,const DumpArgs & args,bool asProto)899     status_t dumpAll(int fd, const DumpArgs& args, bool asProto) override {
900         return doDump(fd, args, asProto);
901     }
902 
903     /* ------------------------------------------------------------------------
904      * VrFlinger
905      */
906     void resetDisplayState();
907 
908     // Check to see if we should handoff to vr flinger.
909     void updateVrFlinger();
910 
911     void updateColorMatrixLocked();
912 
913     /* ------------------------------------------------------------------------
914      * Attributes
915      */
916 
917     surfaceflinger::Factory& mFactory;
918 
919     // access must be protected by mStateLock
920     mutable Mutex mStateLock;
921     State mCurrentState{LayerVector::StateSet::Current};
922     std::atomic<int32_t> mTransactionFlags = 0;
923     Condition mTransactionCV;
924     bool mTransactionPending = false;
925     bool mAnimTransactionPending = false;
926     SortedVector<sp<Layer>> mLayersPendingRemoval;
927     bool mTraversalNeededMainThread = false;
928 
929     // guards access to the mDrawing state if tracing is enabled.
930     mutable std::mutex mDrawingStateLock;
931 
932     // global color transform states
933     Daltonizer mDaltonizer;
934     float mGlobalSaturationFactor = 1.0f;
935     mat4 mClientColorMatrix;
936 
937     // Can't be unordered_set because wp<> isn't hashable
938     std::set<wp<IBinder>> mGraphicBufferProducerList;
939     size_t mMaxGraphicBufferProducerListSize = MAX_LAYERS;
940 
941     // protected by mStateLock (but we could use another lock)
942     bool mLayersRemoved = false;
943     bool mLayersAdded = false;
944 
945     std::atomic<bool> mRepaintEverything = false;
946 
947     // constant members (no synchronization needed for access)
948     const nsecs_t mBootTime = systemTime();
949     bool mGpuToCpuSupported = false;
950     std::unique_ptr<EventThread> mInjectorEventThread;
951     std::unique_ptr<InjectVSyncSource> mVSyncInjector;
952 
953     // Calculates correct offsets.
954     VSyncModulator mVsyncModulator;
955     // Keeps track of all available phase offsets for different refresh types.
956     const std::unique_ptr<scheduler::PhaseOffsets> mPhaseOffsets;
957 
958     // Can only accessed from the main thread, these members
959     // don't need synchronization
960     State mDrawingState{LayerVector::StateSet::Drawing};
961     bool mVisibleRegionsDirty = false;
962     // Set during transaction commit stage to track if the input info for a layer has changed.
963     bool mInputInfoChanged = false;
964     bool mGeometryInvalid = false;
965     bool mAnimCompositionPending = false;
966     std::vector<sp<Layer>> mLayersWithQueuedFrames;
967     // Tracks layers that need to update a display's dirty region.
968     std::vector<sp<Layer>> mLayersPendingRefresh;
969     std::array<sp<Fence>, 2> mPreviousPresentFences = {Fence::NO_FENCE, Fence::NO_FENCE};
970     // True if in the previous frame at least one layer was composed via the GPU.
971     bool mHadClientComposition = false;
972     // True if in the previous frame at least one layer was composed via HW Composer.
973     // Note that it is possible for a frame to be composed via both client and device
974     // composition, for example in the case of overlays.
975     bool mHadDeviceComposition = false;
976 
977     enum class BootStage {
978         BOOTLOADER,
979         BOOTANIMATION,
980         FINISHED,
981     };
982     BootStage mBootStage = BootStage::BOOTLOADER;
983 
984     struct HotplugEvent {
985         hwc2_display_t hwcDisplayId;
986         HWC2::Connection connection = HWC2::Connection::Invalid;
987     };
988     // protected by mStateLock
989     std::vector<HotplugEvent> mPendingHotplugEvents;
990 
991     // this may only be written from the main thread with mStateLock held
992     // it may be read from other threads with mStateLock held
993     std::map<wp<IBinder>, sp<DisplayDevice>> mDisplays;
994     std::unordered_map<DisplayId, sp<IBinder>> mPhysicalDisplayTokens;
995 
996     // protected by mStateLock
997     std::unordered_map<BBinder*, wp<Layer>> mLayersByLocalBinderToken;
998 
999     // don't use a lock for these, we don't care
1000     int mDebugRegion = 0;
1001     bool mDebugDisableHWC = false;
1002     bool mDebugDisableTransformHint = false;
1003     volatile nsecs_t mDebugInTransaction = 0;
1004     bool mForceFullDamage = false;
1005     bool mPropagateBackpressure = true;
1006     bool mPropagateBackpressureClientComposition = false;
1007     std::unique_ptr<SurfaceInterceptor> mInterceptor;
1008     SurfaceTracing mTracing{*this};
1009     bool mTracingEnabled = false;
1010     bool mTracingEnabledChanged GUARDED_BY(mStateLock) = false;
1011     LayerStats mLayerStats;
1012     const std::shared_ptr<TimeStats> mTimeStats;
1013     bool mUseHwcVirtualDisplays = false;
1014     std::atomic<uint32_t> mFrameMissedCount = 0;
1015     std::atomic<uint32_t> mHwcFrameMissedCount = 0;
1016     std::atomic<uint32_t> mGpuFrameMissedCount = 0;
1017 
1018     TransactionCompletedThread mTransactionCompletedThread;
1019 
1020     // Restrict layers to use two buffers in their bufferqueues.
1021     bool mLayerTripleBufferingDisabled = false;
1022 
1023     // these are thread safe
1024     std::unique_ptr<MessageQueue> mEventQueue;
1025     FrameTracker mAnimFrameTracker;
1026 
1027     // protected by mDestroyedLayerLock;
1028     mutable Mutex mDestroyedLayerLock;
1029     Vector<Layer const *> mDestroyedLayers;
1030 
1031     nsecs_t mRefreshStartTime = 0;
1032 
1033     std::atomic<bool> mRefreshPending = false;
1034 
1035     // We maintain a pool of pre-generated texture names to hand out to avoid
1036     // layer creation needing to run on the main thread (which it would
1037     // otherwise need to do to access RenderEngine).
1038     std::mutex mTexturePoolMutex;
1039     uint32_t mTexturePoolSize = 0;
1040     std::vector<uint32_t> mTexturePool;
1041 
1042     struct IBinderHash {
operatorIBinderHash1043         std::size_t operator()(const sp<IBinder>& strongPointer) const {
1044             return std::hash<IBinder*>{}(strongPointer.get());
1045         }
1046     };
1047     struct TransactionState {
TransactionStateTransactionState1048         TransactionState(const Vector<ComposerState>& composerStates,
1049                          const Vector<DisplayState>& displayStates, uint32_t transactionFlags,
1050                          int64_t desiredPresentTime, const client_cache_t& uncacheBuffer,
1051                          const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
1052                          bool privileged)
1053               : states(composerStates),
1054                 displays(displayStates),
1055                 flags(transactionFlags),
1056                 desiredPresentTime(desiredPresentTime),
1057                 buffer(uncacheBuffer),
1058                 callback(listenerCallbacks),
1059                 postTime(postTime),
1060                 privileged(privileged) {}
1061 
1062         Vector<ComposerState> states;
1063         Vector<DisplayState> displays;
1064         uint32_t flags;
1065         const int64_t desiredPresentTime;
1066         client_cache_t buffer;
1067         std::vector<ListenerCallbacks> callback;
1068         const int64_t postTime;
1069         bool privileged;
1070     };
1071     std::unordered_map<sp<IBinder>, std::queue<TransactionState>, IBinderHash> mTransactionQueues;
1072 
1073     /* ------------------------------------------------------------------------
1074      * Feature prototyping
1075      */
1076 
1077     bool mInjectVSyncs = false;
1078 
1079     // Static screen stats
1080     bool mHasPoweredOff = false;
1081 
1082     size_t mNumLayers = 0;
1083 
1084     // Verify that transaction is being called by an approved process:
1085     // either AID_GRAPHICS or AID_SYSTEM.
1086     status_t CheckTransactCodeCredentials(uint32_t code);
1087 
1088     std::unique_ptr<dvr::VrFlinger> mVrFlinger;
1089     std::atomic<bool> mVrFlingerRequestsDisplay = false;
1090     static bool useVrFlinger;
1091     std::thread::id mMainThreadId = std::this_thread::get_id();
1092 
1093     DisplayColorSetting mDisplayColorSetting = DisplayColorSetting::ENHANCED;
1094 
1095     // Color mode forced by setting persist.sys.sf.color_mode, it must:
1096     //     1. not be NATIVE color mode, NATIVE color mode means no forced color mode;
1097     //     2. be one of the supported color modes returned by hardware composer, otherwise
1098     //        it will not be respected.
1099     // persist.sys.sf.color_mode will only take effect when persist.sys.sf.native_mode
1100     // is not set to 1.
1101     // This property can be used to force SurfaceFlinger to always pick a certain color mode.
1102     ui::ColorMode mForceColorMode = ui::ColorMode::NATIVE;
1103 
1104     ui::Dataspace mDefaultCompositionDataspace;
1105     ui::Dataspace mWideColorGamutCompositionDataspace;
1106 
1107     SurfaceFlingerBE mBE;
1108     std::unique_ptr<compositionengine::CompositionEngine> mCompositionEngine;
1109 
1110     /* ------------------------------------------------------------------------
1111      * Scheduler
1112      */
1113     bool mUseSmart90ForVideo = false;
1114     std::unique_ptr<Scheduler> mScheduler;
1115     sp<Scheduler::ConnectionHandle> mAppConnectionHandle;
1116     sp<Scheduler::ConnectionHandle> mSfConnectionHandle;
1117 
1118     scheduler::RefreshRateConfigs mRefreshRateConfigs;
1119     scheduler::RefreshRateStats mRefreshRateStats{mRefreshRateConfigs, *mTimeStats};
1120 
1121     // All configs are allowed if the set is empty.
1122     using DisplayConfigs = std::set<int32_t>;
1123     DisplayConfigs mAllowedDisplayConfigs GUARDED_BY(mStateLock);
1124 
1125     std::mutex mActiveConfigLock;
1126     // This bit is set once we start setting the config. We read from this bit during the
1127     // process. If at the end, this bit is different than mDesiredActiveConfig, we restart
1128     // the process.
1129     ActiveConfigInfo mUpcomingActiveConfig; // Always read and written on the main thread.
1130     // This bit can be set at any point in time when the system wants the new config.
1131     ActiveConfigInfo mDesiredActiveConfig GUARDED_BY(mActiveConfigLock);
1132 
1133     // below flags are set by main thread only
1134     bool mDesiredActiveConfigChanged GUARDED_BY(mActiveConfigLock) = false;
1135     bool mCheckPendingFence = false;
1136 
1137     bool mLumaSampling = true;
1138     sp<RegionSamplingThread> mRegionSamplingThread;
1139     ui::DisplayPrimaries mInternalDisplayPrimaries;
1140 
1141     sp<IInputFlinger> mInputFlinger;
1142     InputWindowCommands mPendingInputWindowCommands GUARDED_BY(mStateLock);
1143     // Should only be accessed by the main thread.
1144     InputWindowCommands mInputWindowCommands;
1145 
1146     struct SetInputWindowsListener : BnSetInputWindowsListener {
SetInputWindowsListenerSetInputWindowsListener1147         explicit SetInputWindowsListener(sp<SurfaceFlinger> flinger)
1148               : mFlinger(std::move(flinger)) {}
1149 
1150         void onSetInputWindowsFinished() override;
1151 
1152         const sp<SurfaceFlinger> mFlinger;
1153     };
1154 
1155     const sp<SetInputWindowsListener> mSetInputWindowsListener = new SetInputWindowsListener(this);
1156 
1157     bool mPendingSyncInputWindows GUARDED_BY(mStateLock);
1158     Hwc2::impl::PowerAdvisor mPowerAdvisor;
1159 
1160     std::unique_ptr<RefreshRateOverlay> mRefreshRateOverlay;
1161 
1162     // Flag used to set override allowed display configs from backdoor
1163     bool mDebugDisplayConfigSetByBackdoor = false;
1164 
1165     // A set of layers that have no parent so they are not drawn on screen.
1166     // Should only be accessed by the main thread.
1167     // The Layer pointer is removed from the set when the destructor is called so there shouldn't
1168     // be any issues with a raw pointer referencing an invalid object.
1169     std::unordered_set<Layer*> mOffscreenLayers;
1170 };
1171 
1172 } // namespace android
1173