blob: 998b1b81b1ae1ff8cb34e5b0bdda3be954818cfa [file] [log] [blame]
Ana Krulecb43429d2019-01-09 14:28:51 -08001/*
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
Dominik Laskowski98041832019-08-01 18:35:59 -070019#include <type_traits>
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080020#include <utility>
Dominik Laskowski36dced82022-09-02 09:24:00 -070021#include <variant>
Ana Krulecb43429d2019-01-09 14:28:51 -080022
Dominik Laskowski530d6bd2022-10-10 16:55:54 -040023#include <ftl/concat.h>
Dominik Laskowski03cfce82022-11-02 12:13:29 -040024#include <ftl/optional.h>
Ady Abraham68636062022-11-16 17:07:25 -080025#include <ftl/unit.h>
Dominik Laskowskif6b4ba62021-11-09 12:46:10 -080026#include <gui/DisplayEventReceiver.h>
27
28#include <scheduler/Fps.h>
Ady Abraham68636062022-11-16 17:07:25 -080029#include <scheduler/FrameRateMode.h>
Dominik Laskowskif6b4ba62021-11-09 12:46:10 -080030#include <scheduler/Seamlessness.h>
31
Marin Shalamanov3ea1d602020-12-16 19:59:39 +010032#include "DisplayHardware/DisplayMode.h"
Ady Abraham9a2ea342021-09-03 17:32:34 -070033#include "Scheduler/OneShotTimer.h"
Dominik Laskowskif8734e02022-08-26 09:06:59 -070034#include "ThreadContext.h"
Dominik Laskowskie70461a2022-08-30 14:42:01 -070035#include "Utils/Dumper.h"
Ana Krulec4593b692019-01-11 22:07:25 -080036
Dominik Laskowski98041832019-08-01 18:35:59 -070037namespace android::scheduler {
Ady Abrahamabc27602020-04-08 17:20:29 -070038
Ady Abraham4ccdcb42020-02-11 17:34:34 -080039using namespace std::chrono_literals;
Dominik Laskowski98041832019-08-01 18:35:59 -070040
Ady Abraham62f216c2020-10-13 19:07:23 -070041using FrameRateOverride = DisplayEventReceiver::Event::FrameRateOverride;
42
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040043// Selects the refresh rate of a display by ranking its `DisplayModes` in accordance with
44// the DisplayManager (or override) `Policy`, the `LayerRequirement` of each active layer,
45// and `GlobalSignals`.
46class RefreshRateSelector {
Ana Krulecb43429d2019-01-09 14:28:51 -080047public:
Ady Abraham4ccdcb42020-02-11 17:34:34 -080048 // Margin used when matching refresh rates to the content desired ones.
49 static constexpr nsecs_t MARGIN_FOR_PERIOD_CALCULATION =
rnlee3bd610662021-06-23 16:27:57 -070050 std::chrono::nanoseconds(800us).count();
Ady Abraham4ccdcb42020-02-11 17:34:34 -080051
Ady Abraham68636062022-11-16 17:07:25 -080052 // The lowest Render Frame Rate that will ever be selected
Ady Abraham1d173042023-01-04 23:24:47 +000053 static constexpr Fps kMinSupportedFrameRate = 20_Hz;
Ady Abraham68636062022-11-16 17:07:25 -080054
Dominik Laskowski36dced82022-09-02 09:24:00 -070055 class Policy {
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020056 static constexpr int kAllowGroupSwitchingDefault = false;
57
58 public:
Marin Shalamanova7fe3042021-01-29 21:02:08 +010059 // The default mode, used to ensure we only initiate display mode switches within the
60 // same mode group as defaultMode's group.
61 DisplayModeId defaultMode;
62 // Whether or not we switch mode groups to get the best frame rate.
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020063 bool allowGroupSwitching = kAllowGroupSwitchingDefault;
Ady Abraham285f8c12022-10-11 17:12:14 -070064 // The primary refresh rate ranges. @see DisplayModeSpecs.aidl for details.
65 // TODO(b/257072060): use the render range when selecting SF render rate
66 // or the app override frame rate
67 FpsRanges primaryRanges;
68 // The app request refresh rate ranges. @see DisplayModeSpecs.aidl for details.
69 FpsRanges appRequestRanges;
Ady Abraham67231722024-03-21 18:06:21 -070070 // The idle timer configuration, if provided.
71 std::optional<gui::DisplayModeSpecs::IdleScreenRefreshRateConfig> idleScreenConfigOpt;
Steven Thomasd4071902020-03-24 16:02:53 -070072
Steven Thomasf734df42020-04-13 21:09:28 -070073 Policy() = default;
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020074
Ady Abraham285f8c12022-10-11 17:12:14 -070075 Policy(DisplayModeId defaultMode, FpsRange range,
Ady Abraham67231722024-03-21 18:06:21 -070076 bool allowGroupSwitching = kAllowGroupSwitchingDefault,
77 const std::optional<gui::DisplayModeSpecs::IdleScreenRefreshRateConfig>&
78 idleScreenConfigOpt = std::nullopt)
Ady Abraham285f8c12022-10-11 17:12:14 -070079 : Policy(defaultMode, FpsRanges{range, range}, FpsRanges{range, range},
Ady Abraham67231722024-03-21 18:06:21 -070080 allowGroupSwitching, idleScreenConfigOpt) {}
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020081
Ady Abraham285f8c12022-10-11 17:12:14 -070082 Policy(DisplayModeId defaultMode, FpsRanges primaryRanges, FpsRanges appRequestRanges,
Ady Abraham67231722024-03-21 18:06:21 -070083 bool allowGroupSwitching = kAllowGroupSwitchingDefault,
84 const std::optional<gui::DisplayModeSpecs::IdleScreenRefreshRateConfig>&
85 idleScreenConfigOpt = std::nullopt)
Marin Shalamanova7fe3042021-01-29 21:02:08 +010086 : defaultMode(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020087 allowGroupSwitching(allowGroupSwitching),
Ady Abraham285f8c12022-10-11 17:12:14 -070088 primaryRanges(primaryRanges),
Ady Abraham67231722024-03-21 18:06:21 -070089 appRequestRanges(appRequestRanges),
90 idleScreenConfigOpt(idleScreenConfigOpt) {}
Steven Thomasf734df42020-04-13 21:09:28 -070091
Steven Thomasd4071902020-03-24 16:02:53 -070092 bool operator==(const Policy& other) const {
Dominik Laskowski953b7fd2022-01-08 19:34:59 -080093 using namespace fps_approx_ops;
Ady Abraham67231722024-03-21 18:06:21 -070094 return similarExceptIdleConfig(other) &&
95 idleScreenConfigOpt == other.idleScreenConfigOpt;
Steven Thomasd4071902020-03-24 16:02:53 -070096 }
97
98 bool operator!=(const Policy& other) const { return !(*this == other); }
Ady Abraham90f7fd22023-08-16 11:02:00 -070099
100 bool primaryRangeIsSingleRate() const {
101 return isApproxEqual(primaryRanges.physical.min, primaryRanges.physical.max);
102 }
103
Ady Abraham67231722024-03-21 18:06:21 -0700104 bool similarExceptIdleConfig(const Policy& updated) const {
105 using namespace fps_approx_ops;
106 return defaultMode == updated.defaultMode && primaryRanges == updated.primaryRanges &&
107 appRequestRanges == updated.appRequestRanges &&
108 allowGroupSwitching == updated.allowGroupSwitching;
109 }
110
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100111 std::string toString() const;
Steven Thomasd4071902020-03-24 16:02:53 -0700112 };
113
Dominik Laskowski36dced82022-09-02 09:24:00 -0700114 enum class SetPolicyResult { Invalid, Unchanged, Changed };
Steven Thomasd4071902020-03-24 16:02:53 -0700115
116 // We maintain the display manager policy and the override policy separately. The override
117 // policy is used by CTS tests to get a consistent device state for testing. While the override
118 // policy is set, it takes precedence over the display manager policy. Once the override policy
119 // is cleared, we revert to using the display manager policy.
Dominik Laskowski36dced82022-09-02 09:24:00 -0700120 struct DisplayManagerPolicy : Policy {
121 using Policy::Policy;
122 };
Steven Thomasd4071902020-03-24 16:02:53 -0700123
Dominik Laskowski36dced82022-09-02 09:24:00 -0700124 struct OverridePolicy : Policy {
125 using Policy::Policy;
126 };
127
128 struct NoOverridePolicy {};
129
130 using PolicyVariant = std::variant<DisplayManagerPolicy, OverridePolicy, NoOverridePolicy>;
131
132 SetPolicyResult setPolicy(const PolicyVariant&) EXCLUDES(mLock) REQUIRES(kMainThreadContext);
133
134 void onModeChangeInitiated() REQUIRES(kMainThreadContext) { mNumModeSwitchesInPolicy++; }
135
Steven Thomasd4071902020-03-24 16:02:53 -0700136 // Gets the current policy, which will be the override policy if active, and the display manager
137 // policy otherwise.
138 Policy getCurrentPolicy() const EXCLUDES(mLock);
139 // Gets the display manager policy, regardless of whether an override policy is active.
140 Policy getDisplayManagerPolicy() const EXCLUDES(mLock);
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100141
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100142 // Returns true if mode is allowed by the current policy.
Ady Abrahamace3d052022-11-17 16:25:05 -0800143 bool isModeAllowed(const FrameRateMode&) const EXCLUDES(mLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800144
Ady Abraham8a82ba62020-01-17 12:43:17 -0800145 // Describes the different options the layer voted for refresh rate
146 enum class LayerVoteType {
Ady Abraham71c437d2020-01-31 15:56:57 -0800147 NoVote, // Doesn't care about the refresh rate
148 Min, // Minimal refresh rate available
149 Max, // Maximal refresh rate available
150 Heuristic, // Specific refresh rate that was calculated by platform using a heuristic
151 ExplicitDefault, // Specific refresh rate that was provided by the app with Default
152 // compatibility
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800153 ExplicitExactOrMultiple, // Specific refresh rate that was provided by the app with
154 // ExactOrMultiple compatibility
155 ExplicitExact, // Specific refresh rate that was provided by the app with
156 // Exact compatibility
Rachel Leee5514a72023-10-25 16:20:29 -0700157 ExplicitGte, // Greater than or equal to frame rate provided by the app
Rachel Leece6e0042023-06-27 11:22:54 -0700158 ExplicitCategory, // Specific frame rate category was provided by the app
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800159
Rachel Leece6e0042023-06-27 11:22:54 -0700160 ftl_last = ExplicitCategory
Ady Abraham8a82ba62020-01-17 12:43:17 -0800161 };
162
163 // Captures the layer requirements for a refresh rate. This will be used to determine the
164 // display refresh rate.
165 struct LayerRequirement {
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700166 // Layer's name. Used for debugging purposes.
167 std::string name;
Ady Abraham62a0be22020-12-08 16:54:10 -0800168 // Layer's owner uid
169 uid_t ownerUid = static_cast<uid_t>(-1);
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700170 // Layer vote type.
171 LayerVoteType vote = LayerVoteType::NoVote;
172 // Layer's desired refresh rate, if applicable.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700173 Fps desiredRefreshRate;
Marin Shalamanov46084422020-10-13 12:33:42 +0200174 // If a seamless mode switch is required.
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100175 Seamlessness seamlessness = Seamlessness::Default;
Rachel Lee67afbea2023-09-28 15:35:07 -0700176 // Layer frame rate category.
Rachel Leece6e0042023-06-27 11:22:54 -0700177 FrameRateCategory frameRateCategory = FrameRateCategory::Default;
Rachel Lee67afbea2023-09-28 15:35:07 -0700178 // Goes together with frame rate category vote. Allow refresh rate changes only
179 // if there would be no jank.
180 bool frameRateCategorySmoothSwitchOnly = false;
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700181 // Layer's weight in the range of [0, 1]. The higher the weight the more impact this layer
182 // would have on choosing the refresh rate.
183 float weight = 0.0f;
184 // Whether layer is in focus or not based on WindowManager's state
185 bool focused = false;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800186
187 bool operator==(const LayerRequirement& other) const {
188 return name == other.name && vote == other.vote &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700189 isApproxEqual(desiredRefreshRate, other.desiredRefreshRate) &&
Marin Shalamanovbe97cfa2020-12-01 16:02:07 +0100190 seamlessness == other.seamlessness && weight == other.weight &&
Rachel Leece6e0042023-06-27 11:22:54 -0700191 focused == other.focused && frameRateCategory == other.frameRateCategory;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800192 }
193
194 bool operator!=(const LayerRequirement& other) const { return !(*this == other); }
Rachel Leece6e0042023-06-27 11:22:54 -0700195
Rachel Leed0694bc2023-09-12 14:57:58 -0700196 bool isNoVote() const { return RefreshRateSelector::isNoVote(vote); }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800197 };
198
Rachel Leece6e0042023-06-27 11:22:54 -0700199 // Returns true if the layer explicitly instructs to not contribute to refresh rate selection.
200 // In other words, true if the layer should be ignored.
Rachel Leed0694bc2023-09-12 14:57:58 -0700201 static bool isNoVote(LayerVoteType vote) { return vote == LayerVoteType::NoVote; }
Rachel Leece6e0042023-06-27 11:22:54 -0700202
Ady Abrahamdfd62162020-06-10 16:11:56 -0700203 // Global state describing signals that affect refresh rate choice.
204 struct GlobalSignals {
205 // Whether the user touched the screen recently. Used to apply touch boost.
206 bool touch = false;
207 // True if the system hasn't seen any buffers posted to layers recently.
208 bool idle = false;
ramindani38c84982022-08-29 18:02:57 +0000209 // Whether the display is about to be powered on, or has been in PowerMode::ON
210 // within the timeout of DisplayPowerTimer.
211 bool powerOnImminent = false;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200212
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700213 bool operator==(GlobalSignals other) const {
ramindani38c84982022-08-29 18:02:57 +0000214 return touch == other.touch && idle == other.idle &&
215 powerOnImminent == other.powerOnImminent;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200216 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400217
218 auto toString() const {
219 return ftl::Concat("{touch=", touch, ", idle=", idle,
220 ", powerOnImminent=", powerOnImminent, '}');
221 }
Ady Abrahamdfd62162020-06-10 16:11:56 -0700222 };
223
Ady Abraham68636062022-11-16 17:07:25 -0800224 struct ScoredFrameRate {
225 FrameRateMode frameRateMode;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400226 float score = 0.0f;
227
Ady Abraham68636062022-11-16 17:07:25 -0800228 bool operator==(const ScoredFrameRate& other) const {
229 return frameRateMode == other.frameRateMode && score == other.score;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400230 }
231
232 static bool scoresEqual(float lhs, float rhs) {
233 constexpr float kEpsilon = 0.0001f;
234 return std::abs(lhs - rhs) <= kEpsilon;
235 }
236
237 struct DescendingScore {
Ady Abraham68636062022-11-16 17:07:25 -0800238 bool operator()(const ScoredFrameRate& lhs, const ScoredFrameRate& rhs) const {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400239 return lhs.score > rhs.score && !scoresEqual(lhs.score, rhs.score);
240 }
241 };
242 };
243
Ady Abraham68636062022-11-16 17:07:25 -0800244 using FrameRateRanking = std::vector<ScoredFrameRate>;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400245
Ady Abraham68636062022-11-16 17:07:25 -0800246 struct RankedFrameRates {
247 FrameRateRanking ranking; // Ordered by descending score.
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400248 GlobalSignals consideredSignals;
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500249 Fps pacesetterFps;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400250
Ady Abraham68636062022-11-16 17:07:25 -0800251 bool operator==(const RankedFrameRates& other) const {
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500252 return ranking == other.ranking && consideredSignals == other.consideredSignals &&
253 isApproxEqual(pacesetterFps, other.pacesetterFps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400254 }
255 };
256
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500257 // If valid, `pacesetterFps` (used by follower displays) filters the ranking to modes matching
258 // that refresh rate.
259 RankedFrameRates getRankedFrameRates(const std::vector<LayerRequirement>&, GlobalSignals,
260 Fps pacesetterFps = {}) const EXCLUDES(mLock);
Ana Krulecb43429d2019-01-09 14:28:51 -0800261
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100262 FpsRange getSupportedRefreshRateRange() const EXCLUDES(mLock) {
263 std::lock_guard lock(mLock);
ramindania04b8a52023-08-07 18:49:47 -0700264 return {mMinRefreshRateModeIt->second->getPeakFps(),
265 mMaxRefreshRateModeIt->second->getPeakFps()};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100266 }
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700267
Dominik Laskowski59746512023-11-19 09:30:24 -0500268 ftl::Optional<FrameRateMode> onKernelTimerChanged(ftl::Optional<DisplayModeId> desiredModeIdOpt,
269 bool timerExpired) const EXCLUDES(mLock);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700270
Ady Abrahamace3d052022-11-17 16:25:05 -0800271 void setActiveMode(DisplayModeId, Fps renderFrameRate) EXCLUDES(mLock);
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700272
Ady Abrahamace3d052022-11-17 16:25:05 -0800273 // See mActiveModeOpt for thread safety.
274 FrameRateMode getActiveMode() const EXCLUDES(mLock);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700275
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700276 // Returns a known frame rate that is the closest to frameRate
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100277 Fps findClosestKnownFrameRate(Fps frameRate) const;
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700278
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800279 enum class KernelIdleTimerController { Sysprop, HwcApi, ftl_last = HwcApi };
ramindani32cf0602022-03-02 02:30:29 +0000280
rnlee3bd610662021-06-23 16:27:57 -0700281 // Configuration flags.
282 struct Config {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700283 enum class FrameRateOverride {
284 // Do not override the frame rate for an app
285 Disabled,
286
287 // Override the frame rate for an app to a value which is also
288 // a display refresh rate
Ady Abraham68636062022-11-16 17:07:25 -0800289 AppOverrideNativeRefreshRates,
Ady Abraham8ca643a2022-10-18 18:26:47 -0700290
291 // Override the frame rate for an app to any value
Ady Abraham68636062022-11-16 17:07:25 -0800292 AppOverride,
293
294 // Override the frame rate for all apps and all values.
Ady Abraham8ca643a2022-10-18 18:26:47 -0700295 Enabled,
296
297 ftl_last = Enabled
298 };
299 FrameRateOverride enableFrameRateOverride = FrameRateOverride::Disabled;
rnlee3bd610662021-06-23 16:27:57 -0700300
301 // Specifies the upper refresh rate threshold (inclusive) for layer vote types of multiple
302 // or heuristic, such that refresh rates higher than this value will not be voted for. 0 if
303 // no threshold is set.
304 int frameRateMultipleThreshold = 0;
Ady Abraham9a2ea342021-09-03 17:32:34 -0700305
Ady Abraham6d885932021-09-03 18:05:48 -0700306 // The Idle Timer timeout. 0 timeout means no idle timer.
Ady Abraham67231722024-03-21 18:06:21 -0700307 std::chrono::milliseconds legacyIdleTimerTimeout = 0ms;
Ady Abraham6d885932021-09-03 18:05:48 -0700308
ramindani32cf0602022-03-02 02:30:29 +0000309 // The controller representing how the kernel idle timer will be configured
310 // either on the HWC api or sysprop.
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400311 ftl::Optional<KernelIdleTimerController> kernelIdleTimerController;
rnlee3bd610662021-06-23 16:27:57 -0700312 };
313
Ady Abraham8ca643a2022-10-18 18:26:47 -0700314 RefreshRateSelector(
315 DisplayModes, DisplayModeId activeModeId,
316 Config config = {.enableFrameRateOverride = Config::FrameRateOverride::Disabled,
317 .frameRateMultipleThreshold = 0,
Ady Abraham67231722024-03-21 18:06:21 -0700318 .legacyIdleTimerTimeout = 0ms,
Ady Abraham8ca643a2022-10-18 18:26:47 -0700319 .kernelIdleTimerController = {}});
Ana Krulec4593b692019-01-11 22:07:25 -0800320
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400321 RefreshRateSelector(const RefreshRateSelector&) = delete;
322 RefreshRateSelector& operator=(const RefreshRateSelector&) = delete;
Dominik Laskowski0c252702021-12-20 20:32:09 -0800323
Liz Prucka81da2ab2024-07-22 18:38:27 +0000324 DisplayModes displayModes() const {
325 std::lock_guard lock(mLock);
326 return mDisplayModes;
327 }
Dominik Laskowski2b1037b2023-02-11 16:45:36 -0500328
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100329 // Returns whether switching modes (refresh rate or resolution) is possible.
330 // TODO(b/158780872): Consider HAL support, and skip frame rate detection if the modes only
Ady Abraham68636062022-11-16 17:07:25 -0800331 // differ in resolution. Once Config::FrameRateOverride::Enabled becomes the default,
332 // we can probably remove canSwitch altogether since all devices will be able
333 // to switch to a frame rate divisor.
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100334 bool canSwitch() const EXCLUDES(mLock) {
335 std::lock_guard lock(mLock);
Ady Abraham68636062022-11-16 17:07:25 -0800336 return mDisplayModes.size() > 1 ||
337 mFrameRateOverrideConfig == Config::FrameRateOverride::Enabled;
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100338 }
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700339
TreeHugger Robot758ab612021-06-22 19:17:29 +0000340 // Class to enumerate options around toggling the kernel timer on and off.
Ana Krulecb9afd792020-06-11 13:16:15 -0700341 enum class KernelIdleTimerAction {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400342 TurnOff, // Turn off the idle timer.
343 TurnOn // Turn on the idle timer.
Ana Krulecb9afd792020-06-11 13:16:15 -0700344 };
ramindani32cf0602022-03-02 02:30:29 +0000345
Ana Krulecb9afd792020-06-11 13:16:15 -0700346 // Checks whether kernel idle timer should be active depending the policy decisions around
347 // refresh rates.
348 KernelIdleTimerAction getIdleTimerAction() const;
349
Ady Abraham68636062022-11-16 17:07:25 -0800350 bool supportsAppFrameRateOverrideByContent() const {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700351 return mFrameRateOverrideConfig != Config::FrameRateOverride::Disabled;
352 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800353
Ady Abraham68636062022-11-16 17:07:25 -0800354 bool supportsFrameRateOverride() const {
355 return mFrameRateOverrideConfig == Config::FrameRateOverride::Enabled;
356 }
357
Ady Abrahamcc315492022-02-17 17:06:39 -0800358 // Return the display refresh rate divisor to match the layer
Ady Abraham5cc2e262021-03-25 13:09:17 -0700359 // frame rate, or 0 if the display refresh rate is not a multiple of the
360 // layer refresh rate.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800361 static int getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800362
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200363 // Returns if the provided frame rates have a ratio t*1000/1001 or t*1001/1000
364 // for an integer t.
365 static bool isFractionalPairOrMultiple(Fps, Fps);
366
Ady Abraham62a0be22020-12-08 16:54:10 -0800367 using UidToFrameRateOverride = std::map<uid_t, Fps>;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700368
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800369 // Returns the frame rate override for each uid.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700370 UidToFrameRateOverride getFrameRateOverrides(const std::vector<LayerRequirement>&,
371 Fps displayFrameRate, GlobalSignals) const
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800372 EXCLUDES(mLock);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700373
Rachel Leece6e0042023-06-27 11:22:54 -0700374 // Gets the FpsRange that the FrameRateCategory represents.
375 static FpsRange getFrameRateCategoryRange(FrameRateCategory category);
376
ramindani32cf0602022-03-02 02:30:29 +0000377 std::optional<KernelIdleTimerController> kernelIdleTimerController() {
378 return mConfig.kernelIdleTimerController;
379 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700380
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800381 struct IdleTimerCallbacks {
382 struct Callbacks {
383 std::function<void()> onReset;
384 std::function<void()> onExpired;
385 };
386
387 Callbacks platform;
388 Callbacks kernel;
Ady Abrahame2946322024-07-10 17:45:29 -0700389 Callbacks vrr;
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800390 };
391
392 void setIdleTimerCallbacks(IdleTimerCallbacks callbacks) EXCLUDES(mIdleTimerCallbacksMutex) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700393 std::scoped_lock lock(mIdleTimerCallbacksMutex);
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800394 mIdleTimerCallbacks = std::move(callbacks);
395 }
396
397 void clearIdleTimerCallbacks() EXCLUDES(mIdleTimerCallbacksMutex) {
398 std::scoped_lock lock(mIdleTimerCallbacksMutex);
399 mIdleTimerCallbacks.reset();
Ady Abraham11663402021-11-10 19:46:09 -0800400 }
401
402 void startIdleTimer() {
Ady Abraham67231722024-03-21 18:06:21 -0700403 mIdleTimerStarted = true;
Ady Abraham11663402021-11-10 19:46:09 -0800404 if (mIdleTimer) {
405 mIdleTimer->start();
406 }
407 }
408
409 void stopIdleTimer() {
Ady Abraham67231722024-03-21 18:06:21 -0700410 mIdleTimerStarted = false;
Ady Abraham11663402021-11-10 19:46:09 -0800411 if (mIdleTimer) {
412 mIdleTimer->stop();
413 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700414 }
415
Dominik Laskowski596a2562022-10-28 11:26:12 -0400416 void resetKernelIdleTimer() {
417 if (mIdleTimer && mConfig.kernelIdleTimerController) {
418 mIdleTimer->reset();
Ady Abraham9a2ea342021-09-03 17:32:34 -0700419 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400420 }
421
422 void resetIdleTimer() {
423 if (mIdleTimer) {
424 mIdleTimer->reset();
Ady Abraham9a2ea342021-09-03 17:32:34 -0700425 }
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800426 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700427
Dominik Laskowskie70461a2022-08-30 14:42:01 -0700428 void dump(utils::Dumper&) const EXCLUDES(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +0100429
ramindani32cf0602022-03-02 02:30:29 +0000430 std::chrono::milliseconds getIdleTimerTimeout();
431
Rachel Lee45681982024-03-14 18:40:15 -0700432 bool isVrrDevice() const;
433
Dominik Laskowski22488f62019-03-28 09:53:04 -0700434private:
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400435 friend struct TestableRefreshRateSelector;
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700436
Ady Abraham2139f732019-11-13 18:56:40 -0800437 void constructAvailableRefreshRates() REQUIRES(mLock);
438
Ady Abrahamace3d052022-11-17 16:25:05 -0800439 // See mActiveModeOpt for thread safety.
440 const FrameRateMode& getActiveModeLocked() const REQUIRES(mLock);
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700441
Ady Abraham68636062022-11-16 17:07:25 -0800442 RankedFrameRates getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500443 GlobalSignals signals, Fps pacesetterFps) const
444 REQUIRES(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200445
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800446 // Returns number of display frames and remainder when dividing the layer refresh period by
447 // display refresh period.
448 std::pair<nsecs_t, nsecs_t> getDisplayFrames(nsecs_t layerPeriod, nsecs_t displayPeriod) const;
449
Steven Thomasf734df42020-04-13 21:09:28 -0700450 // Returns the lowest refresh rate according to the current policy. May change at runtime. Only
451 // uses the primary range, not the app request range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800452 const DisplayModePtr& getMinRefreshRateByPolicyLocked() const REQUIRES(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700453
454 // Returns the highest refresh rate according to the current policy. May change at runtime. Only
455 // uses the primary range, not the app request range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800456 const DisplayModePtr& getMaxRefreshRateByPolicyLocked(int anchorGroup) const REQUIRES(mLock);
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200457
ramindanid72ba162022-09-09 21:33:40 +0000458 struct RefreshRateScoreComparator;
459
Ady Abraham68636062022-11-16 17:07:25 -0800460 enum class RefreshRateOrder {
461 Ascending,
462 Descending,
463
464 ftl_last = Descending
465 };
ramindanid72ba162022-09-09 21:33:40 +0000466
Rachel Lee67afbea2023-09-28 15:35:07 -0700467 typedef std::function<bool(const FrameRateMode)> RankFrameRatesPredicate;
468
469 // Rank the frame rates.
470 // Only modes in the primary range for which `predicate` is `true` will be scored.
471 // Does not use the app requested range.
Ady Abraham68636062022-11-16 17:07:25 -0800472 FrameRateRanking rankFrameRates(
473 std::optional<int> anchorGroupOpt, RefreshRateOrder refreshRateOrder,
Rachel Lee67afbea2023-09-28 15:35:07 -0700474 std::optional<DisplayModeId> preferredDisplayModeOpt = std::nullopt,
475 const RankFrameRatesPredicate& predicate = [](FrameRateMode) { return true; }) const
Ady Abraham68636062022-11-16 17:07:25 -0800476 REQUIRES(mLock);
ramindanid72ba162022-09-09 21:33:40 +0000477
Steven Thomasd4071902020-03-24 16:02:53 -0700478 const Policy* getCurrentPolicyLocked() const REQUIRES(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100479 bool isPolicyValidLocked(const Policy& policy) const REQUIRES(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700480
ramindanid72ba162022-09-09 21:33:40 +0000481 // Returns the refresh rate score as a ratio to max refresh rate, which has a score of 1.
Rachel Leee5514a72023-10-25 16:20:29 -0700482 float calculateDistanceScoreFromMaxLocked(Fps refreshRate) const REQUIRES(mLock);
483
484 // Returns the refresh rate score based on its distance from the reference rate.
485 float calculateDistanceScoreLocked(Fps referenceRate, Fps refreshRate) const REQUIRES(mLock);
486
Ady Abraham62a0be22020-12-08 16:54:10 -0800487 // calculates a score for a layer. Used to determine the display refresh rate
488 // and the frame rate override for certains applications.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800489 float calculateLayerScoreLocked(const LayerRequirement&, Fps refreshRate,
Ady Abraham62a0be22020-12-08 16:54:10 -0800490 bool isSeamlessSwitch) const REQUIRES(mLock);
491
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800492 float calculateNonExactMatchingLayerScoreLocked(const LayerRequirement&, Fps refreshRate) const
493 REQUIRES(mLock);
Ady Abraham05243be2021-09-16 15:58:52 -0700494
Rachel Leece6e0042023-06-27 11:22:54 -0700495 // Calculates the score for non-exact matching layer that has LayerVoteType::ExplicitDefault.
496 float calculateNonExactMatchingDefaultLayerScoreLocked(nsecs_t displayPeriod,
497 nsecs_t layerPeriod) const
498 REQUIRES(mLock);
499
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700500 void updateDisplayModes(DisplayModes, DisplayModeId activeModeId) EXCLUDES(mLock)
501 REQUIRES(kMainThreadContext);
Ady Abraham3efa3942021-06-24 19:01:25 -0700502
Ady Abraham67231722024-03-21 18:06:21 -0700503 void initializeIdleTimer(std::chrono::milliseconds timeout);
Ady Abraham9a2ea342021-09-03 17:32:34 -0700504
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800505 std::optional<IdleTimerCallbacks::Callbacks> getIdleTimerCallbacks() const
506 REQUIRES(mIdleTimerCallbacksMutex) {
507 if (!mIdleTimerCallbacks) return {};
Ady Abrahame2946322024-07-10 17:45:29 -0700508
509 if (mIsVrrDevice) return mIdleTimerCallbacks->vrr;
510
ramindani32cf0602022-03-02 02:30:29 +0000511 return mConfig.kernelIdleTimerController.has_value() ? mIdleTimerCallbacks->kernel
512 : mIdleTimerCallbacks->platform;
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800513 }
514
Ady Abraham68636062022-11-16 17:07:25 -0800515 bool isNativeRefreshRate(Fps fps) const REQUIRES(mLock) {
516 LOG_ALWAYS_FATAL_IF(mConfig.enableFrameRateOverride !=
517 Config::FrameRateOverride::AppOverrideNativeRefreshRates,
518 "should only be called when "
519 "Config::FrameRateOverride::AppOverrideNativeRefreshRates is used");
520 return mAppOverrideNativeRefreshRates.contains(fps);
521 }
522
523 std::vector<FrameRateMode> createFrameRateModes(
Ady Abraham90f7fd22023-08-16 11:02:00 -0700524 const Policy&, std::function<bool(const DisplayMode&)>&& filterModes,
525 const FpsRange&) const REQUIRES(mLock);
Ady Abraham68636062022-11-16 17:07:25 -0800526
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800527 // The display modes of the active display. The DisplayModeIterators below are pointers into
528 // this container, so must be invalidated whenever the DisplayModes change. The Policy below
529 // is also dependent, so must be reset as well.
530 DisplayModes mDisplayModes GUARDED_BY(mLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800531
Ady Abraham68636062022-11-16 17:07:25 -0800532 // Set of supported display refresh rates for easy lookup
533 // when FrameRateOverride::AppOverrideNativeRefreshRates is in use.
534 ftl::SmallMap<Fps, ftl::Unit, 8, FpsApproxEqual> mAppOverrideNativeRefreshRates;
535
Ady Abrahamace3d052022-11-17 16:25:05 -0800536 ftl::Optional<FrameRateMode> mActiveModeOpt GUARDED_BY(mLock);
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700537
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800538 DisplayModeIterator mMinRefreshRateModeIt GUARDED_BY(mLock);
539 DisplayModeIterator mMaxRefreshRateModeIt GUARDED_BY(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700540
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800541 // Display modes that satisfy the Policy's ranges, filtered and sorted by refresh rate.
Ady Abraham68636062022-11-16 17:07:25 -0800542 std::vector<FrameRateMode> mPrimaryFrameRates GUARDED_BY(mLock);
543 std::vector<FrameRateMode> mAppRequestFrameRates GUARDED_BY(mLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800544
Rachel Lee45681982024-03-14 18:40:15 -0700545 // Caches whether the device is VRR-compatible based on the active display mode.
Ady Abrahame2946322024-07-10 17:45:29 -0700546 std::atomic_bool mIsVrrDevice = false;
Rachel Lee45681982024-03-14 18:40:15 -0700547
Steven Thomasd4071902020-03-24 16:02:53 -0700548 Policy mDisplayManagerPolicy GUARDED_BY(mLock);
549 std::optional<Policy> mOverridePolicy GUARDED_BY(mLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800550
Dominik Laskowski36dced82022-09-02 09:24:00 -0700551 unsigned mNumModeSwitchesInPolicy GUARDED_BY(kMainThreadContext) = 0;
552
Ady Abraham2139f732019-11-13 18:56:40 -0800553 mutable std::mutex mLock;
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700554
555 // A sorted list of known frame rates that a Heuristic layer will choose
556 // from based on the closest value.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100557 const std::vector<Fps> mKnownFrameRates;
Ady Abraham64c2fc02020-12-29 12:07:50 -0800558
rnlee3bd610662021-06-23 16:27:57 -0700559 const Config mConfig;
Ady Abrahambd44e8a2023-07-24 11:30:06 -0700560
561 // A list of known frame rates that favors at least 60Hz if there is no exact match display
562 // refresh rate
563 const std::vector<Fps> mFrameRatesThatFavorsAtLeast60 = {23.976_Hz, 25_Hz, 29.97_Hz, 50_Hz,
564 59.94_Hz};
565
Ady Abraham8ca643a2022-10-18 18:26:47 -0700566 Config::FrameRateOverride mFrameRateOverrideConfig;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200567
Ady Abraham68636062022-11-16 17:07:25 -0800568 struct GetRankedFrameRatesCache {
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500569 std::vector<LayerRequirement> layers;
570 GlobalSignals signals;
571 Fps pacesetterFps;
572
Ady Abraham68636062022-11-16 17:07:25 -0800573 RankedFrameRates result;
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500574
575 bool matches(const GetRankedFrameRatesCache& other) const {
576 return layers == other.layers && signals == other.signals &&
577 isApproxEqual(pacesetterFps, other.pacesetterFps);
578 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200579 };
Ady Abraham68636062022-11-16 17:07:25 -0800580 mutable std::optional<GetRankedFrameRatesCache> mGetRankedFrameRatesCache GUARDED_BY(mLock);
Ady Abraham9a2ea342021-09-03 17:32:34 -0700581
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800582 // Declare mIdleTimer last to ensure its thread joins before the mutex/callbacks are destroyed.
Ady Abraham9a2ea342021-09-03 17:32:34 -0700583 std::mutex mIdleTimerCallbacksMutex;
584 std::optional<IdleTimerCallbacks> mIdleTimerCallbacks GUARDED_BY(mIdleTimerCallbacksMutex);
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800585 // Used to detect (lack of) frame activity.
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400586 ftl::Optional<scheduler::OneShotTimer> mIdleTimer;
Ady Abraham67231722024-03-21 18:06:21 -0700587 std::atomic<bool> mIdleTimerStarted = false;
Ana Krulecb43429d2019-01-09 14:28:51 -0800588};
589
Dominik Laskowski98041832019-08-01 18:35:59 -0700590} // namespace android::scheduler