1 /* 2 * Copyright 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <algorithm> 20 #include <numeric> 21 #include <optional> 22 #include <type_traits> 23 #include <utility> 24 25 #include <gui/DisplayEventReceiver.h> 26 27 #include <scheduler/Fps.h> 28 #include <scheduler/Seamlessness.h> 29 30 #include "DisplayHardware/DisplayMode.h" 31 #include "DisplayHardware/HWComposer.h" 32 #include "Scheduler/OneShotTimer.h" 33 #include "Scheduler/StrongTyping.h" 34 35 namespace android::scheduler { 36 37 using namespace std::chrono_literals; 38 39 enum class DisplayModeEvent : unsigned { None = 0b0, Changed = 0b1 }; 40 41 inline DisplayModeEvent operator|(DisplayModeEvent lhs, DisplayModeEvent rhs) { 42 using T = std::underlying_type_t<DisplayModeEvent>; 43 return static_cast<DisplayModeEvent>(static_cast<T>(lhs) | static_cast<T>(rhs)); 44 } 45 46 using FrameRateOverride = DisplayEventReceiver::Event::FrameRateOverride; 47 48 /** 49 * This class is used to encapsulate configuration for refresh rates. It holds information 50 * about available refresh rates on the device, and the mapping between the numbers and human 51 * readable names. 52 */ 53 class RefreshRateConfigs { 54 public: 55 // Margin used when matching refresh rates to the content desired ones. 56 static constexpr nsecs_t MARGIN_FOR_PERIOD_CALCULATION = 57 std::chrono::nanoseconds(800us).count(); 58 59 struct Policy { 60 private: 61 static constexpr int kAllowGroupSwitchingDefault = false; 62 63 public: 64 // The default mode, used to ensure we only initiate display mode switches within the 65 // same mode group as defaultMode's group. 66 DisplayModeId defaultMode; 67 // Whether or not we switch mode groups to get the best frame rate. 68 bool allowGroupSwitching = kAllowGroupSwitchingDefault; 69 // The primary refresh rate range represents display manager's general guidance on the 70 // display modes we'll consider when switching refresh rates. Unless we get an explicit 71 // signal from an app, we should stay within this range. 72 FpsRange primaryRange; 73 // The app request refresh rate range allows us to consider more display modes when 74 // switching refresh rates. Although we should generally stay within the primary range, 75 // specific considerations, such as layer frame rate settings specified via the 76 // setFrameRate() api, may cause us to go outside the primary range. We never go outside the 77 // app request range. The app request range will be greater than or equal to the primary 78 // refresh rate range, never smaller. 79 FpsRange appRequestRange; 80 81 Policy() = default; 82 PolicyPolicy83 Policy(DisplayModeId defaultMode, FpsRange range) 84 : Policy(defaultMode, kAllowGroupSwitchingDefault, range, range) {} 85 PolicyPolicy86 Policy(DisplayModeId defaultMode, bool allowGroupSwitching, FpsRange range) 87 : Policy(defaultMode, allowGroupSwitching, range, range) {} 88 PolicyPolicy89 Policy(DisplayModeId defaultMode, FpsRange primaryRange, FpsRange appRequestRange) 90 : Policy(defaultMode, kAllowGroupSwitchingDefault, primaryRange, appRequestRange) {} 91 PolicyPolicy92 Policy(DisplayModeId defaultMode, bool allowGroupSwitching, FpsRange primaryRange, 93 FpsRange appRequestRange) 94 : defaultMode(defaultMode), 95 allowGroupSwitching(allowGroupSwitching), 96 primaryRange(primaryRange), 97 appRequestRange(appRequestRange) {} 98 99 bool operator==(const Policy& other) const { 100 using namespace fps_approx_ops; 101 return defaultMode == other.defaultMode && primaryRange == other.primaryRange && 102 appRequestRange == other.appRequestRange && 103 allowGroupSwitching == other.allowGroupSwitching; 104 } 105 106 bool operator!=(const Policy& other) const { return !(*this == other); } 107 std::string toString() const; 108 }; 109 110 // Return code set*Policy() to indicate the current policy is unchanged. 111 static constexpr int CURRENT_POLICY_UNCHANGED = 1; 112 113 // We maintain the display manager policy and the override policy separately. The override 114 // policy is used by CTS tests to get a consistent device state for testing. While the override 115 // policy is set, it takes precedence over the display manager policy. Once the override policy 116 // is cleared, we revert to using the display manager policy. 117 118 // Sets the display manager policy to choose refresh rates. The return value will be: 119 // - A negative value if the policy is invalid or another error occurred. 120 // - NO_ERROR if the policy was successfully updated, and the current policy is different from 121 // what it was before the call. 122 // - CURRENT_POLICY_UNCHANGED if the policy was successfully updated, but the current policy 123 // is the same as it was before the call. 124 status_t setDisplayManagerPolicy(const Policy& policy) EXCLUDES(mLock); 125 // Sets the override policy. See setDisplayManagerPolicy() for the meaning of the return value. 126 status_t setOverridePolicy(const std::optional<Policy>& policy) EXCLUDES(mLock); 127 // Gets the current policy, which will be the override policy if active, and the display manager 128 // policy otherwise. 129 Policy getCurrentPolicy() const EXCLUDES(mLock); 130 // Gets the display manager policy, regardless of whether an override policy is active. 131 Policy getDisplayManagerPolicy() const EXCLUDES(mLock); 132 133 // Returns true if mode is allowed by the current policy. 134 bool isModeAllowed(DisplayModeId) const EXCLUDES(mLock); 135 136 // Describes the different options the layer voted for refresh rate 137 enum class LayerVoteType { 138 NoVote, // Doesn't care about the refresh rate 139 Min, // Minimal refresh rate available 140 Max, // Maximal refresh rate available 141 Heuristic, // Specific refresh rate that was calculated by platform using a heuristic 142 ExplicitDefault, // Specific refresh rate that was provided by the app with Default 143 // compatibility 144 ExplicitExactOrMultiple, // Specific refresh rate that was provided by the app with 145 // ExactOrMultiple compatibility 146 ExplicitExact, // Specific refresh rate that was provided by the app with 147 // Exact compatibility 148 149 ftl_last = ExplicitExact 150 }; 151 152 // Captures the layer requirements for a refresh rate. This will be used to determine the 153 // display refresh rate. 154 struct LayerRequirement { 155 // Layer's name. Used for debugging purposes. 156 std::string name; 157 // Layer's owner uid 158 uid_t ownerUid = static_cast<uid_t>(-1); 159 // Layer vote type. 160 LayerVoteType vote = LayerVoteType::NoVote; 161 // Layer's desired refresh rate, if applicable. 162 Fps desiredRefreshRate; 163 // If a seamless mode switch is required. 164 Seamlessness seamlessness = Seamlessness::Default; 165 // Layer's weight in the range of [0, 1]. The higher the weight the more impact this layer 166 // would have on choosing the refresh rate. 167 float weight = 0.0f; 168 // Whether layer is in focus or not based on WindowManager's state 169 bool focused = false; 170 171 bool operator==(const LayerRequirement& other) const { 172 return name == other.name && vote == other.vote && 173 isApproxEqual(desiredRefreshRate, other.desiredRefreshRate) && 174 seamlessness == other.seamlessness && weight == other.weight && 175 focused == other.focused; 176 } 177 178 bool operator!=(const LayerRequirement& other) const { return !(*this == other); } 179 }; 180 181 // Global state describing signals that affect refresh rate choice. 182 struct GlobalSignals { 183 // Whether the user touched the screen recently. Used to apply touch boost. 184 bool touch = false; 185 // True if the system hasn't seen any buffers posted to layers recently. 186 bool idle = false; 187 188 bool operator==(GlobalSignals other) const { 189 return touch == other.touch && idle == other.idle; 190 } 191 }; 192 193 // Returns the refresh rate that best fits the given layers, and whether the refresh rate was 194 // chosen based on touch boost and/or idle timer. 195 std::pair<DisplayModePtr, GlobalSignals> getBestRefreshRate( 196 const std::vector<LayerRequirement>&, GlobalSignals) const EXCLUDES(mLock); 197 getSupportedRefreshRateRange()198 FpsRange getSupportedRefreshRateRange() const EXCLUDES(mLock) { 199 std::lock_guard lock(mLock); 200 return {mMinRefreshRateModeIt->second->getFps(), mMaxRefreshRateModeIt->second->getFps()}; 201 } 202 203 std::optional<Fps> onKernelTimerChanged(std::optional<DisplayModeId> desiredActiveModeId, 204 bool timerExpired) const EXCLUDES(mLock); 205 206 // Returns the highest refresh rate according to the current policy. May change at runtime. Only 207 // uses the primary range, not the app request range. 208 DisplayModePtr getMaxRefreshRateByPolicy() const EXCLUDES(mLock); 209 210 void setActiveModeId(DisplayModeId) EXCLUDES(mLock); 211 DisplayModePtr getActiveMode() const EXCLUDES(mLock); 212 213 // Returns a known frame rate that is the closest to frameRate 214 Fps findClosestKnownFrameRate(Fps frameRate) const; 215 216 enum class KernelIdleTimerController { Sysprop, HwcApi, ftl_last = HwcApi }; 217 218 // Configuration flags. 219 struct Config { 220 bool enableFrameRateOverride = false; 221 222 // Specifies the upper refresh rate threshold (inclusive) for layer vote types of multiple 223 // or heuristic, such that refresh rates higher than this value will not be voted for. 0 if 224 // no threshold is set. 225 int frameRateMultipleThreshold = 0; 226 227 // The Idle Timer timeout. 0 timeout means no idle timer. 228 std::chrono::milliseconds idleTimerTimeout = 0ms; 229 230 // The controller representing how the kernel idle timer will be configured 231 // either on the HWC api or sysprop. 232 std::optional<KernelIdleTimerController> kernelIdleTimerController; 233 }; 234 235 RefreshRateConfigs(DisplayModes, DisplayModeId activeModeId, 236 Config config = {.enableFrameRateOverride = false, 237 .frameRateMultipleThreshold = 0, 238 .idleTimerTimeout = 0ms, 239 .kernelIdleTimerController = {}}); 240 241 RefreshRateConfigs(const RefreshRateConfigs&) = delete; 242 RefreshRateConfigs& operator=(const RefreshRateConfigs&) = delete; 243 244 // Returns whether switching modes (refresh rate or resolution) is possible. 245 // TODO(b/158780872): Consider HAL support, and skip frame rate detection if the modes only 246 // differ in resolution. canSwitch()247 bool canSwitch() const EXCLUDES(mLock) { 248 std::lock_guard lock(mLock); 249 return mDisplayModes.size() > 1; 250 } 251 252 // Class to enumerate options around toggling the kernel timer on and off. 253 enum class KernelIdleTimerAction { 254 TurnOff, // Turn off the idle timer. 255 TurnOn // Turn on the idle timer. 256 }; 257 258 // Checks whether kernel idle timer should be active depending the policy decisions around 259 // refresh rates. 260 KernelIdleTimerAction getIdleTimerAction() const; 261 supportsFrameRateOverrideByContent()262 bool supportsFrameRateOverrideByContent() const { return mSupportsFrameRateOverrideByContent; } 263 264 // Return the display refresh rate divisor to match the layer 265 // frame rate, or 0 if the display refresh rate is not a multiple of the 266 // layer refresh rate. 267 static int getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate); 268 269 // Returns if the provided frame rates have a ratio t*1000/1001 or t*1001/1000 270 // for an integer t. 271 static bool isFractionalPairOrMultiple(Fps, Fps); 272 273 using UidToFrameRateOverride = std::map<uid_t, Fps>; 274 275 // Returns the frame rate override for each uid. 276 UidToFrameRateOverride getFrameRateOverrides(const std::vector<LayerRequirement>&, 277 Fps displayFrameRate, GlobalSignals) const 278 EXCLUDES(mLock); 279 kernelIdleTimerController()280 std::optional<KernelIdleTimerController> kernelIdleTimerController() { 281 return mConfig.kernelIdleTimerController; 282 } 283 284 struct IdleTimerCallbacks { 285 struct Callbacks { 286 std::function<void()> onReset; 287 std::function<void()> onExpired; 288 }; 289 290 Callbacks platform; 291 Callbacks kernel; 292 }; 293 setIdleTimerCallbacks(IdleTimerCallbacks callbacks)294 void setIdleTimerCallbacks(IdleTimerCallbacks callbacks) EXCLUDES(mIdleTimerCallbacksMutex) { 295 std::scoped_lock lock(mIdleTimerCallbacksMutex); 296 mIdleTimerCallbacks = std::move(callbacks); 297 } 298 clearIdleTimerCallbacks()299 void clearIdleTimerCallbacks() EXCLUDES(mIdleTimerCallbacksMutex) { 300 std::scoped_lock lock(mIdleTimerCallbacksMutex); 301 mIdleTimerCallbacks.reset(); 302 } 303 startIdleTimer()304 void startIdleTimer() { 305 if (mIdleTimer) { 306 mIdleTimer->start(); 307 } 308 } 309 stopIdleTimer()310 void stopIdleTimer() { 311 if (mIdleTimer) { 312 mIdleTimer->stop(); 313 } 314 } 315 resetIdleTimer(bool kernelOnly)316 void resetIdleTimer(bool kernelOnly) { 317 if (!mIdleTimer) { 318 return; 319 } 320 if (kernelOnly && !mConfig.kernelIdleTimerController.has_value()) { 321 return; 322 } 323 mIdleTimer->reset(); 324 } 325 326 void dump(std::string& result) const EXCLUDES(mLock); 327 328 std::chrono::milliseconds getIdleTimerTimeout(); 329 330 private: 331 friend struct TestableRefreshRateConfigs; 332 333 void constructAvailableRefreshRates() REQUIRES(mLock); 334 335 std::pair<DisplayModePtr, GlobalSignals> getBestRefreshRateLocked( 336 const std::vector<LayerRequirement>&, GlobalSignals) const REQUIRES(mLock); 337 338 // Returns number of display frames and remainder when dividing the layer refresh period by 339 // display refresh period. 340 std::pair<nsecs_t, nsecs_t> getDisplayFrames(nsecs_t layerPeriod, nsecs_t displayPeriod) const; 341 342 // Returns the lowest refresh rate according to the current policy. May change at runtime. Only 343 // uses the primary range, not the app request range. 344 const DisplayModePtr& getMinRefreshRateByPolicyLocked() const REQUIRES(mLock); 345 346 // Returns the highest refresh rate according to the current policy. May change at runtime. Only 347 // uses the primary range, not the app request range. 348 const DisplayModePtr& getMaxRefreshRateByPolicyLocked(int anchorGroup) const REQUIRES(mLock); getMaxRefreshRateByPolicyLocked()349 const DisplayModePtr& getMaxRefreshRateByPolicyLocked() const REQUIRES(mLock) { 350 return getMaxRefreshRateByPolicyLocked(mActiveModeIt->second->getGroup()); 351 } 352 353 const Policy* getCurrentPolicyLocked() const REQUIRES(mLock); 354 bool isPolicyValidLocked(const Policy& policy) const REQUIRES(mLock); 355 356 // calculates a score for a layer. Used to determine the display refresh rate 357 // and the frame rate override for certains applications. 358 float calculateLayerScoreLocked(const LayerRequirement&, Fps refreshRate, 359 bool isSeamlessSwitch) const REQUIRES(mLock); 360 361 float calculateNonExactMatchingLayerScoreLocked(const LayerRequirement&, Fps refreshRate) const 362 REQUIRES(mLock); 363 364 void updateDisplayModes(DisplayModes, DisplayModeId activeModeId) EXCLUDES(mLock); 365 366 void initializeIdleTimer(); 367 getIdleTimerCallbacks()368 std::optional<IdleTimerCallbacks::Callbacks> getIdleTimerCallbacks() const 369 REQUIRES(mIdleTimerCallbacksMutex) { 370 if (!mIdleTimerCallbacks) return {}; 371 return mConfig.kernelIdleTimerController.has_value() ? mIdleTimerCallbacks->kernel 372 : mIdleTimerCallbacks->platform; 373 } 374 375 // The display modes of the active display. The DisplayModeIterators below are pointers into 376 // this container, so must be invalidated whenever the DisplayModes change. The Policy below 377 // is also dependent, so must be reset as well. 378 DisplayModes mDisplayModes GUARDED_BY(mLock); 379 380 DisplayModeIterator mActiveModeIt GUARDED_BY(mLock); 381 DisplayModeIterator mMinRefreshRateModeIt GUARDED_BY(mLock); 382 DisplayModeIterator mMaxRefreshRateModeIt GUARDED_BY(mLock); 383 384 // Display modes that satisfy the Policy's ranges, filtered and sorted by refresh rate. 385 std::vector<DisplayModeIterator> mPrimaryRefreshRates GUARDED_BY(mLock); 386 std::vector<DisplayModeIterator> mAppRequestRefreshRates GUARDED_BY(mLock); 387 388 Policy mDisplayManagerPolicy GUARDED_BY(mLock); 389 std::optional<Policy> mOverridePolicy GUARDED_BY(mLock); 390 391 mutable std::mutex mLock; 392 393 // A sorted list of known frame rates that a Heuristic layer will choose 394 // from based on the closest value. 395 const std::vector<Fps> mKnownFrameRates; 396 397 const Config mConfig; 398 bool mSupportsFrameRateOverrideByContent; 399 400 struct GetBestRefreshRateCache { 401 std::pair<std::vector<LayerRequirement>, GlobalSignals> arguments; 402 std::pair<DisplayModePtr, GlobalSignals> result; 403 }; 404 mutable std::optional<GetBestRefreshRateCache> mGetBestRefreshRateCache GUARDED_BY(mLock); 405 406 // Declare mIdleTimer last to ensure its thread joins before the mutex/callbacks are destroyed. 407 std::mutex mIdleTimerCallbacksMutex; 408 std::optional<IdleTimerCallbacks> mIdleTimerCallbacks GUARDED_BY(mIdleTimerCallbacksMutex); 409 // Used to detect (lack of) frame activity. 410 std::optional<scheduler::OneShotTimer> mIdleTimer; 411 }; 412 413 } // namespace android::scheduler 414