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