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