blob: 40e9a8310f5ff63863f370da34f03da30b831bb1 [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"
Ady Abraham2139f732019-11-13 18:56:40 -080034#include "Scheduler/StrongTyping.h"
Dominik Laskowskif8734e02022-08-26 09:06:59 -070035#include "ThreadContext.h"
Dominik Laskowskie70461a2022-08-30 14:42:01 -070036#include "Utils/Dumper.h"
Ana Krulec4593b692019-01-11 22:07:25 -080037
Dominik Laskowski98041832019-08-01 18:35:59 -070038namespace android::scheduler {
Ady Abrahamabc27602020-04-08 17:20:29 -070039
Ady Abraham4ccdcb42020-02-11 17:34:34 -080040using namespace std::chrono_literals;
Dominik Laskowski98041832019-08-01 18:35:59 -070041
Dominik Laskowski068173d2021-08-11 17:22:59 -070042enum class DisplayModeEvent : unsigned { None = 0b0, Changed = 0b1 };
Dominik Laskowski98041832019-08-01 18:35:59 -070043
Dominik Laskowski068173d2021-08-11 17:22:59 -070044inline DisplayModeEvent operator|(DisplayModeEvent lhs, DisplayModeEvent rhs) {
45 using T = std::underlying_type_t<DisplayModeEvent>;
46 return static_cast<DisplayModeEvent>(static_cast<T>(lhs) | static_cast<T>(rhs));
Dominik Laskowski98041832019-08-01 18:35:59 -070047}
Ana Krulecb43429d2019-01-09 14:28:51 -080048
Ady Abraham62f216c2020-10-13 19:07:23 -070049using FrameRateOverride = DisplayEventReceiver::Event::FrameRateOverride;
50
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040051// Selects the refresh rate of a display by ranking its `DisplayModes` in accordance with
52// the DisplayManager (or override) `Policy`, the `LayerRequirement` of each active layer,
53// and `GlobalSignals`.
54class RefreshRateSelector {
Ana Krulecb43429d2019-01-09 14:28:51 -080055public:
Ady Abraham4ccdcb42020-02-11 17:34:34 -080056 // Margin used when matching refresh rates to the content desired ones.
57 static constexpr nsecs_t MARGIN_FOR_PERIOD_CALCULATION =
rnlee3bd610662021-06-23 16:27:57 -070058 std::chrono::nanoseconds(800us).count();
Ady Abraham4ccdcb42020-02-11 17:34:34 -080059
Ady Abraham68636062022-11-16 17:07:25 -080060 // The lowest Render Frame Rate that will ever be selected
Ady Abraham1d173042023-01-04 23:24:47 +000061 static constexpr Fps kMinSupportedFrameRate = 20_Hz;
Ady Abraham68636062022-11-16 17:07:25 -080062
Dominik Laskowski36dced82022-09-02 09:24:00 -070063 class Policy {
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020064 static constexpr int kAllowGroupSwitchingDefault = false;
65
66 public:
Marin Shalamanova7fe3042021-01-29 21:02:08 +010067 // The default mode, used to ensure we only initiate display mode switches within the
68 // same mode group as defaultMode's group.
69 DisplayModeId defaultMode;
70 // Whether or not we switch mode groups to get the best frame rate.
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020071 bool allowGroupSwitching = kAllowGroupSwitchingDefault;
Ady Abraham285f8c12022-10-11 17:12:14 -070072 // The primary refresh rate ranges. @see DisplayModeSpecs.aidl for details.
73 // TODO(b/257072060): use the render range when selecting SF render rate
74 // or the app override frame rate
75 FpsRanges primaryRanges;
76 // The app request refresh rate ranges. @see DisplayModeSpecs.aidl for details.
77 FpsRanges appRequestRanges;
Steven Thomasd4071902020-03-24 16:02:53 -070078
Steven Thomasf734df42020-04-13 21:09:28 -070079 Policy() = default;
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020080
Ady Abraham285f8c12022-10-11 17:12:14 -070081 Policy(DisplayModeId defaultMode, FpsRange range,
82 bool allowGroupSwitching = kAllowGroupSwitchingDefault)
83 : Policy(defaultMode, FpsRanges{range, range}, FpsRanges{range, range},
84 allowGroupSwitching) {}
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020085
Ady Abraham285f8c12022-10-11 17:12:14 -070086 Policy(DisplayModeId defaultMode, FpsRanges primaryRanges, FpsRanges appRequestRanges,
87 bool allowGroupSwitching = kAllowGroupSwitchingDefault)
Marin Shalamanova7fe3042021-01-29 21:02:08 +010088 : defaultMode(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020089 allowGroupSwitching(allowGroupSwitching),
Ady Abraham285f8c12022-10-11 17:12:14 -070090 primaryRanges(primaryRanges),
91 appRequestRanges(appRequestRanges) {}
Steven Thomasf734df42020-04-13 21:09:28 -070092
Steven Thomasd4071902020-03-24 16:02:53 -070093 bool operator==(const Policy& other) const {
Dominik Laskowski953b7fd2022-01-08 19:34:59 -080094 using namespace fps_approx_ops;
Ady Abraham285f8c12022-10-11 17:12:14 -070095 return defaultMode == other.defaultMode && primaryRanges == other.primaryRanges &&
96 appRequestRanges == other.appRequestRanges &&
Steven Thomasd4071902020-03-24 16:02:53 -070097 allowGroupSwitching == other.allowGroupSwitching;
98 }
99
100 bool operator!=(const Policy& other) const { return !(*this == other); }
Ady Abraham90f7fd22023-08-16 11:02:00 -0700101
102 bool primaryRangeIsSingleRate() const {
103 return isApproxEqual(primaryRanges.physical.min, primaryRanges.physical.max);
104 }
105
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100106 std::string toString() const;
Steven Thomasd4071902020-03-24 16:02:53 -0700107 };
108
Dominik Laskowski36dced82022-09-02 09:24:00 -0700109 enum class SetPolicyResult { Invalid, Unchanged, Changed };
Steven Thomasd4071902020-03-24 16:02:53 -0700110
111 // We maintain the display manager policy and the override policy separately. The override
112 // policy is used by CTS tests to get a consistent device state for testing. While the override
113 // policy is set, it takes precedence over the display manager policy. Once the override policy
114 // is cleared, we revert to using the display manager policy.
Dominik Laskowski36dced82022-09-02 09:24:00 -0700115 struct DisplayManagerPolicy : Policy {
116 using Policy::Policy;
117 };
Steven Thomasd4071902020-03-24 16:02:53 -0700118
Dominik Laskowski36dced82022-09-02 09:24:00 -0700119 struct OverridePolicy : Policy {
120 using Policy::Policy;
121 };
122
123 struct NoOverridePolicy {};
124
125 using PolicyVariant = std::variant<DisplayManagerPolicy, OverridePolicy, NoOverridePolicy>;
126
127 SetPolicyResult setPolicy(const PolicyVariant&) EXCLUDES(mLock) REQUIRES(kMainThreadContext);
128
129 void onModeChangeInitiated() REQUIRES(kMainThreadContext) { mNumModeSwitchesInPolicy++; }
130
Steven Thomasd4071902020-03-24 16:02:53 -0700131 // Gets the current policy, which will be the override policy if active, and the display manager
132 // policy otherwise.
133 Policy getCurrentPolicy() const EXCLUDES(mLock);
134 // Gets the display manager policy, regardless of whether an override policy is active.
135 Policy getDisplayManagerPolicy() const EXCLUDES(mLock);
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100136
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100137 // Returns true if mode is allowed by the current policy.
Ady Abrahamace3d052022-11-17 16:25:05 -0800138 bool isModeAllowed(const FrameRateMode&) const EXCLUDES(mLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800139
Ady Abraham8a82ba62020-01-17 12:43:17 -0800140 // Describes the different options the layer voted for refresh rate
141 enum class LayerVoteType {
Ady Abraham71c437d2020-01-31 15:56:57 -0800142 NoVote, // Doesn't care about the refresh rate
143 Min, // Minimal refresh rate available
144 Max, // Maximal refresh rate available
145 Heuristic, // Specific refresh rate that was calculated by platform using a heuristic
146 ExplicitDefault, // Specific refresh rate that was provided by the app with Default
147 // compatibility
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800148 ExplicitExactOrMultiple, // Specific refresh rate that was provided by the app with
149 // ExactOrMultiple compatibility
150 ExplicitExact, // Specific refresh rate that was provided by the app with
151 // Exact compatibility
Rachel Leece6e0042023-06-27 11:22:54 -0700152 ExplicitCategory, // Specific frame rate category was provided by the app
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800153
Rachel Leece6e0042023-06-27 11:22:54 -0700154 ftl_last = ExplicitCategory
Ady Abraham8a82ba62020-01-17 12:43:17 -0800155 };
156
157 // Captures the layer requirements for a refresh rate. This will be used to determine the
158 // display refresh rate.
159 struct LayerRequirement {
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700160 // Layer's name. Used for debugging purposes.
161 std::string name;
Ady Abraham62a0be22020-12-08 16:54:10 -0800162 // Layer's owner uid
163 uid_t ownerUid = static_cast<uid_t>(-1);
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700164 // Layer vote type.
165 LayerVoteType vote = LayerVoteType::NoVote;
166 // Layer's desired refresh rate, if applicable.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700167 Fps desiredRefreshRate;
Marin Shalamanov46084422020-10-13 12:33:42 +0200168 // If a seamless mode switch is required.
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100169 Seamlessness seamlessness = Seamlessness::Default;
Rachel Lee67afbea2023-09-28 15:35:07 -0700170 // Layer frame rate category.
Rachel Leece6e0042023-06-27 11:22:54 -0700171 FrameRateCategory frameRateCategory = FrameRateCategory::Default;
Rachel Lee67afbea2023-09-28 15:35:07 -0700172 // Goes together with frame rate category vote. Allow refresh rate changes only
173 // if there would be no jank.
174 bool frameRateCategorySmoothSwitchOnly = false;
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700175 // Layer's weight in the range of [0, 1]. The higher the weight the more impact this layer
176 // would have on choosing the refresh rate.
177 float weight = 0.0f;
178 // Whether layer is in focus or not based on WindowManager's state
179 bool focused = false;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800180
181 bool operator==(const LayerRequirement& other) const {
182 return name == other.name && vote == other.vote &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700183 isApproxEqual(desiredRefreshRate, other.desiredRefreshRate) &&
Marin Shalamanovbe97cfa2020-12-01 16:02:07 +0100184 seamlessness == other.seamlessness && weight == other.weight &&
Rachel Leece6e0042023-06-27 11:22:54 -0700185 focused == other.focused && frameRateCategory == other.frameRateCategory;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800186 }
187
188 bool operator!=(const LayerRequirement& other) const { return !(*this == other); }
Rachel Leece6e0042023-06-27 11:22:54 -0700189
Rachel Leed0694bc2023-09-12 14:57:58 -0700190 bool isNoVote() const { return RefreshRateSelector::isNoVote(vote); }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800191 };
192
Rachel Leece6e0042023-06-27 11:22:54 -0700193 // Returns true if the layer explicitly instructs to not contribute to refresh rate selection.
194 // In other words, true if the layer should be ignored.
Rachel Leed0694bc2023-09-12 14:57:58 -0700195 static bool isNoVote(LayerVoteType vote) { return vote == LayerVoteType::NoVote; }
Rachel Leece6e0042023-06-27 11:22:54 -0700196
Ady Abrahamdfd62162020-06-10 16:11:56 -0700197 // Global state describing signals that affect refresh rate choice.
198 struct GlobalSignals {
199 // Whether the user touched the screen recently. Used to apply touch boost.
200 bool touch = false;
201 // True if the system hasn't seen any buffers posted to layers recently.
202 bool idle = false;
ramindani38c84982022-08-29 18:02:57 +0000203 // Whether the display is about to be powered on, or has been in PowerMode::ON
204 // within the timeout of DisplayPowerTimer.
205 bool powerOnImminent = false;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200206
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700207 bool operator==(GlobalSignals other) const {
ramindani38c84982022-08-29 18:02:57 +0000208 return touch == other.touch && idle == other.idle &&
209 powerOnImminent == other.powerOnImminent;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200210 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400211
212 auto toString() const {
213 return ftl::Concat("{touch=", touch, ", idle=", idle,
214 ", powerOnImminent=", powerOnImminent, '}');
215 }
Ady Abrahamdfd62162020-06-10 16:11:56 -0700216 };
217
Ady Abraham68636062022-11-16 17:07:25 -0800218 struct ScoredFrameRate {
219 FrameRateMode frameRateMode;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400220 float score = 0.0f;
221
Ady Abraham68636062022-11-16 17:07:25 -0800222 bool operator==(const ScoredFrameRate& other) const {
223 return frameRateMode == other.frameRateMode && score == other.score;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400224 }
225
226 static bool scoresEqual(float lhs, float rhs) {
227 constexpr float kEpsilon = 0.0001f;
228 return std::abs(lhs - rhs) <= kEpsilon;
229 }
230
231 struct DescendingScore {
Ady Abraham68636062022-11-16 17:07:25 -0800232 bool operator()(const ScoredFrameRate& lhs, const ScoredFrameRate& rhs) const {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400233 return lhs.score > rhs.score && !scoresEqual(lhs.score, rhs.score);
234 }
235 };
236 };
237
Ady Abraham68636062022-11-16 17:07:25 -0800238 using FrameRateRanking = std::vector<ScoredFrameRate>;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400239
Ady Abraham68636062022-11-16 17:07:25 -0800240 struct RankedFrameRates {
241 FrameRateRanking ranking; // Ordered by descending score.
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400242 GlobalSignals consideredSignals;
243
Ady Abraham68636062022-11-16 17:07:25 -0800244 bool operator==(const RankedFrameRates& other) const {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400245 return ranking == other.ranking && consideredSignals == other.consideredSignals;
246 }
247 };
248
Ady Abraham68636062022-11-16 17:07:25 -0800249 RankedFrameRates getRankedFrameRates(const std::vector<LayerRequirement>&, GlobalSignals) const
250 EXCLUDES(mLock);
Ana Krulecb43429d2019-01-09 14:28:51 -0800251
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100252 FpsRange getSupportedRefreshRateRange() const EXCLUDES(mLock) {
253 std::lock_guard lock(mLock);
ramindania04b8a52023-08-07 18:49:47 -0700254 return {mMinRefreshRateModeIt->second->getPeakFps(),
255 mMaxRefreshRateModeIt->second->getPeakFps()};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100256 }
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700257
Dominik Laskowski59746512023-11-19 09:30:24 -0500258 ftl::Optional<FrameRateMode> onKernelTimerChanged(ftl::Optional<DisplayModeId> desiredModeIdOpt,
259 bool timerExpired) const EXCLUDES(mLock);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700260
Ady Abrahamace3d052022-11-17 16:25:05 -0800261 void setActiveMode(DisplayModeId, Fps renderFrameRate) EXCLUDES(mLock);
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700262
Ady Abrahamace3d052022-11-17 16:25:05 -0800263 // See mActiveModeOpt for thread safety.
264 FrameRateMode getActiveMode() const EXCLUDES(mLock);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700265
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700266 // Returns a known frame rate that is the closest to frameRate
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100267 Fps findClosestKnownFrameRate(Fps frameRate) const;
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700268
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800269 enum class KernelIdleTimerController { Sysprop, HwcApi, ftl_last = HwcApi };
ramindani32cf0602022-03-02 02:30:29 +0000270
rnlee3bd610662021-06-23 16:27:57 -0700271 // Configuration flags.
272 struct Config {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700273 enum class FrameRateOverride {
274 // Do not override the frame rate for an app
275 Disabled,
276
277 // Override the frame rate for an app to a value which is also
278 // a display refresh rate
Ady Abraham68636062022-11-16 17:07:25 -0800279 AppOverrideNativeRefreshRates,
Ady Abraham8ca643a2022-10-18 18:26:47 -0700280
281 // Override the frame rate for an app to any value
Ady Abraham68636062022-11-16 17:07:25 -0800282 AppOverride,
283
284 // Override the frame rate for all apps and all values.
Ady Abraham8ca643a2022-10-18 18:26:47 -0700285 Enabled,
286
287 ftl_last = Enabled
288 };
289 FrameRateOverride enableFrameRateOverride = FrameRateOverride::Disabled;
rnlee3bd610662021-06-23 16:27:57 -0700290
291 // Specifies the upper refresh rate threshold (inclusive) for layer vote types of multiple
292 // or heuristic, such that refresh rates higher than this value will not be voted for. 0 if
293 // no threshold is set.
294 int frameRateMultipleThreshold = 0;
Ady Abraham9a2ea342021-09-03 17:32:34 -0700295
Ady Abraham6d885932021-09-03 18:05:48 -0700296 // The Idle Timer timeout. 0 timeout means no idle timer.
ramindani32cf0602022-03-02 02:30:29 +0000297 std::chrono::milliseconds idleTimerTimeout = 0ms;
Ady Abraham6d885932021-09-03 18:05:48 -0700298
ramindani32cf0602022-03-02 02:30:29 +0000299 // The controller representing how the kernel idle timer will be configured
300 // either on the HWC api or sysprop.
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400301 ftl::Optional<KernelIdleTimerController> kernelIdleTimerController;
rnlee3bd610662021-06-23 16:27:57 -0700302 };
303
Ady Abraham8ca643a2022-10-18 18:26:47 -0700304 RefreshRateSelector(
305 DisplayModes, DisplayModeId activeModeId,
306 Config config = {.enableFrameRateOverride = Config::FrameRateOverride::Disabled,
307 .frameRateMultipleThreshold = 0,
308 .idleTimerTimeout = 0ms,
309 .kernelIdleTimerController = {}});
Ana Krulec4593b692019-01-11 22:07:25 -0800310
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400311 RefreshRateSelector(const RefreshRateSelector&) = delete;
312 RefreshRateSelector& operator=(const RefreshRateSelector&) = delete;
Dominik Laskowski0c252702021-12-20 20:32:09 -0800313
Dominik Laskowski2b1037b2023-02-11 16:45:36 -0500314 const DisplayModes& displayModes() const { return mDisplayModes; }
315
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100316 // Returns whether switching modes (refresh rate or resolution) is possible.
317 // TODO(b/158780872): Consider HAL support, and skip frame rate detection if the modes only
Ady Abraham68636062022-11-16 17:07:25 -0800318 // differ in resolution. Once Config::FrameRateOverride::Enabled becomes the default,
319 // we can probably remove canSwitch altogether since all devices will be able
320 // to switch to a frame rate divisor.
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100321 bool canSwitch() const EXCLUDES(mLock) {
322 std::lock_guard lock(mLock);
Ady Abraham68636062022-11-16 17:07:25 -0800323 return mDisplayModes.size() > 1 ||
324 mFrameRateOverrideConfig == Config::FrameRateOverride::Enabled;
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100325 }
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700326
TreeHugger Robot758ab612021-06-22 19:17:29 +0000327 // Class to enumerate options around toggling the kernel timer on and off.
Ana Krulecb9afd792020-06-11 13:16:15 -0700328 enum class KernelIdleTimerAction {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400329 TurnOff, // Turn off the idle timer.
330 TurnOn // Turn on the idle timer.
Ana Krulecb9afd792020-06-11 13:16:15 -0700331 };
ramindani32cf0602022-03-02 02:30:29 +0000332
Ana Krulecb9afd792020-06-11 13:16:15 -0700333 // Checks whether kernel idle timer should be active depending the policy decisions around
334 // refresh rates.
335 KernelIdleTimerAction getIdleTimerAction() const;
336
Ady Abraham68636062022-11-16 17:07:25 -0800337 bool supportsAppFrameRateOverrideByContent() const {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700338 return mFrameRateOverrideConfig != Config::FrameRateOverride::Disabled;
339 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800340
Ady Abraham68636062022-11-16 17:07:25 -0800341 bool supportsFrameRateOverride() const {
342 return mFrameRateOverrideConfig == Config::FrameRateOverride::Enabled;
343 }
344
Ady Abrahamcc315492022-02-17 17:06:39 -0800345 // Return the display refresh rate divisor to match the layer
Ady Abraham5cc2e262021-03-25 13:09:17 -0700346 // frame rate, or 0 if the display refresh rate is not a multiple of the
347 // layer refresh rate.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800348 static int getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800349
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200350 // Returns if the provided frame rates have a ratio t*1000/1001 or t*1001/1000
351 // for an integer t.
352 static bool isFractionalPairOrMultiple(Fps, Fps);
353
Ady Abraham62a0be22020-12-08 16:54:10 -0800354 using UidToFrameRateOverride = std::map<uid_t, Fps>;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700355
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800356 // Returns the frame rate override for each uid.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700357 UidToFrameRateOverride getFrameRateOverrides(const std::vector<LayerRequirement>&,
358 Fps displayFrameRate, GlobalSignals) const
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800359 EXCLUDES(mLock);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700360
Rachel Leece6e0042023-06-27 11:22:54 -0700361 // Gets the FpsRange that the FrameRateCategory represents.
362 static FpsRange getFrameRateCategoryRange(FrameRateCategory category);
363
ramindani32cf0602022-03-02 02:30:29 +0000364 std::optional<KernelIdleTimerController> kernelIdleTimerController() {
365 return mConfig.kernelIdleTimerController;
366 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700367
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800368 struct IdleTimerCallbacks {
369 struct Callbacks {
370 std::function<void()> onReset;
371 std::function<void()> onExpired;
372 };
373
374 Callbacks platform;
375 Callbacks kernel;
376 };
377
378 void setIdleTimerCallbacks(IdleTimerCallbacks callbacks) EXCLUDES(mIdleTimerCallbacksMutex) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700379 std::scoped_lock lock(mIdleTimerCallbacksMutex);
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800380 mIdleTimerCallbacks = std::move(callbacks);
381 }
382
383 void clearIdleTimerCallbacks() EXCLUDES(mIdleTimerCallbacksMutex) {
384 std::scoped_lock lock(mIdleTimerCallbacksMutex);
385 mIdleTimerCallbacks.reset();
Ady Abraham11663402021-11-10 19:46:09 -0800386 }
387
388 void startIdleTimer() {
389 if (mIdleTimer) {
390 mIdleTimer->start();
391 }
392 }
393
394 void stopIdleTimer() {
395 if (mIdleTimer) {
396 mIdleTimer->stop();
397 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700398 }
399
Dominik Laskowski596a2562022-10-28 11:26:12 -0400400 void resetKernelIdleTimer() {
401 if (mIdleTimer && mConfig.kernelIdleTimerController) {
402 mIdleTimer->reset();
Ady Abraham9a2ea342021-09-03 17:32:34 -0700403 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400404 }
405
406 void resetIdleTimer() {
407 if (mIdleTimer) {
408 mIdleTimer->reset();
Ady Abraham9a2ea342021-09-03 17:32:34 -0700409 }
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800410 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700411
Dominik Laskowskie70461a2022-08-30 14:42:01 -0700412 void dump(utils::Dumper&) const EXCLUDES(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +0100413
ramindani32cf0602022-03-02 02:30:29 +0000414 std::chrono::milliseconds getIdleTimerTimeout();
415
Dominik Laskowski22488f62019-03-28 09:53:04 -0700416private:
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400417 friend struct TestableRefreshRateSelector;
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700418
Ady Abraham2139f732019-11-13 18:56:40 -0800419 void constructAvailableRefreshRates() REQUIRES(mLock);
420
Ady Abrahamace3d052022-11-17 16:25:05 -0800421 // See mActiveModeOpt for thread safety.
422 const FrameRateMode& getActiveModeLocked() const REQUIRES(mLock);
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700423
Ady Abraham68636062022-11-16 17:07:25 -0800424 RankedFrameRates getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
425 GlobalSignals signals) const REQUIRES(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200426
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800427 // Returns number of display frames and remainder when dividing the layer refresh period by
428 // display refresh period.
429 std::pair<nsecs_t, nsecs_t> getDisplayFrames(nsecs_t layerPeriod, nsecs_t displayPeriod) const;
430
Steven Thomasf734df42020-04-13 21:09:28 -0700431 // Returns the lowest refresh rate according to the current policy. May change at runtime. Only
432 // uses the primary range, not the app request range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800433 const DisplayModePtr& getMinRefreshRateByPolicyLocked() const REQUIRES(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700434
435 // Returns the highest refresh rate according to the current policy. May change at runtime. Only
436 // uses the primary range, not the app request range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800437 const DisplayModePtr& getMaxRefreshRateByPolicyLocked(int anchorGroup) const REQUIRES(mLock);
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200438
ramindanid72ba162022-09-09 21:33:40 +0000439 struct RefreshRateScoreComparator;
440
Ady Abraham68636062022-11-16 17:07:25 -0800441 enum class RefreshRateOrder {
442 Ascending,
443 Descending,
444
445 ftl_last = Descending
446 };
ramindanid72ba162022-09-09 21:33:40 +0000447
Rachel Lee67afbea2023-09-28 15:35:07 -0700448 typedef std::function<bool(const FrameRateMode)> RankFrameRatesPredicate;
449
450 // Rank the frame rates.
451 // Only modes in the primary range for which `predicate` is `true` will be scored.
452 // Does not use the app requested range.
Ady Abraham68636062022-11-16 17:07:25 -0800453 FrameRateRanking rankFrameRates(
454 std::optional<int> anchorGroupOpt, RefreshRateOrder refreshRateOrder,
Rachel Lee67afbea2023-09-28 15:35:07 -0700455 std::optional<DisplayModeId> preferredDisplayModeOpt = std::nullopt,
456 const RankFrameRatesPredicate& predicate = [](FrameRateMode) { return true; }) const
Ady Abraham68636062022-11-16 17:07:25 -0800457 REQUIRES(mLock);
ramindanid72ba162022-09-09 21:33:40 +0000458
Steven Thomasd4071902020-03-24 16:02:53 -0700459 const Policy* getCurrentPolicyLocked() const REQUIRES(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100460 bool isPolicyValidLocked(const Policy& policy) const REQUIRES(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700461
ramindanid72ba162022-09-09 21:33:40 +0000462 // Returns the refresh rate score as a ratio to max refresh rate, which has a score of 1.
Ady Abraham68636062022-11-16 17:07:25 -0800463 float calculateDistanceScoreFromMax(Fps refreshRate) const REQUIRES(mLock);
Ady Abraham62a0be22020-12-08 16:54:10 -0800464 // calculates a score for a layer. Used to determine the display refresh rate
465 // and the frame rate override for certains applications.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800466 float calculateLayerScoreLocked(const LayerRequirement&, Fps refreshRate,
Ady Abraham62a0be22020-12-08 16:54:10 -0800467 bool isSeamlessSwitch) const REQUIRES(mLock);
468
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800469 float calculateNonExactMatchingLayerScoreLocked(const LayerRequirement&, Fps refreshRate) const
470 REQUIRES(mLock);
Ady Abraham05243be2021-09-16 15:58:52 -0700471
Rachel Leece6e0042023-06-27 11:22:54 -0700472 // Calculates the score for non-exact matching layer that has LayerVoteType::ExplicitDefault.
473 float calculateNonExactMatchingDefaultLayerScoreLocked(nsecs_t displayPeriod,
474 nsecs_t layerPeriod) const
475 REQUIRES(mLock);
476
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700477 void updateDisplayModes(DisplayModes, DisplayModeId activeModeId) EXCLUDES(mLock)
478 REQUIRES(kMainThreadContext);
Ady Abraham3efa3942021-06-24 19:01:25 -0700479
Ady Abraham9a2ea342021-09-03 17:32:34 -0700480 void initializeIdleTimer();
481
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800482 std::optional<IdleTimerCallbacks::Callbacks> getIdleTimerCallbacks() const
483 REQUIRES(mIdleTimerCallbacksMutex) {
484 if (!mIdleTimerCallbacks) return {};
ramindani32cf0602022-03-02 02:30:29 +0000485 return mConfig.kernelIdleTimerController.has_value() ? mIdleTimerCallbacks->kernel
486 : mIdleTimerCallbacks->platform;
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800487 }
488
Ady Abraham68636062022-11-16 17:07:25 -0800489 bool isNativeRefreshRate(Fps fps) const REQUIRES(mLock) {
490 LOG_ALWAYS_FATAL_IF(mConfig.enableFrameRateOverride !=
491 Config::FrameRateOverride::AppOverrideNativeRefreshRates,
492 "should only be called when "
493 "Config::FrameRateOverride::AppOverrideNativeRefreshRates is used");
494 return mAppOverrideNativeRefreshRates.contains(fps);
495 }
496
497 std::vector<FrameRateMode> createFrameRateModes(
Ady Abraham90f7fd22023-08-16 11:02:00 -0700498 const Policy&, std::function<bool(const DisplayMode&)>&& filterModes,
499 const FpsRange&) const REQUIRES(mLock);
Ady Abraham68636062022-11-16 17:07:25 -0800500
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800501 // The display modes of the active display. The DisplayModeIterators below are pointers into
502 // this container, so must be invalidated whenever the DisplayModes change. The Policy below
503 // is also dependent, so must be reset as well.
504 DisplayModes mDisplayModes GUARDED_BY(mLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800505
Ady Abraham68636062022-11-16 17:07:25 -0800506 // Set of supported display refresh rates for easy lookup
507 // when FrameRateOverride::AppOverrideNativeRefreshRates is in use.
508 ftl::SmallMap<Fps, ftl::Unit, 8, FpsApproxEqual> mAppOverrideNativeRefreshRates;
509
Ady Abrahamace3d052022-11-17 16:25:05 -0800510 ftl::Optional<FrameRateMode> mActiveModeOpt GUARDED_BY(mLock);
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700511
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800512 DisplayModeIterator mMinRefreshRateModeIt GUARDED_BY(mLock);
513 DisplayModeIterator mMaxRefreshRateModeIt GUARDED_BY(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700514
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800515 // Display modes that satisfy the Policy's ranges, filtered and sorted by refresh rate.
Ady Abraham68636062022-11-16 17:07:25 -0800516 std::vector<FrameRateMode> mPrimaryFrameRates GUARDED_BY(mLock);
517 std::vector<FrameRateMode> mAppRequestFrameRates GUARDED_BY(mLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800518
Steven Thomasd4071902020-03-24 16:02:53 -0700519 Policy mDisplayManagerPolicy GUARDED_BY(mLock);
520 std::optional<Policy> mOverridePolicy GUARDED_BY(mLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800521
Dominik Laskowski36dced82022-09-02 09:24:00 -0700522 unsigned mNumModeSwitchesInPolicy GUARDED_BY(kMainThreadContext) = 0;
523
Ady Abraham2139f732019-11-13 18:56:40 -0800524 mutable std::mutex mLock;
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700525
526 // A sorted list of known frame rates that a Heuristic layer will choose
527 // from based on the closest value.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100528 const std::vector<Fps> mKnownFrameRates;
Ady Abraham64c2fc02020-12-29 12:07:50 -0800529
rnlee3bd610662021-06-23 16:27:57 -0700530 const Config mConfig;
Ady Abrahambd44e8a2023-07-24 11:30:06 -0700531
532 // A list of known frame rates that favors at least 60Hz if there is no exact match display
533 // refresh rate
534 const std::vector<Fps> mFrameRatesThatFavorsAtLeast60 = {23.976_Hz, 25_Hz, 29.97_Hz, 50_Hz,
535 59.94_Hz};
536
Ady Abraham8ca643a2022-10-18 18:26:47 -0700537 Config::FrameRateOverride mFrameRateOverrideConfig;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200538
Ady Abraham68636062022-11-16 17:07:25 -0800539 struct GetRankedFrameRatesCache {
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800540 std::pair<std::vector<LayerRequirement>, GlobalSignals> arguments;
Ady Abraham68636062022-11-16 17:07:25 -0800541 RankedFrameRates result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200542 };
Ady Abraham68636062022-11-16 17:07:25 -0800543 mutable std::optional<GetRankedFrameRatesCache> mGetRankedFrameRatesCache GUARDED_BY(mLock);
Ady Abraham9a2ea342021-09-03 17:32:34 -0700544
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800545 // Declare mIdleTimer last to ensure its thread joins before the mutex/callbacks are destroyed.
Ady Abraham9a2ea342021-09-03 17:32:34 -0700546 std::mutex mIdleTimerCallbacksMutex;
547 std::optional<IdleTimerCallbacks> mIdleTimerCallbacks GUARDED_BY(mIdleTimerCallbacksMutex);
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800548 // Used to detect (lack of) frame activity.
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400549 ftl::Optional<scheduler::OneShotTimer> mIdleTimer;
Ana Krulecb43429d2019-01-09 14:28:51 -0800550};
551
Dominik Laskowski98041832019-08-01 18:35:59 -0700552} // namespace android::scheduler