blob: 41db38d705582399a0246ac74c27cc3d752b7021 [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
19#include <algorithm>
20#include <numeric>
Ady Abrahambd44e8a2023-07-24 11:30:06 -070021#include <set>
Dominik Laskowski98041832019-08-01 18:35:59 -070022#include <type_traits>
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080023#include <utility>
Dominik Laskowski36dced82022-09-02 09:24:00 -070024#include <variant>
Ana Krulecb43429d2019-01-09 14:28:51 -080025
Dominik Laskowski530d6bd2022-10-10 16:55:54 -040026#include <ftl/concat.h>
Dominik Laskowski03cfce82022-11-02 12:13:29 -040027#include <ftl/optional.h>
Ady Abraham68636062022-11-16 17:07:25 -080028#include <ftl/unit.h>
Dominik Laskowskif6b4ba62021-11-09 12:46:10 -080029#include <gui/DisplayEventReceiver.h>
30
31#include <scheduler/Fps.h>
Ady Abraham68636062022-11-16 17:07:25 -080032#include <scheduler/FrameRateMode.h>
Dominik Laskowskif6b4ba62021-11-09 12:46:10 -080033#include <scheduler/Seamlessness.h>
34
Marin Shalamanov3ea1d602020-12-16 19:59:39 +010035#include "DisplayHardware/DisplayMode.h"
Ady Abraham9a2ea342021-09-03 17:32:34 -070036#include "Scheduler/OneShotTimer.h"
Ady Abraham2139f732019-11-13 18:56:40 -080037#include "Scheduler/StrongTyping.h"
Dominik Laskowskif8734e02022-08-26 09:06:59 -070038#include "ThreadContext.h"
Dominik Laskowskie70461a2022-08-30 14:42:01 -070039#include "Utils/Dumper.h"
Ana Krulec4593b692019-01-11 22:07:25 -080040
Dominik Laskowski98041832019-08-01 18:35:59 -070041namespace android::scheduler {
Ady Abrahamabc27602020-04-08 17:20:29 -070042
Ady Abraham4ccdcb42020-02-11 17:34:34 -080043using namespace std::chrono_literals;
Dominik Laskowski98041832019-08-01 18:35:59 -070044
Dominik Laskowski068173d2021-08-11 17:22:59 -070045enum class DisplayModeEvent : unsigned { None = 0b0, Changed = 0b1 };
Dominik Laskowski98041832019-08-01 18:35:59 -070046
Dominik Laskowski068173d2021-08-11 17:22:59 -070047inline DisplayModeEvent operator|(DisplayModeEvent lhs, DisplayModeEvent rhs) {
48 using T = std::underlying_type_t<DisplayModeEvent>;
49 return static_cast<DisplayModeEvent>(static_cast<T>(lhs) | static_cast<T>(rhs));
Dominik Laskowski98041832019-08-01 18:35:59 -070050}
Ana Krulecb43429d2019-01-09 14:28:51 -080051
Ady Abraham62f216c2020-10-13 19:07:23 -070052using FrameRateOverride = DisplayEventReceiver::Event::FrameRateOverride;
53
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040054// Selects the refresh rate of a display by ranking its `DisplayModes` in accordance with
55// the DisplayManager (or override) `Policy`, the `LayerRequirement` of each active layer,
56// and `GlobalSignals`.
57class RefreshRateSelector {
Ana Krulecb43429d2019-01-09 14:28:51 -080058public:
Ady Abraham4ccdcb42020-02-11 17:34:34 -080059 // Margin used when matching refresh rates to the content desired ones.
60 static constexpr nsecs_t MARGIN_FOR_PERIOD_CALCULATION =
rnlee3bd610662021-06-23 16:27:57 -070061 std::chrono::nanoseconds(800us).count();
Ady Abraham4ccdcb42020-02-11 17:34:34 -080062
Ady Abraham68636062022-11-16 17:07:25 -080063 // The lowest Render Frame Rate that will ever be selected
Ady Abraham1d173042023-01-04 23:24:47 +000064 static constexpr Fps kMinSupportedFrameRate = 20_Hz;
Ady Abraham68636062022-11-16 17:07:25 -080065
Dominik Laskowski36dced82022-09-02 09:24:00 -070066 class Policy {
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020067 static constexpr int kAllowGroupSwitchingDefault = false;
68
69 public:
Marin Shalamanova7fe3042021-01-29 21:02:08 +010070 // The default mode, used to ensure we only initiate display mode switches within the
71 // same mode group as defaultMode's group.
72 DisplayModeId defaultMode;
73 // Whether or not we switch mode groups to get the best frame rate.
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020074 bool allowGroupSwitching = kAllowGroupSwitchingDefault;
Ady Abraham285f8c12022-10-11 17:12:14 -070075 // The primary refresh rate ranges. @see DisplayModeSpecs.aidl for details.
76 // TODO(b/257072060): use the render range when selecting SF render rate
77 // or the app override frame rate
78 FpsRanges primaryRanges;
79 // The app request refresh rate ranges. @see DisplayModeSpecs.aidl for details.
80 FpsRanges appRequestRanges;
Steven Thomasd4071902020-03-24 16:02:53 -070081
Steven Thomasf734df42020-04-13 21:09:28 -070082 Policy() = default;
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020083
Ady Abraham285f8c12022-10-11 17:12:14 -070084 Policy(DisplayModeId defaultMode, FpsRange range,
85 bool allowGroupSwitching = kAllowGroupSwitchingDefault)
86 : Policy(defaultMode, FpsRanges{range, range}, FpsRanges{range, range},
87 allowGroupSwitching) {}
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020088
Ady Abraham285f8c12022-10-11 17:12:14 -070089 Policy(DisplayModeId defaultMode, FpsRanges primaryRanges, FpsRanges appRequestRanges,
90 bool allowGroupSwitching = kAllowGroupSwitchingDefault)
Marin Shalamanova7fe3042021-01-29 21:02:08 +010091 : defaultMode(defaultMode),
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020092 allowGroupSwitching(allowGroupSwitching),
Ady Abraham285f8c12022-10-11 17:12:14 -070093 primaryRanges(primaryRanges),
94 appRequestRanges(appRequestRanges) {}
Steven Thomasf734df42020-04-13 21:09:28 -070095
Steven Thomasd4071902020-03-24 16:02:53 -070096 bool operator==(const Policy& other) const {
Dominik Laskowski953b7fd2022-01-08 19:34:59 -080097 using namespace fps_approx_ops;
Ady Abraham285f8c12022-10-11 17:12:14 -070098 return defaultMode == other.defaultMode && primaryRanges == other.primaryRanges &&
99 appRequestRanges == other.appRequestRanges &&
Steven Thomasd4071902020-03-24 16:02:53 -0700100 allowGroupSwitching == other.allowGroupSwitching;
101 }
102
103 bool operator!=(const Policy& other) const { return !(*this == other); }
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100104 std::string toString() const;
Steven Thomasd4071902020-03-24 16:02:53 -0700105 };
106
Dominik Laskowski36dced82022-09-02 09:24:00 -0700107 enum class SetPolicyResult { Invalid, Unchanged, Changed };
Steven Thomasd4071902020-03-24 16:02:53 -0700108
109 // We maintain the display manager policy and the override policy separately. The override
110 // policy is used by CTS tests to get a consistent device state for testing. While the override
111 // policy is set, it takes precedence over the display manager policy. Once the override policy
112 // is cleared, we revert to using the display manager policy.
Dominik Laskowski36dced82022-09-02 09:24:00 -0700113 struct DisplayManagerPolicy : Policy {
114 using Policy::Policy;
115 };
Steven Thomasd4071902020-03-24 16:02:53 -0700116
Dominik Laskowski36dced82022-09-02 09:24:00 -0700117 struct OverridePolicy : Policy {
118 using Policy::Policy;
119 };
120
121 struct NoOverridePolicy {};
122
123 using PolicyVariant = std::variant<DisplayManagerPolicy, OverridePolicy, NoOverridePolicy>;
124
125 SetPolicyResult setPolicy(const PolicyVariant&) EXCLUDES(mLock) REQUIRES(kMainThreadContext);
126
127 void onModeChangeInitiated() REQUIRES(kMainThreadContext) { mNumModeSwitchesInPolicy++; }
128
Steven Thomasd4071902020-03-24 16:02:53 -0700129 // Gets the current policy, which will be the override policy if active, and the display manager
130 // policy otherwise.
131 Policy getCurrentPolicy() const EXCLUDES(mLock);
132 // Gets the display manager policy, regardless of whether an override policy is active.
133 Policy getDisplayManagerPolicy() const EXCLUDES(mLock);
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100134
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100135 // Returns true if mode is allowed by the current policy.
Ady Abrahamace3d052022-11-17 16:25:05 -0800136 bool isModeAllowed(const FrameRateMode&) const EXCLUDES(mLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800137
Ady Abraham8a82ba62020-01-17 12:43:17 -0800138 // Describes the different options the layer voted for refresh rate
139 enum class LayerVoteType {
Ady Abraham71c437d2020-01-31 15:56:57 -0800140 NoVote, // Doesn't care about the refresh rate
141 Min, // Minimal refresh rate available
142 Max, // Maximal refresh rate available
143 Heuristic, // Specific refresh rate that was calculated by platform using a heuristic
144 ExplicitDefault, // Specific refresh rate that was provided by the app with Default
145 // compatibility
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800146 ExplicitExactOrMultiple, // Specific refresh rate that was provided by the app with
147 // ExactOrMultiple compatibility
148 ExplicitExact, // Specific refresh rate that was provided by the app with
149 // Exact compatibility
Rachel Leece6e0042023-06-27 11:22:54 -0700150 ExplicitCategory, // Specific frame rate category was provided by the app
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800151
Rachel Leece6e0042023-06-27 11:22:54 -0700152 ftl_last = ExplicitCategory
Ady Abraham8a82ba62020-01-17 12:43:17 -0800153 };
154
155 // Captures the layer requirements for a refresh rate. This will be used to determine the
156 // display refresh rate.
157 struct LayerRequirement {
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700158 // Layer's name. Used for debugging purposes.
159 std::string name;
Ady Abraham62a0be22020-12-08 16:54:10 -0800160 // Layer's owner uid
161 uid_t ownerUid = static_cast<uid_t>(-1);
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700162 // Layer vote type.
163 LayerVoteType vote = LayerVoteType::NoVote;
164 // Layer's desired refresh rate, if applicable.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700165 Fps desiredRefreshRate;
Marin Shalamanov46084422020-10-13 12:33:42 +0200166 // If a seamless mode switch is required.
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100167 Seamlessness seamlessness = Seamlessness::Default;
Rachel Leece6e0042023-06-27 11:22:54 -0700168 // Layer frame rate category. Superseded by desiredRefreshRate.
169 FrameRateCategory frameRateCategory = FrameRateCategory::Default;
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700170 // Layer's weight in the range of [0, 1]. The higher the weight the more impact this layer
171 // would have on choosing the refresh rate.
172 float weight = 0.0f;
173 // Whether layer is in focus or not based on WindowManager's state
174 bool focused = false;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800175
176 bool operator==(const LayerRequirement& other) const {
177 return name == other.name && vote == other.vote &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700178 isApproxEqual(desiredRefreshRate, other.desiredRefreshRate) &&
Marin Shalamanovbe97cfa2020-12-01 16:02:07 +0100179 seamlessness == other.seamlessness && weight == other.weight &&
Rachel Leece6e0042023-06-27 11:22:54 -0700180 focused == other.focused && frameRateCategory == other.frameRateCategory;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800181 }
182
183 bool operator!=(const LayerRequirement& other) const { return !(*this == other); }
Rachel Leece6e0042023-06-27 11:22:54 -0700184
185 bool isNoVote() const { return RefreshRateSelector::isNoVote(vote, frameRateCategory); }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800186 };
187
Rachel Leece6e0042023-06-27 11:22:54 -0700188 // Returns true if the layer explicitly instructs to not contribute to refresh rate selection.
189 // In other words, true if the layer should be ignored.
190 static bool isNoVote(LayerVoteType vote, FrameRateCategory category) {
191 return vote == LayerVoteType::NoVote || category == FrameRateCategory::NoPreference;
192 }
193
Ady Abrahamdfd62162020-06-10 16:11:56 -0700194 // Global state describing signals that affect refresh rate choice.
195 struct GlobalSignals {
196 // Whether the user touched the screen recently. Used to apply touch boost.
197 bool touch = false;
198 // True if the system hasn't seen any buffers posted to layers recently.
199 bool idle = false;
ramindani38c84982022-08-29 18:02:57 +0000200 // Whether the display is about to be powered on, or has been in PowerMode::ON
201 // within the timeout of DisplayPowerTimer.
202 bool powerOnImminent = false;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200203
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700204 bool operator==(GlobalSignals other) const {
ramindani38c84982022-08-29 18:02:57 +0000205 return touch == other.touch && idle == other.idle &&
206 powerOnImminent == other.powerOnImminent;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200207 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400208
209 auto toString() const {
210 return ftl::Concat("{touch=", touch, ", idle=", idle,
211 ", powerOnImminent=", powerOnImminent, '}');
212 }
Ady Abrahamdfd62162020-06-10 16:11:56 -0700213 };
214
Ady Abraham68636062022-11-16 17:07:25 -0800215 struct ScoredFrameRate {
216 FrameRateMode frameRateMode;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400217 float score = 0.0f;
218
Ady Abraham68636062022-11-16 17:07:25 -0800219 bool operator==(const ScoredFrameRate& other) const {
220 return frameRateMode == other.frameRateMode && score == other.score;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400221 }
222
223 static bool scoresEqual(float lhs, float rhs) {
224 constexpr float kEpsilon = 0.0001f;
225 return std::abs(lhs - rhs) <= kEpsilon;
226 }
227
228 struct DescendingScore {
Ady Abraham68636062022-11-16 17:07:25 -0800229 bool operator()(const ScoredFrameRate& lhs, const ScoredFrameRate& rhs) const {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400230 return lhs.score > rhs.score && !scoresEqual(lhs.score, rhs.score);
231 }
232 };
233 };
234
Ady Abraham68636062022-11-16 17:07:25 -0800235 using FrameRateRanking = std::vector<ScoredFrameRate>;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400236
Ady Abraham68636062022-11-16 17:07:25 -0800237 struct RankedFrameRates {
238 FrameRateRanking ranking; // Ordered by descending score.
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400239 GlobalSignals consideredSignals;
240
Ady Abraham68636062022-11-16 17:07:25 -0800241 bool operator==(const RankedFrameRates& other) const {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400242 return ranking == other.ranking && consideredSignals == other.consideredSignals;
243 }
244 };
245
Ady Abraham68636062022-11-16 17:07:25 -0800246 RankedFrameRates getRankedFrameRates(const std::vector<LayerRequirement>&, GlobalSignals) const
247 EXCLUDES(mLock);
Ana Krulecb43429d2019-01-09 14:28:51 -0800248
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100249 FpsRange getSupportedRefreshRateRange() const EXCLUDES(mLock) {
250 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800251 return {mMinRefreshRateModeIt->second->getFps(), mMaxRefreshRateModeIt->second->getFps()};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100252 }
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700253
Ady Abraham0aa373a2022-11-22 13:56:50 -0800254 ftl::Optional<FrameRateMode> onKernelTimerChanged(
255 std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const
256 EXCLUDES(mLock);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700257
Ady Abrahamace3d052022-11-17 16:25:05 -0800258 void setActiveMode(DisplayModeId, Fps renderFrameRate) EXCLUDES(mLock);
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700259
Ady Abrahamace3d052022-11-17 16:25:05 -0800260 // See mActiveModeOpt for thread safety.
261 FrameRateMode getActiveMode() const EXCLUDES(mLock);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700262
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700263 // Returns a known frame rate that is the closest to frameRate
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100264 Fps findClosestKnownFrameRate(Fps frameRate) const;
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700265
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800266 enum class KernelIdleTimerController { Sysprop, HwcApi, ftl_last = HwcApi };
ramindani32cf0602022-03-02 02:30:29 +0000267
rnlee3bd610662021-06-23 16:27:57 -0700268 // Configuration flags.
269 struct Config {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700270 enum class FrameRateOverride {
271 // Do not override the frame rate for an app
272 Disabled,
273
274 // Override the frame rate for an app to a value which is also
275 // a display refresh rate
Ady Abraham68636062022-11-16 17:07:25 -0800276 AppOverrideNativeRefreshRates,
Ady Abraham8ca643a2022-10-18 18:26:47 -0700277
278 // Override the frame rate for an app to any value
Ady Abraham68636062022-11-16 17:07:25 -0800279 AppOverride,
280
281 // Override the frame rate for all apps and all values.
Ady Abraham8ca643a2022-10-18 18:26:47 -0700282 Enabled,
283
284 ftl_last = Enabled
285 };
286 FrameRateOverride enableFrameRateOverride = FrameRateOverride::Disabled;
rnlee3bd610662021-06-23 16:27:57 -0700287
288 // Specifies the upper refresh rate threshold (inclusive) for layer vote types of multiple
289 // or heuristic, such that refresh rates higher than this value will not be voted for. 0 if
290 // no threshold is set.
291 int frameRateMultipleThreshold = 0;
Ady Abraham9a2ea342021-09-03 17:32:34 -0700292
Ady Abraham6d885932021-09-03 18:05:48 -0700293 // The Idle Timer timeout. 0 timeout means no idle timer.
ramindani32cf0602022-03-02 02:30:29 +0000294 std::chrono::milliseconds idleTimerTimeout = 0ms;
Ady Abraham6d885932021-09-03 18:05:48 -0700295
ramindani32cf0602022-03-02 02:30:29 +0000296 // The controller representing how the kernel idle timer will be configured
297 // either on the HWC api or sysprop.
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400298 ftl::Optional<KernelIdleTimerController> kernelIdleTimerController;
rnlee3bd610662021-06-23 16:27:57 -0700299 };
300
Ady Abraham8ca643a2022-10-18 18:26:47 -0700301 RefreshRateSelector(
302 DisplayModes, DisplayModeId activeModeId,
303 Config config = {.enableFrameRateOverride = Config::FrameRateOverride::Disabled,
304 .frameRateMultipleThreshold = 0,
305 .idleTimerTimeout = 0ms,
306 .kernelIdleTimerController = {}});
Ana Krulec4593b692019-01-11 22:07:25 -0800307
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400308 RefreshRateSelector(const RefreshRateSelector&) = delete;
309 RefreshRateSelector& operator=(const RefreshRateSelector&) = delete;
Dominik Laskowski0c252702021-12-20 20:32:09 -0800310
Dominik Laskowski2b1037b2023-02-11 16:45:36 -0500311 const DisplayModes& displayModes() const { return mDisplayModes; }
312
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100313 // Returns whether switching modes (refresh rate or resolution) is possible.
314 // TODO(b/158780872): Consider HAL support, and skip frame rate detection if the modes only
Ady Abraham68636062022-11-16 17:07:25 -0800315 // differ in resolution. Once Config::FrameRateOverride::Enabled becomes the default,
316 // we can probably remove canSwitch altogether since all devices will be able
317 // to switch to a frame rate divisor.
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100318 bool canSwitch() const EXCLUDES(mLock) {
319 std::lock_guard lock(mLock);
Ady Abraham68636062022-11-16 17:07:25 -0800320 return mDisplayModes.size() > 1 ||
321 mFrameRateOverrideConfig == Config::FrameRateOverride::Enabled;
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100322 }
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700323
TreeHugger Robot758ab612021-06-22 19:17:29 +0000324 // Class to enumerate options around toggling the kernel timer on and off.
Ana Krulecb9afd792020-06-11 13:16:15 -0700325 enum class KernelIdleTimerAction {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400326 TurnOff, // Turn off the idle timer.
327 TurnOn // Turn on the idle timer.
Ana Krulecb9afd792020-06-11 13:16:15 -0700328 };
ramindani32cf0602022-03-02 02:30:29 +0000329
Ana Krulecb9afd792020-06-11 13:16:15 -0700330 // Checks whether kernel idle timer should be active depending the policy decisions around
331 // refresh rates.
332 KernelIdleTimerAction getIdleTimerAction() const;
333
Ady Abraham68636062022-11-16 17:07:25 -0800334 bool supportsAppFrameRateOverrideByContent() const {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700335 return mFrameRateOverrideConfig != Config::FrameRateOverride::Disabled;
336 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800337
Ady Abraham68636062022-11-16 17:07:25 -0800338 bool supportsFrameRateOverride() const {
339 return mFrameRateOverrideConfig == Config::FrameRateOverride::Enabled;
340 }
341
Ady Abrahamcc315492022-02-17 17:06:39 -0800342 // Return the display refresh rate divisor to match the layer
Ady Abraham5cc2e262021-03-25 13:09:17 -0700343 // frame rate, or 0 if the display refresh rate is not a multiple of the
344 // layer refresh rate.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800345 static int getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800346
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200347 // Returns if the provided frame rates have a ratio t*1000/1001 or t*1001/1000
348 // for an integer t.
349 static bool isFractionalPairOrMultiple(Fps, Fps);
350
Ady Abraham62a0be22020-12-08 16:54:10 -0800351 using UidToFrameRateOverride = std::map<uid_t, Fps>;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700352
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800353 // Returns the frame rate override for each uid.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700354 UidToFrameRateOverride getFrameRateOverrides(const std::vector<LayerRequirement>&,
355 Fps displayFrameRate, GlobalSignals) const
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800356 EXCLUDES(mLock);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700357
Rachel Leece6e0042023-06-27 11:22:54 -0700358 // Gets the FpsRange that the FrameRateCategory represents.
359 static FpsRange getFrameRateCategoryRange(FrameRateCategory category);
360
ramindani32cf0602022-03-02 02:30:29 +0000361 std::optional<KernelIdleTimerController> kernelIdleTimerController() {
362 return mConfig.kernelIdleTimerController;
363 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700364
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800365 struct IdleTimerCallbacks {
366 struct Callbacks {
367 std::function<void()> onReset;
368 std::function<void()> onExpired;
369 };
370
371 Callbacks platform;
372 Callbacks kernel;
373 };
374
375 void setIdleTimerCallbacks(IdleTimerCallbacks callbacks) EXCLUDES(mIdleTimerCallbacksMutex) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700376 std::scoped_lock lock(mIdleTimerCallbacksMutex);
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800377 mIdleTimerCallbacks = std::move(callbacks);
378 }
379
380 void clearIdleTimerCallbacks() EXCLUDES(mIdleTimerCallbacksMutex) {
381 std::scoped_lock lock(mIdleTimerCallbacksMutex);
382 mIdleTimerCallbacks.reset();
Ady Abraham11663402021-11-10 19:46:09 -0800383 }
384
385 void startIdleTimer() {
386 if (mIdleTimer) {
387 mIdleTimer->start();
388 }
389 }
390
391 void stopIdleTimer() {
392 if (mIdleTimer) {
393 mIdleTimer->stop();
394 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700395 }
396
Dominik Laskowski596a2562022-10-28 11:26:12 -0400397 void resetKernelIdleTimer() {
398 if (mIdleTimer && mConfig.kernelIdleTimerController) {
399 mIdleTimer->reset();
Ady Abraham9a2ea342021-09-03 17:32:34 -0700400 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400401 }
402
403 void resetIdleTimer() {
404 if (mIdleTimer) {
405 mIdleTimer->reset();
Ady Abraham9a2ea342021-09-03 17:32:34 -0700406 }
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800407 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700408
Dominik Laskowskie70461a2022-08-30 14:42:01 -0700409 void dump(utils::Dumper&) const EXCLUDES(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +0100410
ramindani32cf0602022-03-02 02:30:29 +0000411 std::chrono::milliseconds getIdleTimerTimeout();
412
Dominik Laskowski22488f62019-03-28 09:53:04 -0700413private:
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400414 friend struct TestableRefreshRateSelector;
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700415
Ady Abraham2139f732019-11-13 18:56:40 -0800416 void constructAvailableRefreshRates() REQUIRES(mLock);
417
Ady Abrahamace3d052022-11-17 16:25:05 -0800418 // See mActiveModeOpt for thread safety.
419 const FrameRateMode& getActiveModeLocked() const REQUIRES(mLock);
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700420
Ady Abraham68636062022-11-16 17:07:25 -0800421 RankedFrameRates getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
422 GlobalSignals signals) const REQUIRES(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200423
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800424 // Returns number of display frames and remainder when dividing the layer refresh period by
425 // display refresh period.
426 std::pair<nsecs_t, nsecs_t> getDisplayFrames(nsecs_t layerPeriod, nsecs_t displayPeriod) const;
427
Steven Thomasf734df42020-04-13 21:09:28 -0700428 // Returns the lowest refresh rate according to the current policy. May change at runtime. Only
429 // uses the primary range, not the app request range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800430 const DisplayModePtr& getMinRefreshRateByPolicyLocked() const REQUIRES(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700431
432 // Returns the highest refresh rate according to the current policy. May change at runtime. Only
433 // uses the primary range, not the app request range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800434 const DisplayModePtr& getMaxRefreshRateByPolicyLocked(int anchorGroup) const REQUIRES(mLock);
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200435
ramindanid72ba162022-09-09 21:33:40 +0000436 struct RefreshRateScoreComparator;
437
Ady Abraham68636062022-11-16 17:07:25 -0800438 enum class RefreshRateOrder {
439 Ascending,
440 Descending,
441
442 ftl_last = Descending
443 };
ramindanid72ba162022-09-09 21:33:40 +0000444
ramindanid72ba162022-09-09 21:33:40 +0000445 // Only uses the primary range, not the app request range.
Ady Abraham68636062022-11-16 17:07:25 -0800446 FrameRateRanking rankFrameRates(
447 std::optional<int> anchorGroupOpt, RefreshRateOrder refreshRateOrder,
448 std::optional<DisplayModeId> preferredDisplayModeOpt = std::nullopt) const
449 REQUIRES(mLock);
ramindanid72ba162022-09-09 21:33:40 +0000450
Steven Thomasd4071902020-03-24 16:02:53 -0700451 const Policy* getCurrentPolicyLocked() const REQUIRES(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100452 bool isPolicyValidLocked(const Policy& policy) const REQUIRES(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700453
ramindanid72ba162022-09-09 21:33:40 +0000454 // 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 -0800455 float calculateDistanceScoreFromMax(Fps refreshRate) const REQUIRES(mLock);
Ady Abraham62a0be22020-12-08 16:54:10 -0800456 // calculates a score for a layer. Used to determine the display refresh rate
457 // and the frame rate override for certains applications.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800458 float calculateLayerScoreLocked(const LayerRequirement&, Fps refreshRate,
Ady Abraham62a0be22020-12-08 16:54:10 -0800459 bool isSeamlessSwitch) const REQUIRES(mLock);
460
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800461 float calculateNonExactMatchingLayerScoreLocked(const LayerRequirement&, Fps refreshRate) const
462 REQUIRES(mLock);
Ady Abraham05243be2021-09-16 15:58:52 -0700463
Rachel Leece6e0042023-06-27 11:22:54 -0700464 // Calculates the score for non-exact matching layer that has LayerVoteType::ExplicitDefault.
465 float calculateNonExactMatchingDefaultLayerScoreLocked(nsecs_t displayPeriod,
466 nsecs_t layerPeriod) const
467 REQUIRES(mLock);
468
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700469 void updateDisplayModes(DisplayModes, DisplayModeId activeModeId) EXCLUDES(mLock)
470 REQUIRES(kMainThreadContext);
Ady Abraham3efa3942021-06-24 19:01:25 -0700471
Ady Abraham9a2ea342021-09-03 17:32:34 -0700472 void initializeIdleTimer();
473
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800474 std::optional<IdleTimerCallbacks::Callbacks> getIdleTimerCallbacks() const
475 REQUIRES(mIdleTimerCallbacksMutex) {
476 if (!mIdleTimerCallbacks) return {};
ramindani32cf0602022-03-02 02:30:29 +0000477 return mConfig.kernelIdleTimerController.has_value() ? mIdleTimerCallbacks->kernel
478 : mIdleTimerCallbacks->platform;
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800479 }
480
Ady Abraham68636062022-11-16 17:07:25 -0800481 bool isNativeRefreshRate(Fps fps) const REQUIRES(mLock) {
482 LOG_ALWAYS_FATAL_IF(mConfig.enableFrameRateOverride !=
483 Config::FrameRateOverride::AppOverrideNativeRefreshRates,
484 "should only be called when "
485 "Config::FrameRateOverride::AppOverrideNativeRefreshRates is used");
486 return mAppOverrideNativeRefreshRates.contains(fps);
487 }
488
489 std::vector<FrameRateMode> createFrameRateModes(
490 std::function<bool(const DisplayMode&)>&& filterModes, const FpsRange&) const
491 REQUIRES(mLock);
492
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800493 // The display modes of the active display. The DisplayModeIterators below are pointers into
494 // this container, so must be invalidated whenever the DisplayModes change. The Policy below
495 // is also dependent, so must be reset as well.
496 DisplayModes mDisplayModes GUARDED_BY(mLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800497
Ady Abraham68636062022-11-16 17:07:25 -0800498 // Set of supported display refresh rates for easy lookup
499 // when FrameRateOverride::AppOverrideNativeRefreshRates is in use.
500 ftl::SmallMap<Fps, ftl::Unit, 8, FpsApproxEqual> mAppOverrideNativeRefreshRates;
501
Ady Abrahamace3d052022-11-17 16:25:05 -0800502 ftl::Optional<FrameRateMode> mActiveModeOpt GUARDED_BY(mLock);
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700503
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800504 DisplayModeIterator mMinRefreshRateModeIt GUARDED_BY(mLock);
505 DisplayModeIterator mMaxRefreshRateModeIt GUARDED_BY(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700506
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800507 // Display modes that satisfy the Policy's ranges, filtered and sorted by refresh rate.
Ady Abraham68636062022-11-16 17:07:25 -0800508 std::vector<FrameRateMode> mPrimaryFrameRates GUARDED_BY(mLock);
509 std::vector<FrameRateMode> mAppRequestFrameRates GUARDED_BY(mLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800510
Steven Thomasd4071902020-03-24 16:02:53 -0700511 Policy mDisplayManagerPolicy GUARDED_BY(mLock);
512 std::optional<Policy> mOverridePolicy GUARDED_BY(mLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800513
Dominik Laskowski36dced82022-09-02 09:24:00 -0700514 unsigned mNumModeSwitchesInPolicy GUARDED_BY(kMainThreadContext) = 0;
515
Ady Abraham2139f732019-11-13 18:56:40 -0800516 mutable std::mutex mLock;
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700517
518 // A sorted list of known frame rates that a Heuristic layer will choose
519 // from based on the closest value.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100520 const std::vector<Fps> mKnownFrameRates;
Ady Abraham64c2fc02020-12-29 12:07:50 -0800521
rnlee3bd610662021-06-23 16:27:57 -0700522 const Config mConfig;
Ady Abrahambd44e8a2023-07-24 11:30:06 -0700523
524 // A list of known frame rates that favors at least 60Hz if there is no exact match display
525 // refresh rate
526 const std::vector<Fps> mFrameRatesThatFavorsAtLeast60 = {23.976_Hz, 25_Hz, 29.97_Hz, 50_Hz,
527 59.94_Hz};
528
Ady Abraham8ca643a2022-10-18 18:26:47 -0700529 Config::FrameRateOverride mFrameRateOverrideConfig;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200530
Ady Abraham68636062022-11-16 17:07:25 -0800531 struct GetRankedFrameRatesCache {
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800532 std::pair<std::vector<LayerRequirement>, GlobalSignals> arguments;
Ady Abraham68636062022-11-16 17:07:25 -0800533 RankedFrameRates result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200534 };
Ady Abraham68636062022-11-16 17:07:25 -0800535 mutable std::optional<GetRankedFrameRatesCache> mGetRankedFrameRatesCache GUARDED_BY(mLock);
Ady Abraham9a2ea342021-09-03 17:32:34 -0700536
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800537 // Declare mIdleTimer last to ensure its thread joins before the mutex/callbacks are destroyed.
Ady Abraham9a2ea342021-09-03 17:32:34 -0700538 std::mutex mIdleTimerCallbacksMutex;
539 std::optional<IdleTimerCallbacks> mIdleTimerCallbacks GUARDED_BY(mIdleTimerCallbacksMutex);
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800540 // Used to detect (lack of) frame activity.
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400541 ftl::Optional<scheduler::OneShotTimer> mIdleTimer;
Ana Krulecb43429d2019-01-09 14:28:51 -0800542};
543
Dominik Laskowski98041832019-08-01 18:35:59 -0700544} // namespace android::scheduler