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