• 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  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #pragma once
17 
18 #include <sys/types.h>
19 
20 /*
21  * NOTE: Make sure this file doesn't include  anything from <gl/ > or <gl2/ >
22  */
23 
24 #include <android-base/thread_annotations.h>
25 #include <android/gui/BnSurfaceComposer.h>
26 #include <android/gui/DisplayStatInfo.h>
27 #include <android/gui/DisplayState.h>
28 #include <android/gui/ISurfaceComposerClient.h>
29 #include <cutils/atomic.h>
30 #include <cutils/compiler.h>
31 #include <ftl/algorithm.h>
32 #include <ftl/future.h>
33 #include <ftl/non_null.h>
34 #include <gui/BufferQueue.h>
35 #include <gui/CompositorTiming.h>
36 #include <gui/FrameTimestamps.h>
37 #include <gui/ISurfaceComposer.h>
38 #include <gui/ITransactionCompletedListener.h>
39 #include <gui/LayerDebugInfo.h>
40 #include <gui/LayerState.h>
41 #include <layerproto/LayerProtoHeader.h>
42 #include <math/mat4.h>
43 #include <renderengine/LayerSettings.h>
44 #include <serviceutils/PriorityDumper.h>
45 #include <system/graphics.h>
46 #include <ui/DisplayMap.h>
47 #include <ui/FenceTime.h>
48 #include <ui/PixelFormat.h>
49 #include <ui/Size.h>
50 #include <utils/Errors.h>
51 #include <utils/KeyedVector.h>
52 #include <utils/RefBase.h>
53 #include <utils/SortedVector.h>
54 #include <utils/Trace.h>
55 #include <utils/threads.h>
56 
57 #include <compositionengine/OutputColorSetting.h>
58 #include <scheduler/Fps.h>
59 #include <scheduler/PresentLatencyTracker.h>
60 #include <scheduler/Time.h>
61 #include <scheduler/TransactionSchedule.h>
62 #include <scheduler/interface/CompositionCoverage.h>
63 #include <scheduler/interface/ICompositor.h>
64 #include <ui/FenceResult.h>
65 
66 #include "Display/PhysicalDisplay.h"
67 #include "DisplayDevice.h"
68 #include "DisplayHardware/HWC2.h"
69 #include "DisplayHardware/PowerAdvisor.h"
70 #include "DisplayIdGenerator.h"
71 #include "Effects/Daltonizer.h"
72 #include "FlagManager.h"
73 #include "FrontEnd/DisplayInfo.h"
74 #include "FrontEnd/LayerCreationArgs.h"
75 #include "FrontEnd/LayerLifecycleManager.h"
76 #include "FrontEnd/LayerSnapshot.h"
77 #include "FrontEnd/LayerSnapshotBuilder.h"
78 #include "FrontEnd/TransactionHandler.h"
79 #include "LayerVector.h"
80 #include "Scheduler/ISchedulerCallback.h"
81 #include "Scheduler/RefreshRateSelector.h"
82 #include "Scheduler/RefreshRateStats.h"
83 #include "Scheduler/Scheduler.h"
84 #include "SurfaceFlingerFactory.h"
85 #include "ThreadContext.h"
86 #include "Tracing/LayerTracing.h"
87 #include "Tracing/TransactionTracing.h"
88 #include "TransactionCallbackInvoker.h"
89 #include "TransactionState.h"
90 
91 #include <atomic>
92 #include <cstdint>
93 #include <functional>
94 #include <map>
95 #include <memory>
96 #include <mutex>
97 #include <optional>
98 #include <queue>
99 #include <set>
100 #include <string>
101 #include <thread>
102 #include <type_traits>
103 #include <unordered_map>
104 #include <unordered_set>
105 #include <utility>
106 #include <vector>
107 
108 #include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
109 #include <aidl/android/hardware/graphics/composer3/RefreshRateChangedDebugData.h>
110 #include "Client.h"
111 
112 using namespace android::surfaceflinger;
113 
114 namespace android {
115 
116 class EventThread;
117 class FlagManager;
118 class FpsReporter;
119 class TunnelModeEnabledReporter;
120 class HdrLayerInfoReporter;
121 class HWComposer;
122 class IGraphicBufferProducer;
123 class Layer;
124 class MessageBase;
125 class RefreshRateOverlay;
126 class RegionSamplingThread;
127 class RenderArea;
128 class TimeStats;
129 class FrameTracer;
130 class ScreenCapturer;
131 class WindowInfosListenerInvoker;
132 
133 using ::aidl::android::hardware::graphics::composer3::RefreshRateChangedDebugData;
134 using frontend::TransactionHandler;
135 using gui::CaptureArgs;
136 using gui::DisplayCaptureArgs;
137 using gui::IRegionSamplingListener;
138 using gui::LayerCaptureArgs;
139 using gui::ScreenCaptureResults;
140 
141 namespace frametimeline {
142 class FrameTimeline;
143 }
144 
145 namespace os {
146     class IInputFlinger;
147 }
148 
149 namespace compositionengine {
150 class DisplaySurface;
151 class OutputLayer;
152 
153 struct CompositionRefreshArgs;
154 } // namespace compositionengine
155 
156 namespace renderengine {
157 class RenderEngine;
158 } // namespace renderengine
159 
160 enum {
161     eTransactionNeeded = 0x01,
162     eTraversalNeeded = 0x02,
163     eDisplayTransactionNeeded = 0x04,
164     eTransformHintUpdateNeeded = 0x08,
165     eTransactionFlushNeeded = 0x10,
166     eInputInfoUpdateNeeded = 0x20,
167     eTransactionMask = 0x3f,
168 };
169 
170 // Latch Unsignaled buffer behaviours
171 enum class LatchUnsignaledConfig {
172     // All buffers are latched signaled.
173     Disabled,
174 
175     // Latch unsignaled is permitted when a single layer is updated in a frame,
176     // and the update includes just a buffer update (i.e. no sync transactions
177     // or geometry changes).
178     // Latch unsignaled is also only permitted when a single transaction is ready
179     // to be applied. If we pass an unsignaled fence to HWC, HWC might miss presenting
180     // the frame if the fence does not fire in time. If we apply another transaction,
181     // we may penalize the other transaction unfairly.
182     AutoSingleLayer,
183 
184     // All buffers are latched unsignaled. This behaviour is discouraged as it
185     // can break sync transactions, stall the display and cause undesired side effects.
186     // This is equivalent to ignoring the acquire fence when applying transactions.
187     Always,
188 };
189 
190 using DisplayColorSetting = compositionengine::OutputColorSetting;
191 
192 class SurfaceFlinger : public BnSurfaceComposer,
193                        public PriorityDumper,
194                        private IBinder::DeathRecipient,
195                        private HWC2::ComposerCallback,
196                        private ICompositor,
197                        private scheduler::ISchedulerCallback,
198                        private compositionengine::ICEPowerCallback {
199 public:
200     struct SkipInitializationTag {};
201 
202     SurfaceFlinger(surfaceflinger::Factory&, SkipInitializationTag) ANDROID_API;
203     explicit SurfaceFlinger(surfaceflinger::Factory&) ANDROID_API;
204 
205     // set main thread scheduling policy
206     static status_t setSchedFifo(bool enabled) ANDROID_API;
207 
208     // set main thread scheduling attributes
209     static status_t setSchedAttr(bool enabled);
210 
getServiceName()211     static char const* getServiceName() ANDROID_API { return "SurfaceFlinger"; }
212 
213     // If fences from sync Framework are supported.
214     static bool hasSyncFramework;
215 
216     // The offset in nanoseconds to use when VsyncController timestamps present fence
217     // signaling time.
218     static int64_t dispSyncPresentTimeOffset;
219 
220     // Some hardware can do RGB->YUV conversion more efficiently in hardware
221     // controlled by HWC than in hardware controlled by the video encoder.
222     // This instruct VirtualDisplaySurface to use HWC for such conversion on
223     // GL composition.
224     static bool useHwcForRgbToYuv;
225 
226     // Controls the number of buffers SurfaceFlinger will allocate for use in
227     // FramebufferSurface
228     static int64_t maxFrameBufferAcquiredBuffers;
229 
230     // Controls the maximum width and height in pixels that the graphics pipeline can support for
231     // GPU fallback composition. For example, 8k devices with 4k GPUs, or 4k devices with 2k GPUs.
232     static uint32_t maxGraphicsWidth;
233     static uint32_t maxGraphicsHeight;
234 
235     // Indicate if device wants color management on its display.
236     static const constexpr bool useColorManagement = true;
237 
238     static bool useContextPriority;
239 
240     // The data space and pixel format that SurfaceFlinger expects hardware composer
241     // to composite efficiently. Meaning under most scenarios, hardware composer
242     // will accept layers with the data space and pixel format.
243     static ui::Dataspace defaultCompositionDataspace;
244     static ui::PixelFormat defaultCompositionPixelFormat;
245 
246     // The data space and pixel format that SurfaceFlinger expects hardware composer
247     // to composite efficiently for wide color gamut surfaces. Meaning under most scenarios,
248     // hardware composer will accept layers with the data space and pixel format.
249     static ui::Dataspace wideColorGamutCompositionDataspace;
250     static ui::PixelFormat wideColorGamutCompositionPixelFormat;
251 
252     static constexpr SkipInitializationTag SkipInitialization;
253 
254     static LatchUnsignaledConfig enableLatchUnsignaledConfig;
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     // Indicates frame activity, i.e. whether commit and/or composite is taking place.
263     enum class FrameHint { kNone, kActive };
264 
265     // Schedule commit of transactions on the main thread ahead of the next VSYNC.
266     void scheduleCommit(FrameHint);
267     // As above, but also force composite regardless if transactions were committed.
268     void scheduleComposite(FrameHint);
269     // As above, but also force dirty geometry to repaint.
270     void scheduleRepaint();
271     // Schedule sampling independently from commit or composite.
272     void scheduleSample();
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     // Obtains a name from the texture pool, or, if the pool is empty, posts a
280     // synchronous message to the main thread to obtain one on the fly
281     uint32_t getNewTexture();
282 
283     // utility function to delete a texture on the main thread
284     void deleteTextureAsync(uint32_t texture);
285 
286     renderengine::RenderEngine& getRenderEngine() const;
287 
288     void onLayerFirstRef(Layer*);
289     void onLayerDestroyed(Layer*);
290     void onLayerUpdate();
291 
292     void removeHierarchyFromOffscreenLayers(Layer* layer);
293     void removeFromOffscreenLayers(Layer* layer);
294 
295     // Called when all clients have released all their references to
296     // this layer. The layer may still be kept alive by its parents but
297     // the client can no longer modify this layer directly.
298     void onHandleDestroyed(BBinder* handle, sp<Layer>& layer, uint32_t layerId);
299 
300     std::vector<Layer*> mLayerMirrorRoots;
301 
getTransactionCallbackInvoker()302     TransactionCallbackInvoker& getTransactionCallbackInvoker() {
303         return mTransactionCallbackInvoker;
304     }
305 
306     // If set, disables reusing client composition buffers. This can be set by
307     // debug.sf.disable_client_composition_cache
308     bool mDisableClientCompositionCache = false;
309 
310     // Disables expensive rendering for all displays
311     // This is scheduled on the main thread
312     void disableExpensiveRendering();
313     FloatRect getMaxDisplayBounds();
314 
315     // If set, composition engine tries to predict the composition strategy provided by HWC
316     // based on the previous frame. If the strategy can be predicted, gpu composition will
317     // run parallel to the hwc validateDisplay call and re-run if the predition is incorrect.
318     bool mPredictCompositionStrategy = false;
319 
320     // If true, then any layer with a SMPTE 170M transfer function is decoded using the sRGB
321     // transfer instead. This is mainly to preserve legacy behavior, where implementations treated
322     // SMPTE 170M as sRGB prior to color management being implemented, and now implementations rely
323     // on this behavior to increase contrast for some media sources.
324     bool mTreat170mAsSrgb = false;
325 
326     // If true, then screenshots with an enhanced render intent will dim in gamma space.
327     // The purpose is to ensure that screenshots appear correct during system animations for devices
328     // that require that dimming must occur in gamma space.
329     bool mDimInGammaSpaceForEnhancedScreenshots = false;
330 
331     // Allows to ignore physical orientation provided through hwc API in favour of
332     // 'ro.surface_flinger.primary_display_orientation'.
333     // TODO(b/246793311): Clean up a temporary property
334     bool mIgnoreHwcPhysicalDisplayOrientation = false;
335 
336     void forceFutureUpdate(int delayInMs);
337     const DisplayDevice* getDisplayFromLayerStack(ui::LayerStack)
338             REQUIRES(mStateLock, kMainThreadContext);
339 
340     // TODO (b/259407931): Remove.
341     // TODO (b/281857977): This should be annotated with REQUIRES(kMainThreadContext), but this
342     // would require thread safety annotations throughout the frontend (in particular Layer and
343     // LayerFE).
getActiveDisplayRotationFlags()344     static ui::Transform::RotationFlags getActiveDisplayRotationFlags() {
345         return sActiveDisplayRotationFlags;
346     }
347 
348 protected:
349     // We're reference counted, never destroy SurfaceFlinger directly
350     virtual ~SurfaceFlinger();
351 
352     virtual void processDisplayAdded(const wp<IBinder>& displayToken, const DisplayDeviceState&)
353             REQUIRES(mStateLock);
354 
355     virtual std::shared_ptr<renderengine::ExternalTexture> getExternalTextureFromBufferData(
356             BufferData& bufferData, const char* layerName, uint64_t transactionId);
357 
358     // Returns true if any display matches a `bool(const DisplayDevice&)` predicate.
359     template <typename Predicate>
hasDisplay(Predicate p)360     bool hasDisplay(Predicate p) const REQUIRES(mStateLock) {
361         return static_cast<bool>(findDisplay(p));
362     }
363 
exceedsMaxRenderTargetSize(uint32_t width,uint32_t height)364     bool exceedsMaxRenderTargetSize(uint32_t width, uint32_t height) const {
365         return width > mMaxRenderTargetSize || height > mMaxRenderTargetSize;
366     }
367 
368 private:
369     friend class BufferLayer;
370     friend class Client;
371     friend class FpsReporter;
372     friend class TunnelModeEnabledReporter;
373     friend class Layer;
374     friend class RefreshRateOverlay;
375     friend class RegionSamplingThread;
376     friend class LayerRenderArea;
377     friend class LayerTracing;
378     friend class SurfaceComposerAIDL;
379     friend class DisplayRenderArea;
380 
381     // For unit tests
382     friend class TestableSurfaceFlinger;
383     friend class TransactionApplicationTest;
384     friend class TunnelModeEnabledReporterTest;
385 
386     using TransactionSchedule = scheduler::TransactionSchedule;
387     using GetLayerSnapshotsFunction = std::function<std::vector<std::pair<Layer*, sp<LayerFE>>>()>;
388     using RenderAreaFuture = ftl::Future<std::unique_ptr<RenderArea>>;
389     using DumpArgs = Vector<String16>;
390     using Dumper = std::function<void(const DumpArgs&, bool asProto, std::string&)>;
391 
392     class State {
393     public:
State(LayerVector::StateSet set)394         explicit State(LayerVector::StateSet set) : stateSet(set), layersSortedByZ(set) {}
395         State& operator=(const State& other) {
396             // We explicitly don't copy stateSet so that, e.g., mDrawingState
397             // always uses the Drawing StateSet.
398             layersSortedByZ = other.layersSortedByZ;
399             displays = other.displays;
400             colorMatrixChanged = other.colorMatrixChanged;
401             if (colorMatrixChanged) {
402                 colorMatrix = other.colorMatrix;
403             }
404             globalShadowSettings = other.globalShadowSettings;
405 
406             return *this;
407         }
408 
409         const LayerVector::StateSet stateSet = LayerVector::StateSet::Invalid;
410         LayerVector layersSortedByZ;
411 
412         // TODO(b/241285876): Replace deprecated DefaultKeyedVector with ftl::SmallMap.
413         DefaultKeyedVector<wp<IBinder>, DisplayDeviceState> displays;
414 
getDisplayIndex(PhysicalDisplayId displayId)415         std::optional<size_t> getDisplayIndex(PhysicalDisplayId displayId) const {
416             for (size_t i = 0; i < displays.size(); i++) {
417                 const auto& state = displays.valueAt(i);
418                 if (state.physical && state.physical->id == displayId) {
419                     return i;
420                 }
421             }
422 
423             return {};
424         }
425 
426         bool colorMatrixChanged = true;
427         mat4 colorMatrix;
428 
429         renderengine::ShadowSettings globalShadowSettings;
430 
431         void traverse(const LayerVector::Visitor& visitor) const;
432         void traverseInZOrder(const LayerVector::Visitor& visitor) const;
433         void traverseInReverseZOrder(const LayerVector::Visitor& visitor) const;
434     };
435 
436     // Keeps track of pending buffers per layer handle in the transaction queue or current/drawing
437     // state before the buffers are latched. The layer owns the atomic counters and decrements the
438     // count in the main thread when dropping or latching a buffer.
439     //
440     // The binder threads increment the same counter when a new transaction containing a buffer is
441     // added to the transaction queue. The map is updated with the layer handle lifecycle updates.
442     // This is done to avoid lock contention with the main thread.
443     class BufferCountTracker {
444     public:
increment(BBinder * layerHandle)445         void increment(BBinder* layerHandle) {
446             std::lock_guard<std::mutex> lock(mLock);
447             auto it = mCounterByLayerHandle.find(layerHandle);
448             if (it != mCounterByLayerHandle.end()) {
449                 auto [name, pendingBuffers] = it->second;
450                 int32_t count = ++(*pendingBuffers);
451                 ATRACE_INT(name.c_str(), count);
452             } else {
453                 ALOGW("Handle not found! %p", layerHandle);
454             }
455         }
456 
add(BBinder * layerHandle,const std::string & name,std::atomic<int32_t> * counter)457         void add(BBinder* layerHandle, const std::string& name, std::atomic<int32_t>* counter) {
458             std::lock_guard<std::mutex> lock(mLock);
459             mCounterByLayerHandle[layerHandle] = std::make_pair(name, counter);
460         }
461 
remove(BBinder * layerHandle)462         void remove(BBinder* layerHandle) {
463             std::lock_guard<std::mutex> lock(mLock);
464             mCounterByLayerHandle.erase(layerHandle);
465         }
466 
467     private:
468         std::mutex mLock;
469         std::unordered_map<BBinder*, std::pair<std::string, std::atomic<int32_t>*>>
470                 mCounterByLayerHandle GUARDED_BY(mLock);
471     };
472 
473     enum class BootStage {
474         BOOTLOADER,
475         BOOTANIMATION,
476         FINISHED,
477     };
478 
479     template <typename F, std::enable_if_t<!std::is_member_function_pointer_v<F>>* = nullptr>
dumper(F && dump)480     static Dumper dumper(F&& dump) {
481         using namespace std::placeholders;
482         return std::bind(std::forward<F>(dump), _3);
483     }
484 
485     template <typename F, std::enable_if_t<std::is_member_function_pointer_v<F>>* = nullptr>
dumper(F dump)486     Dumper dumper(F dump) {
487         using namespace std::placeholders;
488         return std::bind(dump, this, _3);
489     }
490 
491     template <typename F>
argsDumper(F dump)492     Dumper argsDumper(F dump) {
493         using namespace std::placeholders;
494         return std::bind(dump, this, _1, _3);
495     }
496 
497     template <typename F>
protoDumper(F dump)498     Dumper protoDumper(F dump) {
499         using namespace std::placeholders;
500         return std::bind(dump, this, _1, _2, _3);
501     }
502 
503     // Maximum allowed number of display frames that can be set through backdoor
504     static const int MAX_ALLOWED_DISPLAY_FRAMES = 2048;
505 
506     static const size_t MAX_LAYERS = 4096;
507 
508     // Implements IBinder.
509     status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) override;
dump(int fd,const Vector<String16> & args)510     status_t dump(int fd, const Vector<String16>& args) override { return priorityDump(fd, args); }
511     bool callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache = true)
512             EXCLUDES(mStateLock);
513 
514     // Implements ISurfaceComposer
515     sp<IBinder> createDisplay(const String8& displayName, bool secure,
516                               float requestedRefreshRate = 0.0f);
517     void destroyDisplay(const sp<IBinder>& displayToken);
getPhysicalDisplayIds()518     std::vector<PhysicalDisplayId> getPhysicalDisplayIds() const EXCLUDES(mStateLock) {
519         Mutex::Autolock lock(mStateLock);
520         return getPhysicalDisplayIdsLocked();
521     }
522 
523     sp<IBinder> getPhysicalDisplayToken(PhysicalDisplayId displayId) const;
524     status_t setTransactionState(
525             const FrameTimelineInfo& frameTimelineInfo, Vector<ComposerState>& state,
526             const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
527             InputWindowCommands inputWindowCommands, int64_t desiredPresentTime,
528             bool isAutoTimestamp, const std::vector<client_cache_t>& uncacheBuffers,
529             bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
530             uint64_t transactionId, const std::vector<uint64_t>& mergedTransactionIds) override;
531     void bootFinished();
532     virtual status_t getSupportedFrameTimestamps(std::vector<FrameEvent>* outSupported) const;
533     sp<IDisplayEventConnection> createDisplayEventConnection(
534             gui::ISurfaceComposer::VsyncSource vsyncSource =
535                     gui::ISurfaceComposer::VsyncSource::eVsyncSourceApp,
536             EventRegistrationFlags eventRegistration = {},
537             const sp<IBinder>& layerHandle = nullptr);
538 
539     status_t captureDisplay(const DisplayCaptureArgs&, const sp<IScreenCaptureListener>&);
540     status_t captureDisplay(DisplayId, const sp<IScreenCaptureListener>&);
541     status_t captureLayers(const LayerCaptureArgs&, const sp<IScreenCaptureListener>&);
542 
543     status_t getDisplayStats(const sp<IBinder>& displayToken, DisplayStatInfo* stats);
544     status_t getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState*)
545             EXCLUDES(mStateLock);
546     status_t getStaticDisplayInfo(int64_t displayId, ui::StaticDisplayInfo*) EXCLUDES(mStateLock);
547     status_t getDynamicDisplayInfoFromId(int64_t displayId, ui::DynamicDisplayInfo*)
548             EXCLUDES(mStateLock);
549     status_t getDynamicDisplayInfoFromToken(const sp<IBinder>& displayToken,
550                                             ui::DynamicDisplayInfo*) EXCLUDES(mStateLock);
551     void getDynamicDisplayInfoInternal(ui::DynamicDisplayInfo*&, const sp<DisplayDevice>&,
552                                        const display::DisplaySnapshot&);
553     status_t getDisplayNativePrimaries(const sp<IBinder>& displayToken, ui::DisplayPrimaries&);
554     status_t setActiveColorMode(const sp<IBinder>& displayToken, ui::ColorMode colorMode);
555     status_t getBootDisplayModeSupport(bool* outSupport) const;
556     status_t setBootDisplayMode(const sp<display::DisplayToken>&, DisplayModeId);
557     status_t getOverlaySupport(gui::OverlayProperties* outProperties) const;
558     status_t clearBootDisplayMode(const sp<IBinder>& displayToken);
559     status_t getHdrConversionCapabilities(
560             std::vector<gui::HdrConversionCapability>* hdrConversionCapaabilities) const;
561     status_t setHdrConversionStrategy(const gui::HdrConversionStrategy& hdrConversionStrategy,
562                                       int32_t*);
563     status_t getHdrOutputConversionSupport(bool* outSupport) const;
564     void setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on);
565     void setGameContentType(const sp<IBinder>& displayToken, bool on);
566     void setPowerMode(const sp<IBinder>& displayToken, int mode);
567     status_t overrideHdrTypes(const sp<IBinder>& displayToken,
568                               const std::vector<ui::Hdr>& hdrTypes);
569     status_t onPullAtom(const int32_t atomId, std::vector<uint8_t>* pulledData, bool* success);
570     status_t getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers);
571     status_t getColorManagement(bool* outGetColorManagement) const;
572     status_t getCompositionPreference(ui::Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
573                                       ui::Dataspace* outWideColorGamutDataspace,
574                                       ui::PixelFormat* outWideColorGamutPixelFormat) const;
575     status_t getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
576                                                    ui::PixelFormat* outFormat,
577                                                    ui::Dataspace* outDataspace,
578                                                    uint8_t* outComponentMask) const;
579     status_t setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken, bool enable,
580                                               uint8_t componentMask, uint64_t maxFrames);
581     status_t getDisplayedContentSample(const sp<IBinder>& displayToken, uint64_t maxFrames,
582                                        uint64_t timestamp, DisplayedFrameStats* outStats) const;
583     status_t getProtectedContentSupport(bool* outSupported) const;
584     status_t isWideColorDisplay(const sp<IBinder>& displayToken, bool* outIsWideColorDisplay) const;
585     status_t addRegionSamplingListener(const Rect& samplingArea, const sp<IBinder>& stopLayerHandle,
586                                        const sp<IRegionSamplingListener>& listener);
587     status_t removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener);
588     status_t addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener);
589     status_t removeFpsListener(const sp<gui::IFpsListener>& listener);
590     status_t addTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener>& listener);
591     status_t removeTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener>& listener);
592     status_t setDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
593                                         const gui::DisplayModeSpecs&);
594     status_t getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken, gui::DisplayModeSpecs*);
595     status_t getDisplayBrightnessSupport(const sp<IBinder>& displayToken, bool* outSupport) const;
596     status_t setDisplayBrightness(const sp<IBinder>& displayToken,
597                                   const gui::DisplayBrightness& brightness);
598     status_t addHdrLayerInfoListener(const sp<IBinder>& displayToken,
599                                      const sp<gui::IHdrLayerInfoListener>& listener);
600     status_t removeHdrLayerInfoListener(const sp<IBinder>& displayToken,
601                                         const sp<gui::IHdrLayerInfoListener>& listener);
602     status_t notifyPowerBoost(int32_t boostId);
603     status_t setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
604                                      float lightPosY, float lightPosZ, float lightRadius);
605     status_t getDisplayDecorationSupport(
606             const sp<IBinder>& displayToken,
607             std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport>*
608                     outSupport) const;
609     status_t setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
610                           int8_t compatibility, int8_t changeFrameRateStrategy);
611 
612     status_t setFrameTimelineInfo(const sp<IGraphicBufferProducer>& surface,
613                                   const gui::FrameTimelineInfo& frameTimelineInfo);
614 
615     status_t setOverrideFrameRate(uid_t uid, float frameRate);
616 
617     status_t updateSmallAreaDetection(std::vector<std::pair<uid_t, float>>& uidThresholdMappings);
618 
619     status_t setSmallAreaDetectionThreshold(uid_t uid, float threshold);
620 
621     int getGpuContextPriority();
622 
623     status_t getMaxAcquiredBufferCount(int* buffers) const;
624 
625     status_t addWindowInfosListener(const sp<gui::IWindowInfosListener>& windowInfosListener,
626                                     gui::WindowInfosListenerInfo* outResult);
627     status_t removeWindowInfosListener(
628             const sp<gui::IWindowInfosListener>& windowInfosListener) const;
629 
630     status_t getStalledTransactionInfo(
631             int pid, std::optional<TransactionHandler::StalledTransactionInfo>& result);
632 
633     // Implements IBinder::DeathRecipient.
634     void binderDied(const wp<IBinder>& who) override;
635 
636     // HWC2::ComposerCallback overrides:
637     void onComposerHalVsync(hal::HWDisplayId, nsecs_t timestamp,
638                             std::optional<hal::VsyncPeriodNanos>) override;
639     void onComposerHalHotplug(hal::HWDisplayId, hal::Connection) override;
640     void onComposerHalRefresh(hal::HWDisplayId) override;
641     void onComposerHalVsyncPeriodTimingChanged(hal::HWDisplayId,
642                                                const hal::VsyncPeriodChangeTimeline&) override;
643     void onComposerHalSeamlessPossible(hal::HWDisplayId) override;
644     void onComposerHalVsyncIdle(hal::HWDisplayId) override;
645     void onRefreshRateChangedDebug(const RefreshRateChangedDebugData&) override;
646 
647     // ICompositor overrides:
648     void configure() override REQUIRES(kMainThreadContext);
649     bool commit(PhysicalDisplayId pacesetterId, const scheduler::FrameTargets&) override
650             REQUIRES(kMainThreadContext);
651     CompositeResultsPerDisplay composite(PhysicalDisplayId pacesetterId,
652                                          const scheduler::FrameTargeters&) override
653             REQUIRES(kMainThreadContext);
654 
655     void sample() override;
656 
657     // ISchedulerCallback overrides:
658     void requestHardwareVsync(PhysicalDisplayId, bool) override;
659     void requestDisplayModes(std::vector<display::DisplayModeRequest>) override;
660     void kernelTimerChanged(bool expired) override;
661     void triggerOnFrameRateOverridesChanged() override;
662 
663     // ICEPowerCallback overrides:
664     void notifyCpuLoadUp() override;
665 
666     // Toggles the kernel idle timer on or off depending the policy decisions around refresh rates.
667     void toggleKernelIdleTimer() REQUIRES(mStateLock);
668 
669     using KernelIdleTimerController = scheduler::RefreshRateSelector::KernelIdleTimerController;
670 
671     // Get the controller and timeout that will help decide how the kernel idle timer will be
672     // configured and what value to use as the timeout.
673     std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
674             getKernelIdleTimerProperties(DisplayId) REQUIRES(mStateLock);
675     // Updates the kernel idle timer either through HWC or through sysprop
676     // depending on which controller is provided
677     void updateKernelIdleTimer(std::chrono::milliseconds timeoutMs, KernelIdleTimerController,
678                                PhysicalDisplayId) REQUIRES(mStateLock);
679     // Keeps track of whether the kernel idle timer is currently enabled, so we don't have to
680     // make calls to sys prop each time.
681     bool mKernelIdleTimerEnabled = false;
682     // Show spinner with refresh rate overlay
683     bool mRefreshRateOverlaySpinner = false;
684     // Show render rate with refresh rate overlay
685     bool mRefreshRateOverlayRenderRate = false;
686     // Show render rate overlay offseted to the middle of the screen (e.g. for circular displays)
687     bool mRefreshRateOverlayShowInMiddle = false;
688 
689     void setDesiredActiveMode(display::DisplayModeRequest&&, bool force = false)
690             REQUIRES(mStateLock);
691 
692     status_t setActiveModeFromBackdoor(const sp<display::DisplayToken>&, DisplayModeId);
693 
694     void initiateDisplayModeChanges() REQUIRES(mStateLock, kMainThreadContext);
695     void finalizeDisplayModeChange(DisplayDevice&) REQUIRES(mStateLock, kMainThreadContext);
696 
697     void clearDesiredActiveModeState(const sp<DisplayDevice>&) REQUIRES(mStateLock);
698     // Called when active mode is no longer is progress
699     void desiredActiveModeChangeDone(const sp<DisplayDevice>&) REQUIRES(mStateLock);
700     // Called on the main thread in response to setPowerMode()
701     void setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode)
702             REQUIRES(mStateLock, kMainThreadContext);
703 
704     // Returns the preferred mode for PhysicalDisplayId if the Scheduler has selected one for that
705     // display. Falls back to the display's defaultModeId otherwise.
706     ftl::Optional<scheduler::FrameRateMode> getPreferredDisplayMode(
707             PhysicalDisplayId, DisplayModeId defaultModeId) const REQUIRES(mStateLock);
708 
709     status_t setDesiredDisplayModeSpecsInternal(
710             const sp<DisplayDevice>&, const scheduler::RefreshRateSelector::PolicyVariant&)
711             EXCLUDES(mStateLock) REQUIRES(kMainThreadContext);
712 
713     bool shouldApplyRefreshRateSelectorPolicy(const DisplayDevice&) const
714             REQUIRES(mStateLock, kMainThreadContext);
715 
716     // TODO(b/241285191): Look up RefreshRateSelector on Scheduler to remove redundant parameter.
717     status_t applyRefreshRateSelectorPolicy(PhysicalDisplayId,
718                                             const scheduler::RefreshRateSelector&,
719                                             bool force = false)
720             REQUIRES(mStateLock, kMainThreadContext);
721 
722     void commitTransactions() EXCLUDES(mStateLock) REQUIRES(kMainThreadContext);
723     void commitTransactionsLocked(uint32_t transactionFlags)
724             REQUIRES(mStateLock, kMainThreadContext);
725     void doCommitTransactions() REQUIRES(mStateLock);
726 
727     // Returns whether a new buffer has been latched.
728     bool latchBuffers();
729 
730     void updateLayerGeometry();
731     void updateLayerMetadataSnapshot();
732     std::vector<std::pair<Layer*, LayerFE*>> moveSnapshotsToCompositionArgs(
733             compositionengine::CompositionRefreshArgs& refreshArgs, bool cursorOnly);
734     void moveSnapshotsFromCompositionArgs(compositionengine::CompositionRefreshArgs& refreshArgs,
735                                           const std::vector<std::pair<Layer*, LayerFE*>>& layers);
736     bool updateLayerSnapshotsLegacy(VsyncId vsyncId, frontend::Update& update,
737                                     bool transactionsFlushed, bool& out)
738             REQUIRES(kMainThreadContext);
739     bool updateLayerSnapshots(VsyncId vsyncId, frontend::Update& update, bool transactionsFlushed,
740                               bool& out) REQUIRES(kMainThreadContext);
741     void updateLayerHistory(const frontend::LayerSnapshot& snapshot);
742     frontend::Update flushLifecycleUpdates() REQUIRES(kMainThreadContext);
743 
744     void updateInputFlinger(VsyncId vsyncId, TimePoint frameTime);
745     void persistDisplayBrightness(bool needsComposite) REQUIRES(kMainThreadContext);
746     void buildWindowInfos(std::vector<gui::WindowInfo>& outWindowInfos,
747                           std::vector<gui::DisplayInfo>& outDisplayInfos);
748     void commitInputWindowCommands() REQUIRES(mStateLock);
749     void updateCursorAsync();
750 
751     void initScheduler(const sp<const DisplayDevice>&) REQUIRES(kMainThreadContext, mStateLock);
752 
753     void resetPhaseConfiguration(Fps) REQUIRES(mStateLock, kMainThreadContext);
754     void updatePhaseConfiguration(Fps) REQUIRES(mStateLock);
755 
756     /*
757      * Transactions
758      */
759     bool applyTransactionState(const FrameTimelineInfo& info,
760                                std::vector<ResolvedComposerState>& state,
761                                Vector<DisplayState>& displays, uint32_t flags,
762                                const InputWindowCommands& inputWindowCommands,
763                                const int64_t desiredPresentTime, bool isAutoTimestamp,
764                                const std::vector<uint64_t>& uncacheBufferIds,
765                                const int64_t postTime, bool hasListenerCallbacks,
766                                const std::vector<ListenerCallbacks>& listenerCallbacks,
767                                int originPid, int originUid, uint64_t transactionId)
768             REQUIRES(mStateLock);
769     // Flush pending transactions that were presented after desiredPresentTime.
770     // For test only
771     bool flushTransactionQueues(VsyncId) REQUIRES(kMainThreadContext);
772 
773     bool applyTransactions(std::vector<TransactionState>&, VsyncId) REQUIRES(kMainThreadContext);
774     bool applyAndCommitDisplayTransactionStates(std::vector<TransactionState>& transactions)
775             REQUIRES(kMainThreadContext);
776 
777     // Returns true if there is at least one transaction that needs to be flushed
778     bool transactionFlushNeeded();
779     void addTransactionReadyFilters();
780     TransactionHandler::TransactionReadiness transactionReadyTimelineCheck(
781             const TransactionHandler::TransactionFlushState& flushState)
782             REQUIRES(kMainThreadContext);
783     TransactionHandler::TransactionReadiness transactionReadyBufferCheck(
784             const TransactionHandler::TransactionFlushState& flushState)
785             REQUIRES(kMainThreadContext);
786 
787     uint32_t setClientStateLocked(const FrameTimelineInfo&, ResolvedComposerState&,
788                                   int64_t desiredPresentTime, bool isAutoTimestamp,
789                                   int64_t postTime, uint64_t transactionId) REQUIRES(mStateLock);
790     uint32_t updateLayerCallbacksAndStats(const FrameTimelineInfo&, ResolvedComposerState&,
791                                           int64_t desiredPresentTime, bool isAutoTimestamp,
792                                           int64_t postTime, uint64_t transactionId)
793             REQUIRES(mStateLock);
794     uint32_t getTransactionFlags() const;
795 
796     // Sets the masked bits, and schedules a commit if needed.
797     void setTransactionFlags(uint32_t mask, TransactionSchedule = TransactionSchedule::Late,
798                              const sp<IBinder>& applyToken = nullptr,
799                              FrameHint = FrameHint::kActive);
800 
801     // Clears and returns the masked bits.
802     uint32_t clearTransactionFlags(uint32_t mask);
803 
804     void commitOffscreenLayers();
805 
806     static LatchUnsignaledConfig getLatchUnsignaledConfig();
807     bool shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t&, size_t numStates,
808                                bool firstTransaction) const;
809     bool applyTransactionsLocked(std::vector<TransactionState>& transactions, VsyncId)
810             REQUIRES(mStateLock);
811     uint32_t setDisplayStateLocked(const DisplayState& s) REQUIRES(mStateLock);
812     uint32_t addInputWindowCommands(const InputWindowCommands& inputWindowCommands)
813             REQUIRES(mStateLock);
814     bool frameIsEarly(TimePoint expectedPresentTime, VsyncId) const;
815 
816     /*
817      * Layer management
818      */
819     status_t createLayer(LayerCreationArgs& args, gui::CreateSurfaceResult& outResult);
820 
821     status_t createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,
822                                     sp<Layer>* outLayer);
823 
824     status_t createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* outHandle,
825                                sp<Layer>* outLayer);
826 
827     status_t mirrorLayer(const LayerCreationArgs& args, const sp<IBinder>& mirrorFromHandle,
828                          gui::CreateSurfaceResult& outResult);
829 
830     status_t mirrorDisplay(DisplayId displayId, const LayerCreationArgs& args,
831                            gui::CreateSurfaceResult& outResult);
832 
833     void markLayerPendingRemovalLocked(const sp<Layer>& layer) REQUIRES(mStateLock);
834 
835     // add a layer to SurfaceFlinger
836     status_t addClientLayer(LayerCreationArgs& args, const sp<IBinder>& handle,
837                             const sp<Layer>& layer, const wp<Layer>& parentLayer,
838                             uint32_t* outTransformHint);
839 
840     // Traverse through all the layers and compute and cache its bounds.
841     void computeLayerBounds();
842 
843     // Boot animation, on/off animations and screen capture
844     void startBootAnim();
845 
846     ftl::SharedFuture<FenceResult> captureScreenCommon(RenderAreaFuture, GetLayerSnapshotsFunction,
847                                                        ui::Size bufferSize, ui::PixelFormat,
848                                                        bool allowProtected, bool grayscale,
849                                                        const sp<IScreenCaptureListener>&);
850     ftl::SharedFuture<FenceResult> captureScreenCommon(
851             RenderAreaFuture, GetLayerSnapshotsFunction,
852             const std::shared_ptr<renderengine::ExternalTexture>&, bool regionSampling,
853             bool grayscale, const sp<IScreenCaptureListener>&);
854     ftl::SharedFuture<FenceResult> renderScreenImpl(
855             std::shared_ptr<const RenderArea>, GetLayerSnapshotsFunction,
856             const std::shared_ptr<renderengine::ExternalTexture>&, bool canCaptureBlackoutContent,
857             bool regionSampling, bool grayscale, ScreenCaptureResults&) EXCLUDES(mStateLock)
858             REQUIRES(kMainThreadContext);
859 
860     // If the uid provided is not UNSET_UID, the traverse will skip any layers that don't have a
861     // matching ownerUid
862     void traverseLayersInLayerStack(ui::LayerStack, const int32_t uid,
863                                     std::unordered_set<uint32_t> excludeLayerIds,
864                                     const LayerVector::Visitor&);
865 
866     void readPersistentProperties();
867 
868     uint32_t getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const;
869 
870     /*
871      * Display and layer stack management
872      */
873 
874     // Called during boot, and restart after system_server death.
875     void initializeDisplays() REQUIRES(kMainThreadContext);
876 
getDisplayDeviceLocked(const wp<IBinder> & displayToken)877     sp<const DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& displayToken) const
878             REQUIRES(mStateLock) {
879         return const_cast<SurfaceFlinger*>(this)->getDisplayDeviceLocked(displayToken);
880     }
881 
getDisplayDeviceLocked(const wp<IBinder> & displayToken)882     sp<DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& displayToken) REQUIRES(mStateLock) {
883         return mDisplays.get(displayToken)
884                 .or_else(ftl::static_ref<sp<DisplayDevice>>([] { return nullptr; }))
885                 .value();
886     }
887 
getDisplayDeviceLocked(PhysicalDisplayId id)888     sp<const DisplayDevice> getDisplayDeviceLocked(PhysicalDisplayId id) const
889             REQUIRES(mStateLock) {
890         return const_cast<SurfaceFlinger*>(this)->getDisplayDeviceLocked(id);
891     }
892 
getDisplayDeviceLocked(PhysicalDisplayId id)893     sp<DisplayDevice> getDisplayDeviceLocked(PhysicalDisplayId id) REQUIRES(mStateLock) {
894         if (const auto token = getPhysicalDisplayTokenLocked(id)) {
895             return getDisplayDeviceLocked(token);
896         }
897         return nullptr;
898     }
899 
getDisplayDeviceLocked(DisplayId id)900     sp<const DisplayDevice> getDisplayDeviceLocked(DisplayId id) const REQUIRES(mStateLock) {
901         // TODO(b/182939859): Replace tokens with IDs for display lookup.
902         return findDisplay([id](const auto& display) { return display.getId() == id; });
903     }
904 
getCompositionDisplayLocked(DisplayId id)905     std::shared_ptr<compositionengine::Display> getCompositionDisplayLocked(DisplayId id) const
906             REQUIRES(mStateLock) {
907         if (const auto display = getDisplayDeviceLocked(id)) {
908             return display->getCompositionDisplay();
909         }
910         return nullptr;
911     }
912 
913     // Returns the primary display or (for foldables) the active display, assuming that the inner
914     // and outer displays have mutually exclusive power states.
getDefaultDisplayDeviceLocked()915     sp<const DisplayDevice> getDefaultDisplayDeviceLocked() const REQUIRES(mStateLock) {
916         return const_cast<SurfaceFlinger*>(this)->getDefaultDisplayDeviceLocked();
917     }
918 
getDefaultDisplayDeviceLocked()919     sp<DisplayDevice> getDefaultDisplayDeviceLocked() REQUIRES(mStateLock) {
920         if (const auto display = getDisplayDeviceLocked(mActiveDisplayId)) {
921             return display;
922         }
923         // The active display is outdated, so fall back to the primary display.
924         mActiveDisplayId = getPrimaryDisplayIdLocked();
925         return getDisplayDeviceLocked(mActiveDisplayId);
926     }
927 
getDefaultDisplayDevice()928     sp<const DisplayDevice> getDefaultDisplayDevice() const EXCLUDES(mStateLock) {
929         Mutex::Autolock lock(mStateLock);
930         return getDefaultDisplayDeviceLocked();
931     }
932 
933     using DisplayDeviceAndSnapshot =
934             std::pair<sp<DisplayDevice>, display::PhysicalDisplay::SnapshotRef>;
935 
936     // Combinator for ftl::Optional<PhysicalDisplay>::and_then.
getDisplayDeviceAndSnapshot()937     auto getDisplayDeviceAndSnapshot() REQUIRES(mStateLock) {
938         return [this](const display::PhysicalDisplay& display) REQUIRES(
939                        mStateLock) -> ftl::Optional<DisplayDeviceAndSnapshot> {
940             if (auto device = getDisplayDeviceLocked(display.snapshot().displayId())) {
941                 return std::make_pair(std::move(device), display.snapshotRef());
942             }
943 
944             return {};
945         };
946     }
947 
948     // Returns the first display that matches a `bool(const DisplayDevice&)` predicate.
949     template <typename Predicate>
findDisplay(Predicate p)950     sp<DisplayDevice> findDisplay(Predicate p) const REQUIRES(mStateLock) {
951         const auto it = std::find_if(mDisplays.begin(), mDisplays.end(),
952                                      [&](const auto& pair)
953                                              REQUIRES(mStateLock) { return p(*pair.second); });
954 
955         return it == mDisplays.end() ? nullptr : it->second;
956     }
957 
958     std::vector<PhysicalDisplayId> getPhysicalDisplayIdsLocked() const REQUIRES(mStateLock);
959 
960     // mark a region of a layer stack dirty. this updates the dirty
961     // region of all screens presenting this layer stack.
962     void invalidateLayerStack(const ui::LayerFilter& layerFilter, const Region& dirty);
963 
makeLayerFilterForDisplay(DisplayId displayId,ui::LayerStack layerStack)964     ui::LayerFilter makeLayerFilterForDisplay(DisplayId displayId, ui::LayerStack layerStack)
965             REQUIRES(mStateLock) {
966         return {layerStack,
967                 PhysicalDisplayId::tryCast(displayId)
968                         .and_then(display::getPhysicalDisplay(mPhysicalDisplays))
969                         .transform(&display::PhysicalDisplay::isInternal)
970                         .value_or(false)};
971     }
972 
973     /*
974      * H/W composer
975      */
976     // The following thread safety rules apply when accessing HWComposer:
977     // 1. When reading display state from HWComposer on the main thread, it's not necessary to
978     //    acquire mStateLock.
979     // 2. When accessing HWComposer on a thread other than the main thread, we always
980     //    need to acquire mStateLock. This is because the main thread could be
981     //    in the process of writing display state, e.g. creating or destroying a display.
982     HWComposer& getHwComposer() const;
983 
984     /*
985      * Compositing
986      */
987     void postComposition(PhysicalDisplayId pacesetterId, const scheduler::FrameTargeters&,
988                          nsecs_t presentStartTime) REQUIRES(kMainThreadContext);
989 
990     /*
991      * Display management
992      */
993     std::pair<DisplayModes, DisplayModePtr> loadDisplayModes(PhysicalDisplayId) const
994             REQUIRES(mStateLock);
995 
996     // TODO(b/241285876): Move to DisplayConfigurator.
997     //
998     // Returns whether displays have been added/changed/removed, i.e. whether ICompositor should
999     // commit display transactions.
1000     bool configureLocked() REQUIRES(mStateLock) REQUIRES(kMainThreadContext)
1001             EXCLUDES(mHotplugMutex);
1002 
1003     // Returns a string describing the hotplug, or nullptr if it was rejected.
1004     const char* processHotplug(PhysicalDisplayId, hal::HWDisplayId, bool connected,
1005                                DisplayIdentificationInfo&&) REQUIRES(mStateLock)
1006             REQUIRES(kMainThreadContext);
1007 
1008     sp<DisplayDevice> setupNewDisplayDeviceInternal(
1009             const wp<IBinder>& displayToken,
1010             std::shared_ptr<compositionengine::Display> compositionDisplay,
1011             const DisplayDeviceState& state,
1012             const sp<compositionengine::DisplaySurface>& displaySurface,
1013             const sp<IGraphicBufferProducer>& producer) REQUIRES(mStateLock);
1014     void processDisplayChangesLocked() REQUIRES(mStateLock, kMainThreadContext);
1015     void processDisplayRemoved(const wp<IBinder>& displayToken)
1016             REQUIRES(mStateLock, kMainThreadContext);
1017     void processDisplayChanged(const wp<IBinder>& displayToken,
1018                                const DisplayDeviceState& currentState,
1019                                const DisplayDeviceState& drawingState)
1020             REQUIRES(mStateLock, kMainThreadContext);
1021 
1022     void dispatchDisplayHotplugEvent(PhysicalDisplayId, bool connected);
1023     void dispatchDisplayModeChangeEvent(PhysicalDisplayId, const scheduler::FrameRateMode&)
1024             REQUIRES(mStateLock);
1025 
1026     /*
1027      * VSYNC
1028      */
1029     nsecs_t getVsyncPeriodFromHWC() const REQUIRES(mStateLock);
1030 
1031     /*
1032      * Display identification
1033      */
getPhysicalDisplayTokenLocked(PhysicalDisplayId displayId)1034     sp<display::DisplayToken> getPhysicalDisplayTokenLocked(PhysicalDisplayId displayId) const
1035             REQUIRES(mStateLock) {
1036         return mPhysicalDisplays.get(displayId)
1037                 .transform([](const display::PhysicalDisplay& display) { return display.token(); })
1038                 .or_else([] { return std::optional<sp<display::DisplayToken>>(nullptr); })
1039                 .value();
1040     }
1041 
1042     std::optional<PhysicalDisplayId> getPhysicalDisplayIdLocked(
1043             const sp<display::DisplayToken>&) const REQUIRES(mStateLock);
1044 
1045     // Returns the first display connected at boot.
1046     //
1047     // TODO(b/229851933): SF conflates the primary display with the first display connected at boot,
1048     // which typically has DisplayConnectionType::Internal. (Theoretically, it must be an internal
1049     // display because SF does not support disconnecting it, though in practice HWC may circumvent
1050     // this limitation.)
getPrimaryDisplayTokenLocked()1051     sp<IBinder> getPrimaryDisplayTokenLocked() const REQUIRES(mStateLock) {
1052         return getPhysicalDisplayTokenLocked(getPrimaryDisplayIdLocked());
1053     }
1054 
getPrimaryDisplayIdLocked()1055     PhysicalDisplayId getPrimaryDisplayIdLocked() const REQUIRES(mStateLock) {
1056         return getHwComposer().getPrimaryDisplayId();
1057     }
1058 
1059     // Toggles use of HAL/GPU virtual displays.
1060     void enableHalVirtualDisplays(bool);
1061 
1062     // Virtual display lifecycle for ID generation and HAL allocation.
1063     VirtualDisplayId acquireVirtualDisplay(ui::Size, ui::PixelFormat) REQUIRES(mStateLock);
1064     void releaseVirtualDisplay(VirtualDisplayId);
1065 
1066     // Returns a display other than `mActiveDisplayId` that can be activated, if any.
1067     sp<DisplayDevice> getActivatableDisplay() const REQUIRES(mStateLock, kMainThreadContext);
1068 
1069     void onActiveDisplayChangedLocked(const DisplayDevice* inactiveDisplayPtr,
1070                                       const DisplayDevice& activeDisplay)
1071             REQUIRES(mStateLock, kMainThreadContext);
1072 
1073     void onActiveDisplaySizeChanged(const DisplayDevice&);
1074 
1075     /*
1076      * Debugging & dumpsys
1077      */
1078     void dumpAllLocked(const DumpArgs& args, const std::string& compositionLayers,
1079                        std::string& result) const REQUIRES(mStateLock);
1080     void dumpHwcLayersMinidumpLocked(std::string& result) const REQUIRES(mStateLock);
1081 
1082     void appendSfConfigString(std::string& result) const;
1083     void listLayersLocked(std::string& result) const;
1084     void dumpStatsLocked(const DumpArgs& args, std::string& result) const REQUIRES(mStateLock);
1085     void clearStatsLocked(const DumpArgs& args, std::string& result);
1086     void dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const;
1087     void dumpFrameTimeline(const DumpArgs& args, std::string& result) const;
1088     void logFrameStats(TimePoint now) REQUIRES(kMainThreadContext);
1089 
1090     void dumpScheduler(std::string& result) const REQUIRES(mStateLock);
1091     void dumpEvents(std::string& result) const REQUIRES(mStateLock);
1092     void dumpVsync(std::string& result) const REQUIRES(mStateLock);
1093 
1094     void dumpCompositionDisplays(std::string& result) const REQUIRES(mStateLock);
1095     void dumpDisplays(std::string& result) const REQUIRES(mStateLock);
1096     void dumpDisplayIdentificationData(std::string& result) const REQUIRES(mStateLock);
1097     void dumpRawDisplayIdentificationData(const DumpArgs&, std::string& result) const;
1098     void dumpWideColorInfo(std::string& result) const REQUIRES(mStateLock);
1099 
1100     LayersProto dumpDrawingStateProto(uint32_t traceFlags) const;
1101     void dumpOffscreenLayersProto(LayersProto& layersProto,
1102                                   uint32_t traceFlags = LayerTracing::TRACE_ALL) const;
1103     google::protobuf::RepeatedPtrField<DisplayProto> dumpDisplayProto() const;
1104     void addToLayerTracing(bool visibleRegionDirty, TimePoint, VsyncId)
1105             REQUIRES(kMainThreadContext);
1106 
1107     // Dumps state from HW Composer
1108     void dumpHwc(std::string& result) const;
1109     LayersProto dumpProtoFromMainThread(uint32_t traceFlags = LayerTracing::TRACE_ALL)
1110             EXCLUDES(mStateLock);
1111     void dumpOffscreenLayers(std::string& result) EXCLUDES(mStateLock);
1112     void dumpPlannerInfo(const DumpArgs& args, std::string& result) const REQUIRES(mStateLock);
1113 
1114     status_t doDump(int fd, const DumpArgs& args, bool asProto);
1115 
1116     status_t dumpCritical(int fd, const DumpArgs&, bool asProto);
1117 
dumpAll(int fd,const DumpArgs & args,bool asProto)1118     status_t dumpAll(int fd, const DumpArgs& args, bool asProto) override {
1119         return doDump(fd, args, asProto);
1120     }
1121 
1122     static mat4 calculateColorMatrix(float saturation);
1123 
1124     void updateColorMatrixLocked();
1125 
1126     // Verify that transaction is being called by an approved process:
1127     // either AID_GRAPHICS or AID_SYSTEM.
1128     status_t CheckTransactCodeCredentials(uint32_t code);
1129 
1130     // Add transaction to the Transaction Queue
1131 
1132     /*
1133      * Generic Layer Metadata
1134      */
1135     const std::unordered_map<std::string, uint32_t>& getGenericLayerMetadataKeyMap() const;
1136 
1137     static int calculateMaxAcquiredBufferCount(Fps refreshRate,
1138                                                std::chrono::nanoseconds presentLatency);
1139     int getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const;
1140 
1141     bool isHdrLayer(const frontend::LayerSnapshot& snapshot) const;
1142 
1143     ui::Rotation getPhysicalDisplayOrientation(DisplayId, bool isPrimary) const
1144             REQUIRES(mStateLock);
1145     void traverseLegacyLayers(const LayerVector::Visitor& visitor) const;
1146 
1147     sp<StartPropertySetThread> mStartPropertySetThread;
1148     surfaceflinger::Factory& mFactory;
1149     pid_t mPid;
1150     std::future<void> mRenderEnginePrimeCacheFuture;
1151 
1152     // mStateLock has conventions related to the current thread, because only
1153     // the main thread should modify variables protected by mStateLock.
1154     // - read access from a non-main thread must lock mStateLock, since the main
1155     // thread may modify these variables.
1156     // - write access from a non-main thread is not permitted.
1157     // - read access from the main thread can use an ftl::FakeGuard, since other
1158     // threads must not modify these variables.
1159     // - write access from the main thread must lock mStateLock, since another
1160     // thread may be reading these variables.
1161     mutable Mutex mStateLock;
1162     State mCurrentState{LayerVector::StateSet::Current};
1163     std::atomic<int32_t> mTransactionFlags = 0;
1164     std::atomic<uint32_t> mUniqueTransactionId = 1;
1165     SortedVector<sp<Layer>> mLayersPendingRemoval;
1166 
1167     // Buffers that have been discarded by clients and need to be evicted from per-layer caches so
1168     // the graphics memory can be immediately freed.
1169     std::vector<uint64_t> mBufferIdsToUncache;
1170 
1171     // global color transform states
1172     Daltonizer mDaltonizer;
1173     float mGlobalSaturationFactor = 1.0f;
1174     mat4 mClientColorMatrix;
1175 
1176     size_t mMaxGraphicBufferProducerListSize = MAX_LAYERS;
1177     // If there are more GraphicBufferProducers tracked by SurfaceFlinger than
1178     // this threshold, then begin logging.
1179     size_t mGraphicBufferProducerListSizeLogThreshold =
1180             static_cast<size_t>(0.95 * static_cast<double>(MAX_LAYERS));
1181 
1182     // protected by mStateLock (but we could use another lock)
1183     bool mLayersRemoved = false;
1184     bool mLayersAdded = false;
1185 
1186     std::atomic_bool mMustComposite = false;
1187     std::atomic_bool mGeometryDirty = false;
1188 
1189     // constant members (no synchronization needed for access)
1190     const nsecs_t mBootTime = systemTime();
1191     bool mIsUserBuild = true;
1192 
1193     // Can only accessed from the main thread, these members
1194     // don't need synchronization
1195     State mDrawingState{LayerVector::StateSet::Drawing};
1196     bool mVisibleRegionsDirty = false;
1197 
1198     bool mHdrLayerInfoChanged = false;
1199 
1200     // Used to ensure we omit a callback when HDR layer info listener is newly added but the
1201     // scene hasn't changed
1202     bool mAddingHDRLayerInfoListener = false;
1203     bool mIgnoreHdrCameraLayers = false;
1204 
1205     // Set during transaction application stage to track if the input info or children
1206     // for a layer has changed.
1207     // TODO: Also move visibleRegions over to a boolean system.
1208     bool mUpdateInputInfo = false;
1209     bool mSomeChildrenChanged;
1210     bool mForceTransactionDisplayChange = false;
1211 
1212     // Set if LayerMetadata has changed since the last LayerMetadata snapshot.
1213     bool mLayerMetadataSnapshotNeeded = false;
1214 
1215     // TODO(b/238781169) validate these on composition
1216     // Tracks layers that have pending frames which are candidates for being
1217     // latched.
1218     std::unordered_set<sp<Layer>, SpHash<Layer>> mLayersWithQueuedFrames;
1219     std::unordered_set<sp<Layer>, SpHash<Layer>> mLayersWithBuffersRemoved;
1220     // Tracks layers that need to update a display's dirty region.
1221     std::vector<sp<Layer>> mLayersPendingRefresh;
1222     // Sorted list of layers that were composed during previous frame. This is used to
1223     // avoid an expensive traversal of the layer hierarchy when there are no
1224     // visible region changes. Because this is a list of strong pointers, this will
1225     // extend the life of the layer but this list is only updated in the main thread.
1226     std::vector<sp<Layer>> mPreviouslyComposedLayers;
1227 
1228     BootStage mBootStage = BootStage::BOOTLOADER;
1229 
1230     struct HotplugEvent {
1231         hal::HWDisplayId hwcDisplayId;
1232         hal::Connection connection = hal::Connection::INVALID;
1233     };
1234 
1235     std::mutex mHotplugMutex;
1236     std::vector<HotplugEvent> mPendingHotplugEvents GUARDED_BY(mHotplugMutex);
1237 
1238     // Displays are composited in `mDisplays` order. Internal displays are inserted at boot and
1239     // never removed, so take precedence over external and virtual displays.
1240     //
1241     // May be read from any thread, but must only be written from the main thread.
1242     ui::DisplayMap<wp<IBinder>, const sp<DisplayDevice>> mDisplays GUARDED_BY(mStateLock);
1243 
1244     display::PhysicalDisplays mPhysicalDisplays GUARDED_BY(mStateLock);
1245 
1246     // The inner or outer display for foldables, assuming they have mutually exclusive power states.
1247     // Atomic because writes from onActiveDisplayChangedLocked are not always under mStateLock, but
1248     // reads from ISchedulerCallback::requestDisplayModes may happen concurrently.
1249     std::atomic<PhysicalDisplayId> mActiveDisplayId GUARDED_BY(mStateLock);
1250 
1251     struct {
1252         DisplayIdGenerator<GpuVirtualDisplayId> gpu;
1253         std::optional<DisplayIdGenerator<HalVirtualDisplayId>> hal;
1254     } mVirtualDisplayIdGenerators;
1255 
1256     std::atomic_uint mDebugFlashDelay = 0;
1257     std::atomic_bool mDebugDisableHWC = false;
1258     std::atomic_bool mDebugDisableTransformHint = false;
1259     std::atomic<nsecs_t> mDebugInTransaction = 0;
1260     std::atomic_bool mForceFullDamage = false;
1261 
1262     bool mLayerCachingEnabled = false;
1263     bool mBackpressureGpuComposition = false;
1264 
1265     LayerTracing mLayerTracing;
1266     bool mLayerTracingEnabled = false;
1267 
1268     std::optional<TransactionTracing> mTransactionTracing;
1269     std::atomic<bool> mTracingEnabledChanged = false;
1270 
1271     const std::shared_ptr<TimeStats> mTimeStats;
1272     const std::unique_ptr<FrameTracer> mFrameTracer;
1273     const std::unique_ptr<frametimeline::FrameTimeline> mFrameTimeline;
1274 
1275     VsyncId mLastCommittedVsyncId;
1276 
1277     // If blurs should be enabled on this device.
1278     bool mSupportsBlur = false;
1279 
1280     TransactionCallbackInvoker mTransactionCallbackInvoker;
1281 
1282     // We maintain a pool of pre-generated texture names to hand out to avoid
1283     // layer creation needing to run on the main thread (which it would
1284     // otherwise need to do to access RenderEngine).
1285     std::mutex mTexturePoolMutex;
1286     uint32_t mTexturePoolSize = 0;
1287     std::vector<uint32_t> mTexturePool;
1288 
1289     std::atomic<size_t> mNumLayers = 0;
1290 
1291     // to linkToDeath
1292     sp<IBinder> mWindowManager;
1293     // We want to avoid multiple calls to BOOT_FINISHED as they come in on
1294     // different threads without a lock and could trigger unsynchronized writes to
1295     // to mWindowManager or mInputFlinger
1296     std::atomic<bool> mBootFinished = false;
1297 
1298     std::thread::id mMainThreadId = std::this_thread::get_id();
1299 
1300     DisplayColorSetting mDisplayColorSetting = DisplayColorSetting::kEnhanced;
1301 
1302     // Color mode forced by setting persist.sys.sf.color_mode, it must:
1303     //     1. not be NATIVE color mode, NATIVE color mode means no forced color mode;
1304     //     2. be one of the supported color modes returned by hardware composer, otherwise
1305     //        it will not be respected.
1306     // persist.sys.sf.color_mode will only take effect when persist.sys.sf.native_mode
1307     // is not set to 1.
1308     // This property can be used to force SurfaceFlinger to always pick a certain color mode.
1309     ui::ColorMode mForceColorMode = ui::ColorMode::NATIVE;
1310 
1311     // Whether to enable wide color gamut (e.g. Display P3) for internal displays that support it.
1312     // If false, wide color modes are filtered out for all internal displays.
1313     bool mSupportsWideColor = false;
1314 
1315     ui::Dataspace mDefaultCompositionDataspace;
1316     ui::Dataspace mWideColorGamutCompositionDataspace;
1317     ui::Dataspace mColorSpaceAgnosticDataspace;
1318     float mDimmingRatio = -1.f;
1319 
1320     std::unique_ptr<renderengine::RenderEngine> mRenderEngine;
1321     std::atomic<int> mNumTrustedPresentationListeners = 0;
1322 
1323     std::unique_ptr<compositionengine::CompositionEngine> mCompositionEngine;
1324 
1325     CompositionCoveragePerDisplay mCompositionCoverage;
1326 
1327     // mMaxRenderTargetSize is only set once in init() so it doesn't need to be protected by
1328     // any mutex.
1329     size_t mMaxRenderTargetSize{1};
1330 
1331     const std::string mHwcServiceName;
1332 
1333     /*
1334      * Scheduler
1335      */
1336     std::unique_ptr<scheduler::Scheduler> mScheduler;
1337     scheduler::ConnectionHandle mAppConnectionHandle;
1338     scheduler::ConnectionHandle mSfConnectionHandle;
1339 
1340     // Stores phase offsets configured per refresh rate.
1341     std::unique_ptr<scheduler::VsyncConfiguration> mVsyncConfiguration;
1342 
1343     std::unique_ptr<scheduler::RefreshRateStats> mRefreshRateStats;
1344     scheduler::PresentLatencyTracker mPresentLatencyTracker GUARDED_BY(kMainThreadContext);
1345 
1346     bool mLumaSampling = true;
1347     sp<RegionSamplingThread> mRegionSamplingThread;
1348     sp<FpsReporter> mFpsReporter;
1349     sp<TunnelModeEnabledReporter> mTunnelModeEnabledReporter;
1350     ui::DisplayPrimaries mInternalDisplayPrimaries;
1351 
1352     const float mEmulatedDisplayDensity;
1353     const float mInternalDisplayDensity;
1354 
1355     // Should only be accessed by the main thread.
1356     sp<os::IInputFlinger> mInputFlinger;
1357     InputWindowCommands mInputWindowCommands;
1358 
1359     std::unique_ptr<Hwc2::PowerAdvisor> mPowerAdvisor;
1360 
1361     void enableRefreshRateOverlay(bool enable) REQUIRES(mStateLock, kMainThreadContext);
1362 
1363     // Flag used to set override desired display mode from backdoor
1364     bool mDebugDisplayModeSetByBackdoor = false;
1365 
1366     // A set of layers that have no parent so they are not drawn on screen.
1367     // Should only be accessed by the main thread.
1368     // The Layer pointer is removed from the set when the destructor is called so there shouldn't
1369     // be any issues with a raw pointer referencing an invalid object.
1370     std::unordered_set<Layer*> mOffscreenLayers;
1371 
1372     BufferCountTracker mBufferCountTracker;
1373 
1374     std::unordered_map<DisplayId, sp<HdrLayerInfoReporter>> mHdrLayerInfoListeners
1375             GUARDED_BY(mStateLock);
1376 
1377     mutable std::mutex mCreatedLayersLock;
1378 
1379     // A temporay pool that store the created layers and will be added to current state in main
1380     // thread.
1381     std::vector<LayerCreatedState> mCreatedLayers GUARDED_BY(mCreatedLayersLock);
1382     bool commitCreatedLayers(VsyncId, std::vector<LayerCreatedState>& createdLayers);
1383     void handleLayerCreatedLocked(const LayerCreatedState&, VsyncId) REQUIRES(mStateLock);
1384 
1385     mutable std::mutex mMirrorDisplayLock;
1386     struct MirrorDisplayState {
MirrorDisplayStateMirrorDisplayState1387         MirrorDisplayState(ui::LayerStack layerStack, sp<IBinder>& rootHandle,
1388                            const sp<Client>& client)
1389               : layerStack(layerStack), rootHandle(rootHandle), client(client) {}
1390 
1391         ui::LayerStack layerStack;
1392         sp<IBinder> rootHandle;
1393         const sp<Client> client;
1394     };
1395     std::vector<MirrorDisplayState> mMirrorDisplays GUARDED_BY(mMirrorDisplayLock);
1396     bool commitMirrorDisplays(VsyncId);
1397 
1398     std::atomic<ui::Transform::RotationFlags> mActiveDisplayTransformHint;
1399 
1400     // Must only be accessed on the main thread.
1401     // TODO (b/259407931): Remove.
1402     static ui::Transform::RotationFlags sActiveDisplayRotationFlags;
1403 
isRefreshRateOverlayEnabled()1404     bool isRefreshRateOverlayEnabled() const REQUIRES(mStateLock) {
1405         return hasDisplay(
1406                 [](const auto& display) { return display.isRefreshRateOverlayEnabled(); });
1407     }
1408     std::function<std::vector<std::pair<Layer*, sp<LayerFE>>>()> getLayerSnapshotsForScreenshots(
1409             std::optional<ui::LayerStack> layerStack, uint32_t uid,
1410             std::function<bool(const frontend::LayerSnapshot&, bool& outStopTraversal)>
1411                     snapshotFilterFn);
1412     std::function<std::vector<std::pair<Layer*, sp<LayerFE>>>()> getLayerSnapshotsForScreenshots(
1413             std::optional<ui::LayerStack> layerStack, uint32_t uid,
1414             std::unordered_set<uint32_t> excludeLayerIds);
1415     std::function<std::vector<std::pair<Layer*, sp<LayerFE>>>()> getLayerSnapshotsForScreenshots(
1416             uint32_t rootLayerId, uint32_t uid, std::unordered_set<uint32_t> excludeLayerIds,
1417             bool childrenOnly, const std::optional<FloatRect>& optionalParentCrop);
1418 
1419     const sp<WindowInfosListenerInvoker> mWindowInfosListenerInvoker;
1420 
1421     FlagManager mFlagManager;
1422 
1423     // returns the framerate of the layer with the given sequence ID
getLayerFramerate(nsecs_t now,int32_t id)1424     float getLayerFramerate(nsecs_t now, int32_t id) const {
1425         return mScheduler->getLayerFramerate(now, id);
1426     }
1427 
1428     bool mPowerHintSessionEnabled;
1429 
1430     bool mLayerLifecycleManagerEnabled = false;
1431     bool mLegacyFrontEndEnabled = true;
1432 
1433     frontend::LayerLifecycleManager mLayerLifecycleManager;
1434     frontend::LayerHierarchyBuilder mLayerHierarchyBuilder{{}};
1435     frontend::LayerSnapshotBuilder mLayerSnapshotBuilder;
1436 
1437     std::vector<uint32_t> mDestroyedHandles;
1438     std::vector<std::unique_ptr<frontend::RequestedLayerState>> mNewLayers;
1439     std::vector<LayerCreationArgs> mNewLayerArgs;
1440     // These classes do not store any client state but help with managing transaction callbacks
1441     // and stats.
1442     std::unordered_map<uint32_t, sp<Layer>> mLegacyLayers;
1443 
1444     TransactionHandler mTransactionHandler;
1445     ui::DisplayMap<ui::LayerStack, frontend::DisplayInfo> mFrontEndDisplayInfos;
1446     bool mFrontEndDisplayInfosChanged = false;
1447 
1448     // WindowInfo ids visible during the last commit.
1449     std::unordered_set<int32_t> mVisibleWindowIds;
1450 };
1451 
1452 class SurfaceComposerAIDL : public gui::BnSurfaceComposer {
1453 public:
SurfaceComposerAIDL(sp<SurfaceFlinger> sf)1454     SurfaceComposerAIDL(sp<SurfaceFlinger> sf) : mFlinger(std::move(sf)) {}
1455 
1456     binder::Status bootFinished() override;
1457     binder::Status createDisplayEventConnection(
1458             VsyncSource vsyncSource, EventRegistration eventRegistration,
1459             const sp<IBinder>& layerHandle,
1460             sp<gui::IDisplayEventConnection>* outConnection) override;
1461     binder::Status createConnection(sp<gui::ISurfaceComposerClient>* outClient) override;
1462     binder::Status createDisplay(const std::string& displayName, bool secure,
1463                                  float requestedRefreshRate, sp<IBinder>* outDisplay) override;
1464     binder::Status destroyDisplay(const sp<IBinder>& display) override;
1465     binder::Status getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) override;
1466     binder::Status getPhysicalDisplayToken(int64_t displayId, sp<IBinder>* outDisplay) override;
1467     binder::Status setPowerMode(const sp<IBinder>& display, int mode) override;
1468     binder::Status getSupportedFrameTimestamps(std::vector<FrameEvent>* outSupported) override;
1469     binder::Status getDisplayStats(const sp<IBinder>& display,
1470                                    gui::DisplayStatInfo* outStatInfo) override;
1471     binder::Status getDisplayState(const sp<IBinder>& display,
1472                                    gui::DisplayState* outState) override;
1473     binder::Status getStaticDisplayInfo(int64_t displayId,
1474                                         gui::StaticDisplayInfo* outInfo) override;
1475     binder::Status getDynamicDisplayInfoFromId(int64_t displayId,
1476                                                gui::DynamicDisplayInfo* outInfo) override;
1477     binder::Status getDynamicDisplayInfoFromToken(const sp<IBinder>& display,
1478                                                   gui::DynamicDisplayInfo* outInfo) override;
1479     binder::Status getDisplayNativePrimaries(const sp<IBinder>& display,
1480                                              gui::DisplayPrimaries* outPrimaries) override;
1481     binder::Status setActiveColorMode(const sp<IBinder>& display, int colorMode) override;
1482     binder::Status setBootDisplayMode(const sp<IBinder>& display, int displayModeId) override;
1483     binder::Status clearBootDisplayMode(const sp<IBinder>& display) override;
1484     binder::Status getBootDisplayModeSupport(bool* outMode) override;
1485     binder::Status getOverlaySupport(gui::OverlayProperties* outProperties) override;
1486     binder::Status getHdrConversionCapabilities(
1487             std::vector<gui::HdrConversionCapability>*) override;
1488     binder::Status setHdrConversionStrategy(const gui::HdrConversionStrategy& hdrConversionStrategy,
1489                                             int32_t*) override;
1490     binder::Status getHdrOutputConversionSupport(bool* outSupport) override;
1491     binder::Status setAutoLowLatencyMode(const sp<IBinder>& display, bool on) override;
1492     binder::Status setGameContentType(const sp<IBinder>& display, bool on) override;
1493     binder::Status captureDisplay(const DisplayCaptureArgs&,
1494                                   const sp<IScreenCaptureListener>&) override;
1495     binder::Status captureDisplayById(int64_t, const sp<IScreenCaptureListener>&) override;
1496     binder::Status captureLayers(const LayerCaptureArgs&,
1497                                  const sp<IScreenCaptureListener>&) override;
1498 
1499     // TODO(b/239076119): Remove deprecated AIDL.
clearAnimationFrameStats()1500     [[deprecated]] binder::Status clearAnimationFrameStats() override {
1501         return binder::Status::ok();
1502     }
getAnimationFrameStats(gui::FrameStats *)1503     [[deprecated]] binder::Status getAnimationFrameStats(gui::FrameStats*) override {
1504         return binder::Status::ok();
1505     }
1506 
1507     binder::Status overrideHdrTypes(const sp<IBinder>& display,
1508                                     const std::vector<int32_t>& hdrTypes) override;
1509     binder::Status onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) override;
1510     binder::Status getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) override;
1511     binder::Status getColorManagement(bool* outGetColorManagement) override;
1512     binder::Status getCompositionPreference(gui::CompositionPreference* outPref) override;
1513     binder::Status getDisplayedContentSamplingAttributes(
1514             const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) override;
1515     binder::Status setDisplayContentSamplingEnabled(const sp<IBinder>& display, bool enable,
1516                                                     int8_t componentMask,
1517                                                     int64_t maxFrames) override;
1518     binder::Status getDisplayedContentSample(const sp<IBinder>& display, int64_t maxFrames,
1519                                              int64_t timestamp,
1520                                              gui::DisplayedFrameStats* outStats) override;
1521     binder::Status getProtectedContentSupport(bool* outSupporte) override;
1522     binder::Status isWideColorDisplay(const sp<IBinder>& token,
1523                                       bool* outIsWideColorDisplay) override;
1524     binder::Status addRegionSamplingListener(
1525             const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
1526             const sp<gui::IRegionSamplingListener>& listener) override;
1527     binder::Status removeRegionSamplingListener(
1528             const sp<gui::IRegionSamplingListener>& listener) override;
1529     binder::Status addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) override;
1530     binder::Status removeFpsListener(const sp<gui::IFpsListener>& listener) override;
1531     binder::Status addTunnelModeEnabledListener(
1532             const sp<gui::ITunnelModeEnabledListener>& listener) override;
1533     binder::Status removeTunnelModeEnabledListener(
1534             const sp<gui::ITunnelModeEnabledListener>& listener) override;
1535     binder::Status setDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
1536                                               const gui::DisplayModeSpecs&) override;
1537     binder::Status getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
1538                                               gui::DisplayModeSpecs* outSpecs) override;
1539     binder::Status getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1540                                                bool* outSupport) override;
1541     binder::Status setDisplayBrightness(const sp<IBinder>& displayToken,
1542                                         const gui::DisplayBrightness& brightness) override;
1543     binder::Status addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1544                                            const sp<gui::IHdrLayerInfoListener>& listener) override;
1545     binder::Status removeHdrLayerInfoListener(
1546             const sp<IBinder>& displayToken,
1547             const sp<gui::IHdrLayerInfoListener>& listener) override;
1548 
1549     binder::Status notifyPowerBoost(int boostId) override;
1550     binder::Status setGlobalShadowSettings(const gui::Color& ambientColor,
1551                                            const gui::Color& spotColor, float lightPosY,
1552                                            float lightPosZ, float lightRadius) override;
1553     binder::Status getDisplayDecorationSupport(
1554             const sp<IBinder>& displayToken,
1555             std::optional<gui::DisplayDecorationSupport>* outSupport) override;
1556     binder::Status setOverrideFrameRate(int32_t uid, float frameRate) override;
1557     binder::Status updateSmallAreaDetection(const std::vector<int32_t>& uids,
1558                                             const std::vector<float>& thresholds) override;
1559     binder::Status setSmallAreaDetectionThreshold(int32_t uid, float threshold) override;
1560     binder::Status getGpuContextPriority(int32_t* outPriority) override;
1561     binder::Status getMaxAcquiredBufferCount(int32_t* buffers) override;
1562     binder::Status addWindowInfosListener(const sp<gui::IWindowInfosListener>& windowInfosListener,
1563                                           gui::WindowInfosListenerInfo* outInfo) override;
1564     binder::Status removeWindowInfosListener(
1565             const sp<gui::IWindowInfosListener>& windowInfosListener) override;
1566     binder::Status getStalledTransactionInfo(int pid,
1567                                              std::optional<gui::StalledTransactionInfo>* outInfo);
1568 
1569 private:
1570     static const constexpr bool kUsePermissionCache = true;
1571     status_t checkAccessPermission(bool usePermissionCache = kUsePermissionCache);
1572     status_t checkControlDisplayBrightnessPermission();
1573     status_t checkReadFrameBufferPermission();
1574     static void getDynamicDisplayInfoInternal(ui::DynamicDisplayInfo& info,
1575                                               gui::DynamicDisplayInfo*& outInfo);
1576 
1577 private:
1578     sp<SurfaceFlinger> mFlinger;
1579 };
1580 
1581 } // namespace android
1582