blob: 68e34d2bfd23eb984515922b5bd2a4e3b01ab0e9 [file] [log] [blame]
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -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 */
Ady Abraham2139f732019-11-13 18:56:40 -080016
Ady Abraham8a82ba62020-01-17 12:43:17 -080017// #define LOG_NDEBUG 0
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020// TODO(b/129481165): remove the #pragma below and fix conversion issues
21#pragma clang diagnostic push
22#pragma clang diagnostic ignored "-Wextra"
23
Ady Abraham8a82ba62020-01-17 12:43:17 -080024#include <chrono>
25#include <cmath>
Dominik Laskowski530d6bd2022-10-10 16:55:54 -040026#include <deque>
Ady Abraham68636062022-11-16 17:07:25 -080027#include <map>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070028
29#include <android-base/properties.h>
30#include <android-base/stringprintf.h>
Vishnu Nairbe0ad902024-06-27 23:38:43 +000031#include <common/trace.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070032#include <ftl/enum.h>
Dominik Laskowskif8734e02022-08-26 09:06:59 -070033#include <ftl/fake_guard.h>
Dominik Laskowski36dced82022-09-02 09:24:00 -070034#include <ftl/match.h>
Ady Abraham8ca643a2022-10-18 18:26:47 -070035#include <ftl/unit.h>
Ady Abraham68636062022-11-16 17:07:25 -080036#include <scheduler/FrameRateMode.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070037
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040038#include "RefreshRateSelector.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080039
ramindania04b8a52023-08-07 18:49:47 -070040#include <com_android_graphics_surfaceflinger_flags.h>
41
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080042#undef LOG_TAG
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040043#define LOG_TAG "RefreshRateSelector"
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080044
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080045namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010046namespace {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070047
ramindania04b8a52023-08-07 18:49:47 -070048using namespace com::android::graphics::surfaceflinger;
49
Dominik Laskowskib0054a22022-03-03 09:03:06 -080050struct RefreshRateScore {
Ady Abraham68636062022-11-16 17:07:25 -080051 FrameRateMode frameRateMode;
Ady Abrahamae2e3c72022-08-13 05:12:13 +000052 float overallScore;
53 struct {
Ady Abraham62f51d92022-08-24 22:20:22 +000054 float modeBelowThreshold;
55 float modeAboveThreshold;
56 } fixedRateBelowThresholdLayersScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -080057};
58
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040059constexpr RefreshRateSelector::GlobalSignals kNoSignals;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080060
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040061std::string formatLayerInfo(const RefreshRateSelector::LayerRequirement& layer, float weight) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080062 return base::StringPrintf("%s (type=%s, weight=%.2f, seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070063 ftl::enum_string(layer.vote).c_str(), weight,
64 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010065 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010066}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010067
Marin Shalamanova7fe3042021-01-29 21:02:08 +010068std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070069 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010070 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010071
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070072 // Add all supported refresh rates.
Dominik Laskowskib0054a22022-03-03 09:03:06 -080073 for (const auto& [id, mode] : modes) {
ramindania04b8a52023-08-07 18:49:47 -070074 knownFrameRates.push_back(mode->getPeakFps());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010075 }
76
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070077 // Sort and remove duplicates.
78 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010079 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070080 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010081 knownFrameRates.end());
82 return knownFrameRates;
83}
84
Ady Abraham68636062022-11-16 17:07:25 -080085std::vector<DisplayModeIterator> sortByRefreshRate(const DisplayModes& modes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080086 std::vector<DisplayModeIterator> sortedModes;
87 sortedModes.reserve(modes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -080088 for (auto it = modes.begin(); it != modes.end(); ++it) {
Ady Abraham68636062022-11-16 17:07:25 -080089 sortedModes.push_back(it);
Dominik Laskowskib0054a22022-03-03 09:03:06 -080090 }
91
92 std::sort(sortedModes.begin(), sortedModes.end(), [](auto it1, auto it2) {
93 const auto& mode1 = it1->second;
94 const auto& mode2 = it2->second;
95
ramindania04b8a52023-08-07 18:49:47 -070096 if (mode1->getVsyncRate().getPeriodNsecs() == mode2->getVsyncRate().getPeriodNsecs()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080097 return mode1->getGroup() > mode2->getGroup();
98 }
99
ramindania04b8a52023-08-07 18:49:47 -0700100 return mode1->getVsyncRate().getPeriodNsecs() > mode2->getVsyncRate().getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800101 });
102
103 return sortedModes;
Marin Shalamanov46084422020-10-13 12:33:42 +0200104}
105
ramindania04b8a52023-08-07 18:49:47 -0700106std::pair<unsigned, unsigned> divisorRange(Fps vsyncRate, Fps peakFps, FpsRange range,
Ady Abraham68636062022-11-16 17:07:25 -0800107 RefreshRateSelector::Config::FrameRateOverride config) {
108 if (config != RefreshRateSelector::Config::FrameRateOverride::Enabled) {
109 return {1, 1};
110 }
111
112 using fps_approx_ops::operator/;
Ady Abraham08048ce2022-11-30 18:08:00 -0800113 // use signed type as `fps / range.max` might be 0
ramindania04b8a52023-08-07 18:49:47 -0700114 auto start = std::max(1, static_cast<int>(peakFps / range.max) - 1);
Ady Abrahamd6d80162023-10-23 12:57:41 -0700115 if (FlagManager::getInstance().vrr_config()) {
ramindania04b8a52023-08-07 18:49:47 -0700116 start = std::max(1,
117 static_cast<int>(vsyncRate /
118 std::min(range.max, peakFps, fps_approx_ops::operator<)) -
119 1);
120 }
121 const auto end = vsyncRate /
Ady Abraham68636062022-11-16 17:07:25 -0800122 std::max(range.min, RefreshRateSelector::kMinSupportedFrameRate,
123 fps_approx_ops::operator<);
124
125 return {start, end};
126}
127
Ady Abraham8ca643a2022-10-18 18:26:47 -0700128bool shouldEnableFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800129 for (const auto it1 : sortedModes) {
130 const auto& mode1 = it1->second;
131 for (const auto it2 : sortedModes) {
132 const auto& mode2 = it2->second;
133
ramindania04b8a52023-08-07 18:49:47 -0700134 if (RefreshRateSelector::getFrameRateDivisor(mode1->getPeakFps(),
135 mode2->getPeakFps()) >= 2) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800136 return true;
137 }
138 }
139 }
140 return false;
141}
142
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400143std::string toString(const RefreshRateSelector::PolicyVariant& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700144 using namespace std::string_literals;
145
146 return ftl::match(
147 policy,
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400148 [](const RefreshRateSelector::DisplayManagerPolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700149 return "DisplayManagerPolicy"s + policy.toString();
150 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400151 [](const RefreshRateSelector::OverridePolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700152 return "OverridePolicy"s + policy.toString();
153 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400154 [](RefreshRateSelector::NoOverridePolicy) { return "NoOverridePolicy"s; });
Dominik Laskowski36dced82022-09-02 09:24:00 -0700155}
156
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800157} // namespace
158
Ady Abraham68636062022-11-16 17:07:25 -0800159auto RefreshRateSelector::createFrameRateModes(
Ady Abraham90f7fd22023-08-16 11:02:00 -0700160 const Policy& policy, std::function<bool(const DisplayMode&)>&& filterModes,
161 const FpsRange& renderRange) const -> std::vector<FrameRateMode> {
Ady Abraham68636062022-11-16 17:07:25 -0800162 struct Key {
163 Fps fps;
164 int32_t group;
165 };
166
167 struct KeyLess {
168 bool operator()(const Key& a, const Key& b) const {
169 using namespace fps_approx_ops;
170 if (a.fps != b.fps) {
171 return a.fps < b.fps;
172 }
173
174 // For the same fps the order doesn't really matter, but we still
175 // want the behaviour of a strictly less operator.
176 // We use the group id as the secondary ordering for that.
177 return a.group < b.group;
178 }
179 };
180
181 std::map<Key, DisplayModeIterator, KeyLess> ratesMap;
182 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
183 const auto& [id, mode] = *it;
184
185 if (!filterModes(*mode)) {
186 continue;
187 }
ramindania04b8a52023-08-07 18:49:47 -0700188 const auto vsyncRate = mode->getVsyncRate();
189 const auto peakFps = mode->getPeakFps();
Ady Abraham68636062022-11-16 17:07:25 -0800190 const auto [start, end] =
ramindania04b8a52023-08-07 18:49:47 -0700191 divisorRange(vsyncRate, peakFps, renderRange, mConfig.enableFrameRateOverride);
Ady Abraham68636062022-11-16 17:07:25 -0800192 for (auto divisor = start; divisor <= end; divisor++) {
ramindania04b8a52023-08-07 18:49:47 -0700193 const auto fps = vsyncRate / divisor;
Ady Abraham68636062022-11-16 17:07:25 -0800194 using fps_approx_ops::operator<;
Ady Abrahamdc0b3a72023-01-04 16:58:27 -0800195 if (divisor > 1 && fps < kMinSupportedFrameRate) {
Ady Abraham68636062022-11-16 17:07:25 -0800196 break;
197 }
198
199 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Enabled &&
200 !renderRange.includes(fps)) {
201 continue;
202 }
203
204 if (mConfig.enableFrameRateOverride ==
205 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
206 !isNativeRefreshRate(fps)) {
207 continue;
208 }
209
210 const auto [existingIter, emplaceHappened] =
211 ratesMap.try_emplace(Key{fps, mode->getGroup()}, it);
212 if (emplaceHappened) {
ramindania04b8a52023-08-07 18:49:47 -0700213 ALOGV("%s: including %s (%s(%s))", __func__, to_string(fps).c_str(),
214 to_string(peakFps).c_str(), to_string(vsyncRate).c_str());
Ady Abraham68636062022-11-16 17:07:25 -0800215 } else {
Ady Abraham90f7fd22023-08-16 11:02:00 -0700216 // If the primary physical range is a single rate, prefer to stay in that rate
217 // even if there is a lower physical refresh rate available. This would cause more
218 // cases to stay within the primary physical range
ramindania04b8a52023-08-07 18:49:47 -0700219 const Fps existingModeFps = existingIter->second->second->getPeakFps();
Ady Abraham90f7fd22023-08-16 11:02:00 -0700220 const bool existingModeIsPrimaryRange = policy.primaryRangeIsSingleRate() &&
221 policy.primaryRanges.physical.includes(existingModeFps);
222 const bool newModeIsPrimaryRange = policy.primaryRangeIsSingleRate() &&
ramindania04b8a52023-08-07 18:49:47 -0700223 policy.primaryRanges.physical.includes(mode->getPeakFps());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700224 if (newModeIsPrimaryRange == existingModeIsPrimaryRange) {
225 // We might need to update the map as we found a lower refresh rate
ramindania04b8a52023-08-07 18:49:47 -0700226 if (isStrictlyLess(mode->getPeakFps(), existingModeFps)) {
Ady Abraham90f7fd22023-08-16 11:02:00 -0700227 existingIter->second = it;
ramindania04b8a52023-08-07 18:49:47 -0700228 ALOGV("%s: changing %s (%s(%s)) as we found a lower physical rate",
229 __func__, to_string(fps).c_str(), to_string(peakFps).c_str(),
230 to_string(vsyncRate).c_str());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700231 }
232 } else if (newModeIsPrimaryRange) {
Ady Abraham68636062022-11-16 17:07:25 -0800233 existingIter->second = it;
ramindania04b8a52023-08-07 18:49:47 -0700234 ALOGV("%s: changing %s (%s(%s)) to stay in the primary range", __func__,
235 to_string(fps).c_str(), to_string(peakFps).c_str(),
236 to_string(vsyncRate).c_str());
Ady Abraham68636062022-11-16 17:07:25 -0800237 }
238 }
239 }
240 }
241
242 std::vector<FrameRateMode> frameRateModes;
243 frameRateModes.reserve(ratesMap.size());
244 for (const auto& [key, mode] : ratesMap) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800245 frameRateModes.emplace_back(FrameRateMode{key.fps, ftl::as_non_null(mode->second)});
Ady Abraham68636062022-11-16 17:07:25 -0800246 }
247
248 // We always want that the lowest frame rate will be corresponding to the
249 // lowest mode for power saving.
250 const auto lowestRefreshRateIt =
251 std::min_element(frameRateModes.begin(), frameRateModes.end(),
252 [](const FrameRateMode& lhs, const FrameRateMode& rhs) {
ramindania04b8a52023-08-07 18:49:47 -0700253 return isStrictlyLess(lhs.modePtr->getVsyncRate(),
254 rhs.modePtr->getVsyncRate());
Ady Abraham68636062022-11-16 17:07:25 -0800255 });
256 frameRateModes.erase(frameRateModes.begin(), lowestRefreshRateIt);
257
258 return frameRateModes;
259}
260
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400261struct RefreshRateSelector::RefreshRateScoreComparator {
ramindanid72ba162022-09-09 21:33:40 +0000262 bool operator()(const RefreshRateScore& lhs, const RefreshRateScore& rhs) const {
Ady Abraham68636062022-11-16 17:07:25 -0800263 const auto& [frameRateMode, overallScore, _] = lhs;
ramindanid72ba162022-09-09 21:33:40 +0000264
Ady Abraham68636062022-11-16 17:07:25 -0800265 std::string name = to_string(frameRateMode);
266
ramindanid72ba162022-09-09 21:33:40 +0000267 ALOGV("%s sorting scores %.2f", name.c_str(), overallScore);
ramindanid72ba162022-09-09 21:33:40 +0000268
Ady Abraham68636062022-11-16 17:07:25 -0800269 if (!ScoredFrameRate::scoresEqual(overallScore, rhs.overallScore)) {
ramindanid72ba162022-09-09 21:33:40 +0000270 return overallScore > rhs.overallScore;
271 }
272
ramindanid72ba162022-09-09 21:33:40 +0000273 if (refreshRateOrder == RefreshRateOrder::Descending) {
274 using fps_approx_ops::operator>;
Ady Abraham68636062022-11-16 17:07:25 -0800275 return frameRateMode.fps > rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000276 } else {
277 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -0800278 return frameRateMode.fps < rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000279 }
280 }
281
282 const RefreshRateOrder refreshRateOrder;
283};
284
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400285std::string RefreshRateSelector::Policy::toString() const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700286 return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
Ady Abraham67231722024-03-21 18:06:21 -0700287 ", primaryRanges=%s, appRequestRanges=%s idleScreenConfig=%s}",
Dominik Laskowski43baf902023-11-17 18:13:11 -0500288 ftl::to_underlying(defaultMode),
289 allowGroupSwitching ? "true" : "false",
Ady Abraham67231722024-03-21 18:06:21 -0700290 to_string(primaryRanges).c_str(), to_string(appRequestRanges).c_str(),
291 idleScreenConfigOpt ? idleScreenConfigOpt->toString().c_str()
292 : "nullptr");
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200293}
294
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400295std::pair<nsecs_t, nsecs_t> RefreshRateSelector::getDisplayFrames(nsecs_t layerPeriod,
296 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800297 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
298 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
299 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
300 quotient++;
301 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800302 }
303
Ady Abraham62a0be22020-12-08 16:54:10 -0800304 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800305}
306
Rachel Leece6e0042023-06-27 11:22:54 -0700307float RefreshRateSelector::calculateNonExactMatchingDefaultLayerScoreLocked(
308 nsecs_t displayPeriod, nsecs_t layerPeriod) const {
309 // Find the actual rate the layer will render, assuming
310 // that layerPeriod is the minimal period to render a frame.
311 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
312 // then the actualLayerPeriod will be 32ms, because it is the
313 // smallest multiple of the display period which is >= layerPeriod.
314 auto actualLayerPeriod = displayPeriod;
315 int multiplier = 1;
316 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
317 multiplier++;
318 actualLayerPeriod = displayPeriod * multiplier;
319 }
320
321 // Because of the threshold we used above it's possible that score is slightly
322 // above 1.
323 return std::min(1.0f, static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
324}
325
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400326float RefreshRateSelector::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
327 Fps refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200328 constexpr float kScoreForFractionalPairs = .8f;
329
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800330 const auto displayPeriod = refreshRate.getPeriodNsecs();
Ady Abraham62a0be22020-12-08 16:54:10 -0800331 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
332 if (layer.vote == LayerVoteType::ExplicitDefault) {
Rachel Leece6e0042023-06-27 11:22:54 -0700333 return calculateNonExactMatchingDefaultLayerScoreLocked(displayPeriod, layerPeriod);
Ady Abraham62a0be22020-12-08 16:54:10 -0800334 }
335
Rachel Leee5514a72023-10-25 16:20:29 -0700336 if (layer.vote == LayerVoteType::ExplicitGte) {
337 using fps_approx_ops::operator>=;
338 if (refreshRate >= layer.desiredRefreshRate) {
339 return 1.0f;
340 } else {
341 return calculateDistanceScoreLocked(layer.desiredRefreshRate, refreshRate);
342 }
343 }
344
Ady Abraham62a0be22020-12-08 16:54:10 -0800345 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
346 layer.vote == LayerVoteType::Heuristic) {
Ady Abrahambd44e8a2023-07-24 11:30:06 -0700347 using fps_approx_ops::operator<;
348 if (refreshRate < 60_Hz) {
349 const bool favorsAtLeast60 =
350 std::find_if(mFrameRatesThatFavorsAtLeast60.begin(),
351 mFrameRatesThatFavorsAtLeast60.end(), [&](Fps fps) {
352 using fps_approx_ops::operator==;
353 return fps == layer.desiredRefreshRate;
354 }) != mFrameRatesThatFavorsAtLeast60.end();
355 if (favorsAtLeast60) {
356 return 0;
357 }
358 }
359
Ady Abraham68636062022-11-16 17:07:25 -0800360 const float multiplier = refreshRate.getValue() / layer.desiredRefreshRate.getValue();
361
362 // We only want to score this layer as a fractional pair if the content is not
363 // significantly faster than the display rate, at it would cause a significant frame drop.
364 // It is more appropriate to choose a higher display rate even if
365 // a pull-down will be required.
Rachel Lee36426fa2023-03-08 20:13:52 -0800366 constexpr float kMinMultiplier = 0.75f;
Ady Abraham68636062022-11-16 17:07:25 -0800367 if (multiplier >= kMinMultiplier &&
368 isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700369 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200370 }
371
Ady Abraham62a0be22020-12-08 16:54:10 -0800372 // Calculate how many display vsyncs we need to present a single frame for this
373 // layer
374 const auto [displayFramesQuotient, displayFramesRemainder] =
375 getDisplayFrames(layerPeriod, displayPeriod);
376 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
377 if (displayFramesRemainder == 0) {
378 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700379 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800380 }
381
382 if (displayFramesQuotient == 0) {
383 // Layer desired refresh rate is higher than the display rate.
384 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
385 (1.0f / (MAX_FRAMES_TO_FIT + 1));
386 }
387
388 // Layer desired refresh rate is lower than the display rate. Check how well it fits
389 // the cadence.
390 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
391 int iter = 2;
392 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
393 diff = diff - (displayPeriod - diff);
394 iter++;
395 }
396
Ady Abraham05243be2021-09-16 15:58:52 -0700397 return (1.0f / iter);
398 }
399
400 return 0;
401}
402
Rachel Leee5514a72023-10-25 16:20:29 -0700403float RefreshRateSelector::calculateDistanceScoreLocked(Fps referenceRate, Fps refreshRate) const {
404 using fps_approx_ops::operator>=;
405 const float ratio = referenceRate >= refreshRate
406 ? refreshRate.getValue() / referenceRate.getValue()
407 : referenceRate.getValue() / refreshRate.getValue();
408 // Use ratio^2 to get a lower score the more we get further from the reference rate.
ramindanid72ba162022-09-09 21:33:40 +0000409 return ratio * ratio;
410}
411
Rachel Leee5514a72023-10-25 16:20:29 -0700412float RefreshRateSelector::calculateDistanceScoreFromMaxLocked(Fps refreshRate) const {
413 const auto& maxFps = mAppRequestFrameRates.back().fps;
414 return calculateDistanceScoreLocked(maxFps, refreshRate);
415}
416
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400417float RefreshRateSelector::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
418 bool isSeamlessSwitch) const {
Ady Abraham05243be2021-09-16 15:58:52 -0700419 // Slightly prefer seamless switches.
420 constexpr float kSeamedSwitchPenalty = 0.95f;
421 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
422
Rachel Leece6e0042023-06-27 11:22:54 -0700423 if (layer.vote == LayerVoteType::ExplicitCategory) {
Rachel Lee9580ff12023-12-26 17:33:41 -0800424 // HighHint is considered later for touch boost.
425 if (layer.frameRateCategory == FrameRateCategory::HighHint) {
426 return 0.f;
427 }
428
Rachel Leece6e0042023-06-27 11:22:54 -0700429 if (getFrameRateCategoryRange(layer.frameRateCategory).includes(refreshRate)) {
430 return 1.f;
431 }
432
433 FpsRange categoryRange = getFrameRateCategoryRange(layer.frameRateCategory);
434 using fps_approx_ops::operator<;
435 if (refreshRate < categoryRange.min) {
436 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
437 categoryRange.min
438 .getPeriodNsecs());
439 }
440 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
441 categoryRange.max.getPeriodNsecs());
442 }
443
Ady Abraham05243be2021-09-16 15:58:52 -0700444 // If the layer wants Max, give higher score to the higher refresh rate
445 if (layer.vote == LayerVoteType::Max) {
Rachel Leee5514a72023-10-25 16:20:29 -0700446 return calculateDistanceScoreFromMaxLocked(refreshRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800447 }
448
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800449 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800450 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Ady Abraham68636062022-11-16 17:07:25 -0800451 if (supportsAppFrameRateOverrideByContent()) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800452 // Since we support frame rate override, allow refresh rates which are
453 // multiples of the layer's request, as those apps would be throttled
454 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800455 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800456 }
457
Ady Abrahamcc315492022-02-17 17:06:39 -0800458 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800459 }
460
Ady Abrahamcc315492022-02-17 17:06:39 -0800461 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700462 // the highest score.
Rachel Leece6e0042023-06-27 11:22:54 -0700463 if (layer.desiredRefreshRate.isValid() &&
464 getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700465 return 1.0f * seamlessness;
466 }
467
Ady Abrahamcc315492022-02-17 17:06:39 -0800468 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700469 // there is a small penalty attached to the score to favor the frame rates
470 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800471 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700472 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
473 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800474}
475
Ady Abraham68636062022-11-16 17:07:25 -0800476auto RefreshRateSelector::getRankedFrameRates(const std::vector<LayerRequirement>& layers,
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500477 GlobalSignals signals, Fps pacesetterFps) const
478 -> RankedFrameRates {
479 GetRankedFrameRatesCache cache{layers, signals, pacesetterFps};
480
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200481 std::lock_guard lock(mLock);
482
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500483 if (mGetRankedFrameRatesCache && mGetRankedFrameRatesCache->matches(cache)) {
Ady Abraham68636062022-11-16 17:07:25 -0800484 return mGetRankedFrameRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200485 }
486
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500487 cache.result = getRankedFrameRatesLocked(layers, signals, pacesetterFps);
488 mGetRankedFrameRatesCache = std::move(cache);
489 return mGetRankedFrameRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200490}
491
Rachel Lee7e796bc2024-11-05 10:58:48 -0800492using LayerRequirementPtrs = std::vector<const RefreshRateSelector::LayerRequirement*>;
493using PerUidLayerRequirements = std::unordered_map<uid_t, LayerRequirementPtrs>;
494
495PerUidLayerRequirements groupLayersByUid(
496 const std::vector<RefreshRateSelector::LayerRequirement>& layers) {
497 PerUidLayerRequirements layersByUid;
498 for (const auto& layer : layers) {
499 const auto it = layersByUid.emplace(layer.ownerUid, LayerRequirementPtrs()).first;
500 auto& layersWithSameUid = it->second;
501 layersWithSameUid.push_back(&layer);
502 }
503 return layersByUid;
504}
505
Ady Abraham68636062022-11-16 17:07:25 -0800506auto RefreshRateSelector::getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500507 GlobalSignals signals, Fps pacesetterFps) const
Ady Abraham68636062022-11-16 17:07:25 -0800508 -> RankedFrameRates {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000509 using namespace fps_approx_ops;
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000510 SFTRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800511 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700512
Ady Abrahamace3d052022-11-17 16:25:05 -0800513 const auto& activeMode = *getActiveModeLocked().modePtr;
ramindani38c84982022-08-29 18:02:57 +0000514
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500515 if (pacesetterFps.isValid()) {
516 ALOGV("Follower display");
517
518 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Descending,
519 std::nullopt, [&](FrameRateMode mode) {
520 return mode.modePtr->getPeakFps() == pacesetterFps;
521 });
522
523 if (!ranking.empty()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000524 SFTRACE_FORMAT_INSTANT("%s (Follower display)",
525 to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500526
527 return {ranking, kNoSignals, pacesetterFps};
528 }
529
530 ALOGW("Follower display cannot follow the pacesetter");
531 }
532
Ady Abraham68636062022-11-16 17:07:25 -0800533 // Keep the display at max frame rate for the duration of powering on the display.
ramindani38c84982022-08-29 18:02:57 +0000534 if (signals.powerOnImminent) {
535 ALOGV("Power On Imminent");
Ady Abrahamccf63862023-01-19 11:44:01 -0800536 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Descending);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000537 SFTRACE_FORMAT_INSTANT("%s (Power On Imminent)",
538 to_string(ranking.front().frameRateMode.fps).c_str());
Ady Abrahamccf63862023-01-19 11:44:01 -0800539 return {ranking, GlobalSignals{.powerOnImminent = true}};
ramindani38c84982022-08-29 18:02:57 +0000540 }
541
Rachel Lee7e796bc2024-11-05 10:58:48 -0800542 // A method for UI Toolkit to send the touch signal via "HighHint" category vote,
543 // which will touch boost when there are no ExplicitDefault layer votes on the app.
544 // At most one app can have the "HighHint" touch boost vote at a time.
545 // This accounts for cases such as games that use `setFrameRate`
546 // with Default compatibility to limit the frame rate and disabling touch boost.
547 bool isAppTouchBoost = false;
548 const auto layersByUid = groupLayersByUid(layers);
549 for (const auto& [uid, layersWithSameUid] : layersByUid) {
550 bool hasHighHint = false;
551 bool hasExplicitDefault = false;
552 for (const auto& layer : layersWithSameUid) {
553 switch (layer->vote) {
554 case LayerVoteType::ExplicitDefault:
555 hasExplicitDefault = true;
556 break;
557 case LayerVoteType::ExplicitCategory:
558 if (layer->frameRateCategory == FrameRateCategory::HighHint) {
559 hasHighHint = true;
560 }
561 break;
562 default:
563 // No action
564 break;
565 }
566 if (hasHighHint && hasExplicitDefault) {
567 break;
568 }
569 }
570
571 if (hasHighHint && !hasExplicitDefault) {
572 // Focused app has touch signal (HighHint) and no frame rate ExplicitDefault votes
573 // (which prevents touch boost due to games use case).
574 isAppTouchBoost = true;
575 break;
576 }
577 }
578
Ady Abraham8a82ba62020-01-17 12:43:17 -0800579 int noVoteLayers = 0;
Rachel Lee19f01d02024-03-13 20:42:24 -0700580 // Layers that prefer the same mode ("no-op").
581 int noPreferenceLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800582 int minVoteLayers = 0;
583 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800584 int explicitDefaultVoteLayers = 0;
585 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800586 int explicitExact = 0;
Rachel Leee5514a72023-10-25 16:20:29 -0700587 int explicitGteLayers = 0;
Rachel Leece6e0042023-06-27 11:22:54 -0700588 int explicitCategoryVoteLayers = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100589 int seamedFocusedLayers = 0;
Rachel Lee67afbea2023-09-28 15:35:07 -0700590 int categorySmoothSwitchOnlyLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800591
Ady Abraham8a82ba62020-01-17 12:43:17 -0800592 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800593 switch (layer.vote) {
594 case LayerVoteType::NoVote:
595 noVoteLayers++;
596 break;
597 case LayerVoteType::Min:
598 minVoteLayers++;
599 break;
600 case LayerVoteType::Max:
601 maxVoteLayers++;
602 break;
603 case LayerVoteType::ExplicitDefault:
604 explicitDefaultVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800605 break;
606 case LayerVoteType::ExplicitExactOrMultiple:
607 explicitExactOrMultipleVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800608 break;
609 case LayerVoteType::ExplicitExact:
610 explicitExact++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800611 break;
Rachel Leee5514a72023-10-25 16:20:29 -0700612 case LayerVoteType::ExplicitGte:
613 explicitGteLayers++;
614 break;
Rachel Leece6e0042023-06-27 11:22:54 -0700615 case LayerVoteType::ExplicitCategory:
Rachel Lee7e796bc2024-11-05 10:58:48 -0800616 // HighHint does not count as an explicit signal from an app. It is a touch signal
617 // sent from UI Toolkit.
618 if (layer.frameRateCategory != FrameRateCategory::HighHint) {
Rachel Lee9580ff12023-12-26 17:33:41 -0800619 explicitCategoryVoteLayers++;
620 }
Rachel Leef377b362023-09-06 15:01:06 -0700621 if (layer.frameRateCategory == FrameRateCategory::NoPreference) {
Rachel Lee19f01d02024-03-13 20:42:24 -0700622 noPreferenceLayers++;
Rachel Leef377b362023-09-06 15:01:06 -0700623 }
Rachel Leece6e0042023-06-27 11:22:54 -0700624 break;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800625 case LayerVoteType::Heuristic:
626 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800627 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200628
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100629 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
630 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200631 }
Rachel Lee67afbea2023-09-28 15:35:07 -0700632 if (layer.frameRateCategorySmoothSwitchOnly) {
633 categorySmoothSwitchOnlyLayers++;
634 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800635 }
636
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800637 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
Rachel Leee5514a72023-10-25 16:20:29 -0700638 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0 || explicitGteLayers > 0 ||
Rachel Leece6e0042023-06-27 11:22:54 -0700639 explicitCategoryVoteLayers > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700640
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200641 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800642 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700643
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200644 // If the default mode group is different from the group of current mode,
645 // this means a layer requesting a seamed mode switch just disappeared and
646 // we should switch back to the default group.
647 // However if a seamed layer is still present we anchor around the group
648 // of the current mode, in order to prevent unnecessary seamed mode switches
649 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800650 const auto anchorGroup =
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700651 seamedFocusedLayers > 0 ? activeMode.getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200652
Steven Thomasf734df42020-04-13 21:09:28 -0700653 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
654 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800655 if (signals.touch && !hasExplicitVoteLayers) {
ramindanid72ba162022-09-09 21:33:40 +0000656 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800657 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000658 SFTRACE_FORMAT_INSTANT("%s (Touch Boost)",
659 to_string(ranking.front().frameRateMode.fps).c_str());
Ady Abrahamccf63862023-01-19 11:44:01 -0800660 return {ranking, GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800661 }
662
Alec Mouri11232a22020-05-14 18:06:25 -0700663 // If the primary range consists of a single refresh rate then we can only
664 // move out the of range if layers explicitly request a different refresh
665 // rate.
Ady Abraham90f7fd22023-08-16 11:02:00 -0700666 if (!signals.touch && signals.idle &&
667 !(policy->primaryRangeIsSingleRate() && hasExplicitVoteLayers)) {
ramindanid72ba162022-09-09 21:33:40 +0000668 ALOGV("Idle");
Ady Abrahamccf63862023-01-19 11:44:01 -0800669 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000670 SFTRACE_FORMAT_INSTANT("%s (Idle)", to_string(ranking.front().frameRateMode.fps).c_str());
Ady Abrahamccf63862023-01-19 11:44:01 -0800671 return {ranking, GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700672 }
673
Steven Thomasdebafed2020-05-18 17:30:35 -0700674 if (layers.empty() || noVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000675 ALOGV("No layers with votes");
Ady Abrahamccf63862023-01-19 11:44:01 -0800676 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000677 SFTRACE_FORMAT_INSTANT("%s (No layers with votes)",
678 to_string(ranking.front().frameRateMode.fps).c_str());
Ady Abrahamccf63862023-01-19 11:44:01 -0800679 return {ranking, kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700680 }
681
Rachel Lee19f01d02024-03-13 20:42:24 -0700682 // If all layers are category NoPreference, use the current config.
683 if (noPreferenceLayers + noVoteLayers == layers.size()) {
684 ALOGV("All layers NoPreference");
Ady Abraham180d8002024-07-10 17:42:28 -0700685 constexpr float kScore = std::numeric_limits<float>::max();
686 FrameRateRanking currentMode;
687 currentMode.emplace_back(ScoredFrameRate{getActiveModeLocked(), kScore});
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000688 SFTRACE_FORMAT_INSTANT("%s (All layers NoPreference)",
Ady Abraham180d8002024-07-10 17:42:28 -0700689 to_string(currentMode.front().frameRateMode.fps).c_str());
690 return {currentMode, kNoSignals};
Rachel Lee19f01d02024-03-13 20:42:24 -0700691 }
692
Rachel Lee67afbea2023-09-28 15:35:07 -0700693 const bool smoothSwitchOnly = categorySmoothSwitchOnlyLayers > 0;
694 const DisplayModeId activeModeId = activeMode.getId();
695
Ady Abraham8a82ba62020-01-17 12:43:17 -0800696 // Only if all layers want Min we should return Min
697 if (noVoteLayers + minVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000698 ALOGV("All layers Min");
Rachel Lee67afbea2023-09-28 15:35:07 -0700699 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending,
700 std::nullopt, [&](FrameRateMode mode) {
701 return !smoothSwitchOnly ||
702 mode.modePtr->getId() == activeModeId;
703 });
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000704 SFTRACE_FORMAT_INSTANT("%s (All layers Min)",
705 to_string(ranking.front().frameRateMode.fps).c_str());
Ady Abrahamccf63862023-01-19 11:44:01 -0800706 return {ranking, kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800707 }
708
Ady Abraham8a82ba62020-01-17 12:43:17 -0800709 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800710 std::vector<RefreshRateScore> scores;
Ady Abraham68636062022-11-16 17:07:25 -0800711 scores.reserve(mAppRequestFrameRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800712
Ady Abraham68636062022-11-16 17:07:25 -0800713 for (const FrameRateMode& it : mAppRequestFrameRates) {
714 scores.emplace_back(RefreshRateScore{it, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800715 }
716
717 for (const auto& layer : layers) {
Rachel Leece6e0042023-06-27 11:22:54 -0700718 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f, category %s) ",
719 layer.name.c_str(), ftl::enum_string(layer.vote).c_str(), layer.weight,
720 layer.desiredRefreshRate.getValue(),
721 ftl::enum_string(layer.frameRateCategory).c_str());
Rachel Leed0694bc2023-09-12 14:57:58 -0700722 if (layer.isNoVote() || layer.frameRateCategory == FrameRateCategory::NoPreference ||
723 layer.vote == LayerVoteType::Min) {
Rachel Lee19f01d02024-03-13 20:42:24 -0700724 ALOGV("%s scoring skipped due to vote", formatLayerInfo(layer, layer.weight).c_str());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800725 continue;
726 }
727
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800728 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800729
Ady Abraham68636062022-11-16 17:07:25 -0800730 for (auto& [mode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
731 const auto& [fps, modePtr] = mode;
732 const bool isSeamlessSwitch = modePtr->getGroup() == activeMode.getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200733
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100734 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100735 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800736 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700737 to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200738 continue;
739 }
740
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100741 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
742 !layer.focused) {
743 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100744 " Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800745 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700746 to_string(activeMode).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100747 continue;
748 }
749
Rachel Lee67afbea2023-09-28 15:35:07 -0700750 if (smoothSwitchOnly && modePtr->getId() != activeModeId) {
751 ALOGV("%s ignores %s because it's non-VRR and smooth switch only."
752 " Current mode = %s",
753 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
754 to_string(activeMode).c_str());
755 continue;
756 }
757
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100758 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100759 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100760 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100761 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
762 // disappeared.
Ady Abraham68636062022-11-16 17:07:25 -0800763 const bool isInPolicyForDefault = modePtr->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100764 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100765 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham68636062022-11-16 17:07:25 -0800766 to_string(*modePtr).c_str(), to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200767 continue;
768 }
769
Ady Abraham90f7fd22023-08-16 11:02:00 -0700770 const bool inPrimaryPhysicalRange =
ramindania04b8a52023-08-07 18:49:47 -0700771 policy->primaryRanges.physical.includes(modePtr->getPeakFps());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700772 const bool inPrimaryRenderRange = policy->primaryRanges.render.includes(fps);
Rachel Lee861e3472024-10-14 13:32:48 -0700773 if (!mIsVrrDevice.load() &&
774 ((policy->primaryRangeIsSingleRate() && !inPrimaryPhysicalRange) ||
Ady Abraham90f7fd22023-08-16 11:02:00 -0700775 !inPrimaryRenderRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800776 !(layer.focused &&
777 (layer.vote == LayerVoteType::ExplicitDefault ||
778 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700779 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700780 // refresh rates outside the primary range.
Rachel Lee861e3472024-10-14 13:32:48 -0700781 ALOGV("%s ignores %s (primaryRangeIsSingleRate). Current mode = %s",
782 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
783 to_string(activeMode).c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700784 continue;
785 }
786
Ady Abraham68636062022-11-16 17:07:25 -0800787 const float layerScore = calculateLayerScoreLocked(layer, fps, isSeamlessSwitch);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000788 const float weightedLayerScore = weight * layerScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800789
Ady Abraham13cfb362022-08-13 05:12:13 +0000790 // Layer with fixed source has a special consideration which depends on the
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000791 // mConfig.frameRateMultipleThreshold. We don't want these layers to score
792 // refresh rates above the threshold, but we also don't want to favor the lower
793 // ones by having a greater number of layers scoring them. Instead, we calculate
794 // the score independently for these layers and later decide which
795 // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
796 // score 120 Hz, but desired 60 fps should contribute to the score.
797 const bool fixedSourceLayer = [](LayerVoteType vote) {
798 switch (vote) {
799 case LayerVoteType::ExplicitExactOrMultiple:
800 case LayerVoteType::Heuristic:
801 return true;
802 case LayerVoteType::NoVote:
803 case LayerVoteType::Min:
804 case LayerVoteType::Max:
805 case LayerVoteType::ExplicitDefault:
806 case LayerVoteType::ExplicitExact:
Rachel Leee5514a72023-10-25 16:20:29 -0700807 case LayerVoteType::ExplicitGte:
Rachel Leece6e0042023-06-27 11:22:54 -0700808 case LayerVoteType::ExplicitCategory:
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000809 return false;
810 }
811 }(layer.vote);
Ady Abraham62f51d92022-08-24 22:20:22 +0000812 const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000813 layer.desiredRefreshRate <
814 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
Ady Abraham62f51d92022-08-24 22:20:22 +0000815 if (fixedSourceLayer && layerBelowThreshold) {
Ady Abraham13cfb362022-08-13 05:12:13 +0000816 const bool modeAboveThreshold =
ramindania04b8a52023-08-07 18:49:47 -0700817 modePtr->getPeakFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
Ady Abraham62f51d92022-08-24 22:20:22 +0000818 if (modeAboveThreshold) {
ramindania04b8a52023-08-07 18:49:47 -0700819 ALOGV("%s gives %s (%s(%s)) fixed source (above threshold) score of %.4f",
Ady Abraham68636062022-11-16 17:07:25 -0800820 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700821 to_string(modePtr->getPeakFps()).c_str(),
822 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000823 fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000824 } else {
ramindania04b8a52023-08-07 18:49:47 -0700825 ALOGV("%s gives %s (%s(%s)) fixed source (below threshold) score of %.4f",
Ady Abraham68636062022-11-16 17:07:25 -0800826 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700827 to_string(modePtr->getPeakFps()).c_str(),
828 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000829 fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000830 }
831 } else {
ramindania04b8a52023-08-07 18:49:47 -0700832 ALOGV("%s gives %s (%s(%s)) score of %.4f", formatLayerInfo(layer, weight).c_str(),
833 to_string(fps).c_str(), to_string(modePtr->getPeakFps()).c_str(),
834 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000835 overallScore += weightedLayerScore;
836 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800837 }
838 }
839
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000840 // We want to find the best refresh rate without the fixed source layers,
Ady Abraham62f51d92022-08-24 22:20:22 +0000841 // so we could know whether we should add the modeAboveThreshold scores or not.
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000842 // If the best refresh rate is already above the threshold, it means that
843 // some non-fixed source layers already scored it, so we can just add the score
844 // for all fixed source layers, even the ones that are above the threshold.
845 const bool maxScoreAboveThreshold = [&] {
846 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
847 return false;
848 }
849
850 const auto maxScoreIt =
851 std::max_element(scores.begin(), scores.end(),
852 [](RefreshRateScore max, RefreshRateScore current) {
Ady Abraham68636062022-11-16 17:07:25 -0800853 return current.overallScore > max.overallScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000854 });
ramindania04b8a52023-08-07 18:49:47 -0700855 ALOGV("%s (%s(%s)) is the best refresh rate without fixed source layers. It is %s the "
Ady Abraham68636062022-11-16 17:07:25 -0800856 "threshold for "
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000857 "refresh rate multiples",
Ady Abraham68636062022-11-16 17:07:25 -0800858 to_string(maxScoreIt->frameRateMode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700859 to_string(maxScoreIt->frameRateMode.modePtr->getPeakFps()).c_str(),
860 to_string(maxScoreIt->frameRateMode.modePtr->getVsyncRate()).c_str(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000861 maxScoreAboveThreshold ? "above" : "below");
ramindania04b8a52023-08-07 18:49:47 -0700862 return maxScoreIt->frameRateMode.modePtr->getPeakFps() >=
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000863 Fps::fromValue(mConfig.frameRateMultipleThreshold);
864 }();
865
866 // Now we can add the fixed rate layers score
Ady Abraham68636062022-11-16 17:07:25 -0800867 for (auto& [frameRateMode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000868 overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000869 if (maxScoreAboveThreshold) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000870 overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000871 }
ramindania04b8a52023-08-07 18:49:47 -0700872 ALOGV("%s (%s(%s)) adjusted overallScore is %.4f", to_string(frameRateMode.fps).c_str(),
873 to_string(frameRateMode.modePtr->getPeakFps()).c_str(),
874 to_string(frameRateMode.modePtr->getVsyncRate()).c_str(), overallScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000875 }
876
877 // Now that we scored all the refresh rates we need to pick the one that got the highest
ramindanid72ba162022-09-09 21:33:40 +0000878 // overallScore. Sort the scores based on their overallScore in descending order of priority.
879 const RefreshRateOrder refreshRateOrder =
880 maxVoteLayers > 0 ? RefreshRateOrder::Descending : RefreshRateOrder::Ascending;
881 std::sort(scores.begin(), scores.end(),
882 RefreshRateScoreComparator{.refreshRateOrder = refreshRateOrder});
ramindanid72ba162022-09-09 21:33:40 +0000883
Ady Abraham68636062022-11-16 17:07:25 -0800884 FrameRateRanking ranking;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400885 ranking.reserve(scores.size());
886
887 std::transform(scores.begin(), scores.end(), back_inserter(ranking),
ramindanid72ba162022-09-09 21:33:40 +0000888 [](const RefreshRateScore& score) {
Ady Abraham68636062022-11-16 17:07:25 -0800889 return ScoredFrameRate{score.frameRateMode, score.overallScore};
ramindanid72ba162022-09-09 21:33:40 +0000890 });
Ady Abraham34702102020-02-10 14:12:05 -0800891
Ady Abraham37d46922022-10-05 13:08:51 -0700892 const bool noLayerScore = std::all_of(scores.begin(), scores.end(), [](RefreshRateScore score) {
893 return score.overallScore == 0;
894 });
895
Rachel Lee7bedfbf2024-09-04 19:35:44 -0700896 // TODO(b/364651864): Evaluate correctness of primaryRangeIsSingleRate.
897 if (!mIsVrrDevice.load() && policy->primaryRangeIsSingleRate()) {
Alec Mouri11232a22020-05-14 18:06:25 -0700898 // If we never scored any layers, then choose the rate from the primary
899 // range instead of picking a random score from the app range.
Ady Abraham37d46922022-10-05 13:08:51 -0700900 if (noLayerScore) {
ramindanid72ba162022-09-09 21:33:40 +0000901 ALOGV("Layers not scored");
Ady Abrahamccf63862023-01-19 11:44:01 -0800902 const auto descending = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000903 SFTRACE_FORMAT_INSTANT("%s (Layers not scored)",
904 to_string(descending.front().frameRateMode.fps).c_str());
Ady Abrahamccf63862023-01-19 11:44:01 -0800905 return {descending, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700906 } else {
Rachel Lee861e3472024-10-14 13:32:48 -0700907 ALOGV("%s (primaryRangeIsSingleRate)",
908 to_string(ranking.front().frameRateMode.fps).c_str());
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000909 SFTRACE_FORMAT_INSTANT("%s (primaryRangeIsSingleRate)",
910 to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400911 return {ranking, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700912 }
913 }
914
Steven Thomasf734df42020-04-13 21:09:28 -0700915 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
916 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
917 // vote we should not change it if we get a touch event. Only apply touch boost if it will
918 // actually increase the refresh rate over the normal selection.
Dominik Laskowski788cba82024-03-15 11:29:11 -0400919 const auto isTouchBoostForExplicitExact = [&]() -> bool {
Ady Abraham68636062022-11-16 17:07:25 -0800920 if (supportsAppFrameRateOverrideByContent()) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700921 // Enable touch boost if there are other layers besides exact
Ady Abraham52ad61c2024-03-06 11:39:35 -0800922 return explicitExact + noVoteLayers + explicitGteLayers != layers.size();
Ady Abraham5e4e9832021-06-14 13:40:56 -0700923 } else {
924 // Enable touch boost if there are no exact layers
925 return explicitExact == 0;
926 }
Dominik Laskowski788cba82024-03-15 11:29:11 -0400927 };
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700928
Dominik Laskowski788cba82024-03-15 11:29:11 -0400929 const auto isTouchBoostForCategory = [&]() -> bool {
930 return explicitCategoryVoteLayers + noVoteLayers + explicitGteLayers != layers.size();
931 };
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700932
Rachel Lee7e796bc2024-11-05 10:58:48 -0800933 // This accounts for cases such as games that use `setFrameRate` with Default
Rachel Lee9e2416c2024-01-23 15:03:57 -0800934 // compatibility to limit the frame rate, which should not have touch boost.
Rachel Lee7e796bc2024-11-05 10:58:48 -0800935 const bool isLateGlobalTouchBoost = signals.touch && explicitDefaultVoteLayers == 0;
936 const bool isLateTouchBoost = isLateGlobalTouchBoost || isAppTouchBoost;
937 if (isLateTouchBoost && isTouchBoostForExplicitExact() && isTouchBoostForCategory()) {
Dominik Laskowski788cba82024-03-15 11:29:11 -0400938 const auto touchRefreshRates = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
939 using fps_approx_ops::operator<;
940
Rachel Lee7bedfbf2024-09-04 19:35:44 -0700941 if (scores.front().frameRateMode.fps <= touchRefreshRates.front().frameRateMode.fps) {
942 ALOGV("Touch Boost [late]");
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000943 SFTRACE_FORMAT_INSTANT("%s (Touch Boost [late])",
944 to_string(touchRefreshRates.front().frameRateMode.fps).c_str());
Dominik Laskowski788cba82024-03-15 11:29:11 -0400945 return {touchRefreshRates, GlobalSignals{.touch = true}};
946 }
Steven Thomasf734df42020-04-13 21:09:28 -0700947 }
948
Ady Abraham37d46922022-10-05 13:08:51 -0700949 // If we never scored any layers, and we don't favor high refresh rates, prefer to stay with the
950 // current config
951 if (noLayerScore && refreshRateOrder == RefreshRateOrder::Ascending) {
Rachel Lee67afbea2023-09-28 15:35:07 -0700952 ALOGV("preferredDisplayMode");
Ady Abrahamccf63862023-01-19 11:44:01 -0800953 const auto ascendingWithPreferred =
954 rankFrameRates(anchorGroup, RefreshRateOrder::Ascending, activeMode.getId());
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000955 SFTRACE_FORMAT_INSTANT("%s (preferredDisplayMode)",
956 to_string(ascendingWithPreferred.front().frameRateMode.fps).c_str());
Ady Abrahamccf63862023-01-19 11:44:01 -0800957 return {ascendingWithPreferred, kNoSignals};
Ady Abraham37d46922022-10-05 13:08:51 -0700958 }
959
Dominik Laskowski788cba82024-03-15 11:29:11 -0400960 ALOGV("%s (scored)", to_string(ranking.front().frameRateMode.fps).c_str());
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000961 SFTRACE_FORMAT_INSTANT("%s (scored)", to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400962 return {ranking, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800963}
964
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400965auto RefreshRateSelector::getFrameRateOverrides(const std::vector<LayerRequirement>& layers,
966 Fps displayRefreshRate,
967 GlobalSignals globalSignals) const
968 -> UidToFrameRateOverride {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000969 SFTRACE_CALL();
Ady Abraham68636062022-11-16 17:07:25 -0800970 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Disabled) {
971 return {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800972 }
973
Ady Abraham68636062022-11-16 17:07:25 -0800974 ALOGV("%s: %zu layers", __func__, layers.size());
975 std::lock_guard lock(mLock);
976
Ady Abraham8ca643a2022-10-18 18:26:47 -0700977 const auto* policyPtr = getCurrentPolicyLocked();
978 // We don't want to run lower than 30fps
ramindania04b8a52023-08-07 18:49:47 -0700979 // TODO(b/297600226): revise this for dVRR
Ady Abraham8ca643a2022-10-18 18:26:47 -0700980 const Fps minFrameRate = std::max(policyPtr->appRequestRanges.render.min, 30_Hz, isApproxLess);
981
982 using fps_approx_ops::operator/;
983 const unsigned numMultiples = displayRefreshRate / minFrameRate;
984
985 std::vector<std::pair<Fps, float>> scoredFrameRates;
986 scoredFrameRates.reserve(numMultiples);
987
988 for (unsigned n = numMultiples; n > 0; n--) {
989 const Fps divisor = displayRefreshRate / n;
990 if (mConfig.enableFrameRateOverride ==
Ady Abraham68636062022-11-16 17:07:25 -0800991 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
992 !isNativeRefreshRate(divisor)) {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700993 continue;
994 }
995
996 if (policyPtr->appRequestRanges.render.includes(divisor)) {
997 ALOGV("%s: adding %s as a potential frame rate", __func__, to_string(divisor).c_str());
998 scoredFrameRates.emplace_back(divisor, 0);
999 }
1000 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001001
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001002 const auto layersByUid = groupLayersByUid(layers);
Ady Abraham62a0be22020-12-08 16:54:10 -08001003 UidToFrameRateOverride frameRateOverrides;
1004 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Rachel Lee93bec072024-02-23 17:29:34 -08001005 // Look for cases that should not have frame rate overrides.
1006 bool hasExplicitExactOrMultiple = false;
1007 bool hasExplicitDefault = false;
1008 bool hasHighHint = false;
Rachel Lee7e796bc2024-11-05 10:58:48 -08001009 bool hasSkipOverrideLayer = false;
Rachel Lee93bec072024-02-23 17:29:34 -08001010 for (const auto& layer : layersWithSameUid) {
1011 switch (layer->vote) {
1012 case LayerVoteType::ExplicitExactOrMultiple:
1013 hasExplicitExactOrMultiple = true;
1014 break;
1015 case LayerVoteType::ExplicitDefault:
1016 hasExplicitDefault = true;
1017 break;
1018 case LayerVoteType::ExplicitCategory:
1019 if (layer->frameRateCategory == FrameRateCategory::HighHint) {
1020 hasHighHint = true;
1021 }
1022 break;
Rachel Lee7e796bc2024-11-05 10:58:48 -08001023 case LayerVoteType::Max:
1024 case LayerVoteType::Heuristic:
1025 hasSkipOverrideLayer = true;
1026 break;
Rachel Lee93bec072024-02-23 17:29:34 -08001027 default:
1028 // No action
1029 break;
1030 }
Rachel Lee7e796bc2024-11-05 10:58:48 -08001031 if (hasExplicitExactOrMultiple && hasExplicitDefault && hasHighHint &&
1032 hasSkipOverrideLayer) {
Rachel Lee93bec072024-02-23 17:29:34 -08001033 break;
1034 }
1035 }
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001036
Rachel Lee7e796bc2024-11-05 10:58:48 -08001037 if (hasSkipOverrideLayer) {
1038 ALOGV("%s: Skipping due to vote(s): uid=%d", __func__, uid);
1039 continue;
1040 }
1041
Rachel Lee93bec072024-02-23 17:29:34 -08001042 // Layers with ExplicitExactOrMultiple expect touch boost
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001043 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Rachel Lee861e3472024-10-14 13:32:48 -07001044 ALOGV("%s: Skipping for touch (input signal): uid=%d", __func__, uid);
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001045 continue;
1046 }
1047
Rachel Lee93bec072024-02-23 17:29:34 -08001048 // Mirrors getRankedFrameRates. If there is no ExplicitDefault, expect touch boost and
1049 // skip frame rate override.
1050 if (hasHighHint && !hasExplicitDefault) {
Rachel Lee861e3472024-10-14 13:32:48 -07001051 ALOGV("%s: Skipping for touch (HighHint): uid=%d", __func__, uid);
Rachel Lee93bec072024-02-23 17:29:34 -08001052 continue;
1053 }
1054
Ady Abraham8ca643a2022-10-18 18:26:47 -07001055 for (auto& [_, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001056 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -08001057 }
1058
1059 for (const auto& layer : layersWithSameUid) {
Rachel Lee47adfcf2023-09-15 17:36:56 -07001060 if (layer->isNoVote() || layer->frameRateCategory == FrameRateCategory::NoPreference ||
1061 layer->vote == LayerVoteType::Min) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001062 continue;
1063 }
1064
1065 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Rachel Leece6e0042023-06-27 11:22:54 -07001066 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
1067 layer->vote != LayerVoteType::ExplicitExact &&
Rachel Leeef9fb682024-02-23 11:04:33 -08001068 layer->vote != LayerVoteType::ExplicitGte &&
Rachel Leece6e0042023-06-27 11:22:54 -07001069 layer->vote != LayerVoteType::ExplicitCategory,
1070 "Invalid layer vote type for frame rate overrides");
Ady Abraham8ca643a2022-10-18 18:26:47 -07001071 for (auto& [fps, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001072 constexpr bool isSeamlessSwitch = true;
Ady Abraham8ca643a2022-10-18 18:26:47 -07001073 const auto layerScore = calculateLayerScoreLocked(*layer, fps, isSeamlessSwitch);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001074 score += layer->weight * layerScore;
Rachel Lee861e3472024-10-14 13:32:48 -07001075 ALOGV("%s: %s gives %s fps score of %.4f", __func__,
1076 formatLayerInfo(*layer, layer->weight).c_str(), to_string(fps).c_str(),
1077 layerScore);
Ady Abraham62a0be22020-12-08 16:54:10 -08001078 }
1079 }
1080
Ady Abraham62a0be22020-12-08 16:54:10 -08001081 // If we never scored any layers, we don't have a preferred frame rate
Ady Abraham8ca643a2022-10-18 18:26:47 -07001082 if (std::all_of(scoredFrameRates.begin(), scoredFrameRates.end(),
1083 [](const auto& scoredFrameRate) {
1084 const auto [_, score] = scoredFrameRate;
1085 return score == 0;
1086 })) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001087 continue;
1088 }
1089
ramindanid72ba162022-09-09 21:33:40 +00001090 // Now that we scored all the refresh rates we need to pick the lowest refresh rate
1091 // that got the highest score.
Ady Abraham8ca643a2022-10-18 18:26:47 -07001092 const auto [overrideFps, _] =
1093 *std::max_element(scoredFrameRates.begin(), scoredFrameRates.end(),
1094 [](const auto& lhsPair, const auto& rhsPair) {
1095 const float lhs = lhsPair.second;
1096 const float rhs = rhsPair.second;
Ady Abraham68636062022-11-16 17:07:25 -08001097 return lhs < rhs && !ScoredFrameRate::scoresEqual(lhs, rhs);
Ady Abraham8ca643a2022-10-18 18:26:47 -07001098 });
1099 ALOGV("%s: overriding to %s for uid=%d", __func__, to_string(overrideFps).c_str(), uid);
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001100 SFTRACE_FORMAT_INSTANT("%s: overriding to %s for uid=%d", __func__,
1101 to_string(overrideFps).c_str(), uid);
Vishnu Nair2665ca92024-07-09 22:08:15 +00001102 if (SFTRACE_ENABLED() && FlagManager::getInstance().trace_frame_rate_override()) {
Ady Abraham1d0cae92024-06-14 13:41:12 -07001103 std::stringstream ss;
1104 ss << "FrameRateOverride " << uid;
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001105 SFTRACE_INT(ss.str().c_str(), overrideFps.getIntValue());
Ady Abraham1d0cae92024-06-14 13:41:12 -07001106 }
Ady Abraham8ca643a2022-10-18 18:26:47 -07001107 frameRateOverrides.emplace(uid, overrideFps);
Ady Abraham62a0be22020-12-08 16:54:10 -08001108 }
1109
1110 return frameRateOverrides;
1111}
1112
Ady Abraham0aa373a2022-11-22 13:56:50 -08001113ftl::Optional<FrameRateMode> RefreshRateSelector::onKernelTimerChanged(
Dominik Laskowski59746512023-11-19 09:30:24 -05001114 ftl::Optional<DisplayModeId> desiredModeIdOpt, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -08001115 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001116
Dominik Laskowski61651552023-11-19 10:06:19 -05001117 const auto current =
1118 desiredModeIdOpt
1119 .and_then([this](DisplayModeId modeId)
1120 REQUIRES(mLock) { return mDisplayModes.get(modeId); })
1121 .transform([](const DisplayModePtr& modePtr) {
1122 return FrameRateMode{modePtr->getPeakFps(), ftl::as_non_null(modePtr)};
1123 })
1124 .or_else([this] {
1125 ftl::FakeGuard guard(mLock);
1126 return std::make_optional(getActiveModeLocked());
1127 })
1128 .value();
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001129
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001130 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
Ady Abraham0aa373a2022-11-22 13:56:50 -08001131 if (current.modePtr->getId() == min->getId()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001132 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001133 }
1134
ramindania04b8a52023-08-07 18:49:47 -07001135 return timerExpired ? FrameRateMode{min->getPeakFps(), ftl::as_non_null(min)} : current;
Steven Thomasf734df42020-04-13 21:09:28 -07001136}
1137
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001138const DisplayModePtr& RefreshRateSelector::getMinRefreshRateByPolicyLocked() const {
Ady Abrahamace3d052022-11-17 16:25:05 -08001139 const auto& activeMode = *getActiveModeLocked().modePtr;
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001140
Ady Abraham68636062022-11-16 17:07:25 -08001141 for (const FrameRateMode& mode : mPrimaryFrameRates) {
1142 if (activeMode.getGroup() == mode.modePtr->getGroup()) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001143 return mode.modePtr.get();
Marin Shalamanov46084422020-10-13 12:33:42 +02001144 }
1145 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001146
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001147 ALOGE("Can't find min refresh rate by policy with the same mode group as the current mode %s",
1148 to_string(activeMode).c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001149
1150 // Default to the lowest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -08001151 return mPrimaryFrameRates.front().modePtr.get();
Ady Abraham2139f732019-11-13 18:56:40 -08001152}
1153
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001154const DisplayModePtr& RefreshRateSelector::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Ady Abrahamace3d052022-11-17 16:25:05 -08001155 const ftl::NonNull<DisplayModePtr>* maxByAnchor = &mPrimaryFrameRates.back().modePtr;
1156 const ftl::NonNull<DisplayModePtr>* max = &mPrimaryFrameRates.back().modePtr;
Ady Abraham68636062022-11-16 17:07:25 -08001157
1158 bool maxByAnchorFound = false;
1159 for (auto it = mPrimaryFrameRates.rbegin(); it != mPrimaryFrameRates.rend(); ++it) {
1160 using namespace fps_approx_ops;
ramindania04b8a52023-08-07 18:49:47 -07001161 if (it->modePtr->getPeakFps() > (*max)->getPeakFps()) {
Ady Abraham68636062022-11-16 17:07:25 -08001162 max = &it->modePtr;
Marin Shalamanov46084422020-10-13 12:33:42 +02001163 }
Ady Abraham68636062022-11-16 17:07:25 -08001164
1165 if (anchorGroup == it->modePtr->getGroup() &&
ramindania04b8a52023-08-07 18:49:47 -07001166 it->modePtr->getPeakFps() >= (*maxByAnchor)->getPeakFps()) {
Ady Abraham68636062022-11-16 17:07:25 -08001167 maxByAnchorFound = true;
1168 maxByAnchor = &it->modePtr;
1169 }
1170 }
1171
1172 if (maxByAnchorFound) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001173 return maxByAnchor->get();
Marin Shalamanov46084422020-10-13 12:33:42 +02001174 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001175
ramindanid72ba162022-09-09 21:33:40 +00001176 ALOGE("Can't find max refresh rate by policy with the same group %d", anchorGroup);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001177
1178 // Default to the highest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -08001179 return max->get();
Ady Abraham2139f732019-11-13 18:56:40 -08001180}
1181
Ady Abraham68636062022-11-16 17:07:25 -08001182auto RefreshRateSelector::rankFrameRates(std::optional<int> anchorGroupOpt,
1183 RefreshRateOrder refreshRateOrder,
Rachel Lee67afbea2023-09-28 15:35:07 -07001184 std::optional<DisplayModeId> preferredDisplayModeOpt,
1185 const RankFrameRatesPredicate& predicate) const
Ady Abraham68636062022-11-16 17:07:25 -08001186 -> FrameRateRanking {
Ady Abrahama5992df2023-01-27 21:10:57 -08001187 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -08001188 const char* const whence = __func__;
Ady Abrahama5992df2023-01-27 21:10:57 -08001189
1190 // find the highest frame rate for each display mode
1191 ftl::SmallMap<DisplayModeId, Fps, 8> maxRenderRateForMode;
1192 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
1193 if (ascending) {
1194 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1195 // use a lower frame rate when we want Ascending frame rates.
1196 for (const auto& frameRateMode : mPrimaryFrameRates) {
1197 if (anchorGroupOpt && frameRateMode.modePtr->getGroup() != anchorGroupOpt) {
1198 continue;
1199 }
1200
1201 const auto [iter, _] = maxRenderRateForMode.try_emplace(frameRateMode.modePtr->getId(),
1202 frameRateMode.fps);
1203 if (iter->second < frameRateMode.fps) {
1204 iter->second = frameRateMode.fps;
1205 }
1206 }
1207 }
1208
Ady Abraham68636062022-11-16 17:07:25 -08001209 std::deque<ScoredFrameRate> ranking;
1210 const auto rankFrameRate = [&](const FrameRateMode& frameRateMode) REQUIRES(mLock) {
1211 const auto& modePtr = frameRateMode.modePtr;
Rachel Lee67afbea2023-09-28 15:35:07 -07001212 if ((anchorGroupOpt && modePtr->getGroup() != anchorGroupOpt) ||
1213 !predicate(frameRateMode)) {
Ady Abraham37d46922022-10-05 13:08:51 -07001214 return;
ramindanid72ba162022-09-09 21:33:40 +00001215 }
Ady Abraham37d46922022-10-05 13:08:51 -07001216
Ady Abraham3f965922023-01-23 17:18:29 -08001217 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
ramindanif7075202023-03-10 00:24:34 +00001218 const auto id = modePtr->getId();
Ady Abrahama5992df2023-01-27 21:10:57 -08001219 if (ascending && frameRateMode.fps < *maxRenderRateForMode.get(id)) {
Ady Abraham3f965922023-01-23 17:18:29 -08001220 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1221 // use a lower frame rate when we want Ascending frame rates.
1222 return;
1223 }
1224
Rachel Leee5514a72023-10-25 16:20:29 -07001225 float score = calculateDistanceScoreFromMaxLocked(frameRateMode.fps);
Ady Abraham3f965922023-01-23 17:18:29 -08001226
1227 if (ascending) {
Ady Abraham37d46922022-10-05 13:08:51 -07001228 score = 1.0f / score;
1229 }
ramindanif7075202023-03-10 00:24:34 +00001230
1231 constexpr float kScore = std::numeric_limits<float>::max();
Ady Abraham37d46922022-10-05 13:08:51 -07001232 if (preferredDisplayModeOpt) {
Ady Abraham68636062022-11-16 17:07:25 -08001233 if (*preferredDisplayModeOpt == modePtr->getId()) {
Ady Abraham68636062022-11-16 17:07:25 -08001234 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
Ady Abraham37d46922022-10-05 13:08:51 -07001235 return;
1236 }
1237 constexpr float kNonPreferredModePenalty = 0.95f;
1238 score *= kNonPreferredModePenalty;
ramindanif7075202023-03-10 00:24:34 +00001239 } else if (ascending && id == getMinRefreshRateByPolicyLocked()->getId()) {
1240 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround
1241 // and actually use a lower frame rate when we want Ascending frame rates.
1242 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
1243 return;
Ady Abraham37d46922022-10-05 13:08:51 -07001244 }
Ady Abraham3f965922023-01-23 17:18:29 -08001245
ramindania04b8a52023-08-07 18:49:47 -07001246 ALOGV("%s(%s) %s (%s(%s)) scored %.2f", whence, ftl::enum_string(refreshRateOrder).c_str(),
1247 to_string(frameRateMode.fps).c_str(), to_string(modePtr->getPeakFps()).c_str(),
1248 to_string(modePtr->getVsyncRate()).c_str(), score);
Ady Abraham68636062022-11-16 17:07:25 -08001249 ranking.emplace_back(ScoredFrameRate{frameRateMode, score});
ramindanid72ba162022-09-09 21:33:40 +00001250 };
1251
1252 if (refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abraham68636062022-11-16 17:07:25 -08001253 std::for_each(mPrimaryFrameRates.begin(), mPrimaryFrameRates.end(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001254 } else {
Ady Abraham68636062022-11-16 17:07:25 -08001255 std::for_each(mPrimaryFrameRates.rbegin(), mPrimaryFrameRates.rend(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001256 }
1257
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001258 if (!ranking.empty() || !anchorGroupOpt) {
1259 return {ranking.begin(), ranking.end()};
ramindanid72ba162022-09-09 21:33:40 +00001260 }
1261
1262 ALOGW("Can't find %s refresh rate by policy with the same mode group"
1263 " as the mode group %d",
1264 refreshRateOrder == RefreshRateOrder::Ascending ? "min" : "max", anchorGroupOpt.value());
1265
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001266 constexpr std::optional<int> kNoAnchorGroup = std::nullopt;
Ady Abraham68636062022-11-16 17:07:25 -08001267 return rankFrameRates(kNoAnchorGroup, refreshRateOrder, preferredDisplayModeOpt);
ramindanid72ba162022-09-09 21:33:40 +00001268}
1269
Ady Abrahamace3d052022-11-17 16:25:05 -08001270FrameRateMode RefreshRateSelector::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -08001271 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001272 return getActiveModeLocked();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001273}
1274
Ady Abrahamace3d052022-11-17 16:25:05 -08001275const FrameRateMode& RefreshRateSelector::getActiveModeLocked() const {
1276 return *mActiveModeOpt;
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001277}
1278
Ady Abrahamace3d052022-11-17 16:25:05 -08001279void RefreshRateSelector::setActiveMode(DisplayModeId modeId, Fps renderFrameRate) {
Ady Abraham2139f732019-11-13 18:56:40 -08001280 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001281
Ady Abraham68636062022-11-16 17:07:25 -08001282 // Invalidate the cached invocation to getRankedFrameRates. This forces
1283 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1284 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001285
Ady Abrahamace3d052022-11-17 16:25:05 -08001286 const auto activeModeOpt = mDisplayModes.get(modeId);
1287 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1288
1289 mActiveModeOpt.emplace(FrameRateMode{renderFrameRate, ftl::as_non_null(activeModeOpt->get())});
Rachel Lee45681982024-03-14 18:40:15 -07001290 mIsVrrDevice = FlagManager::getInstance().vrr_config() &&
1291 activeModeOpt->get()->getVrrConfig().has_value();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001292}
1293
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001294RefreshRateSelector::RefreshRateSelector(DisplayModes modes, DisplayModeId activeModeId,
1295 Config config)
rnlee3bd610662021-06-23 16:27:57 -07001296 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham67231722024-03-21 18:06:21 -07001297 initializeIdleTimer(mConfig.legacyIdleTimerTimeout);
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001298 FTL_FAKE_GUARD(kMainThreadContext, updateDisplayModes(std::move(modes), activeModeId));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001299}
1300
Ady Abraham67231722024-03-21 18:06:21 -07001301void RefreshRateSelector::initializeIdleTimer(std::chrono::milliseconds timeout) {
1302 if (timeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001303 mIdleTimer.emplace(
Ady Abraham67231722024-03-21 18:06:21 -07001304 "IdleTimer", timeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001305 [this] {
1306 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1307 if (const auto callbacks = getIdleTimerCallbacks()) {
1308 callbacks->onReset();
1309 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001310 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001311 [this] {
1312 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1313 if (const auto callbacks = getIdleTimerCallbacks()) {
1314 callbacks->onExpired();
1315 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001316 });
Ady Abraham9a2ea342021-09-03 17:32:34 -07001317 }
1318}
1319
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001320void RefreshRateSelector::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001321 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001322
Ady Abraham68636062022-11-16 17:07:25 -08001323 // Invalidate the cached invocation to getRankedFrameRates. This forces
1324 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1325 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001326
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001327 mDisplayModes = std::move(modes);
Ady Abrahamace3d052022-11-17 16:25:05 -08001328 const auto activeModeOpt = mDisplayModes.get(activeModeId);
1329 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
ramindania04b8a52023-08-07 18:49:47 -07001330 mActiveModeOpt = FrameRateMode{activeModeOpt->get()->getPeakFps(),
1331 ftl::as_non_null(activeModeOpt->get())};
Rachel Lee861e3472024-10-14 13:32:48 -07001332 mIsVrrDevice = FlagManager::getInstance().vrr_config() &&
1333 activeModeOpt->get()->getVrrConfig().has_value();
Ady Abrahamabc27602020-04-08 17:20:29 -07001334
Ady Abraham68636062022-11-16 17:07:25 -08001335 const auto sortedModes = sortByRefreshRate(mDisplayModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001336 mMinRefreshRateModeIt = sortedModes.front();
1337 mMaxRefreshRateModeIt = sortedModes.back();
1338
Marin Shalamanov75f37252021-02-10 21:43:57 +01001339 // Reset the policy because the old one may no longer be valid.
1340 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001341 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -08001342
Ady Abraham8ca643a2022-10-18 18:26:47 -07001343 mFrameRateOverrideConfig = [&] {
1344 switch (mConfig.enableFrameRateOverride) {
1345 case Config::FrameRateOverride::Disabled:
Ady Abraham68636062022-11-16 17:07:25 -08001346 case Config::FrameRateOverride::AppOverride:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001347 case Config::FrameRateOverride::Enabled:
1348 return mConfig.enableFrameRateOverride;
Ady Abraham68636062022-11-16 17:07:25 -08001349 case Config::FrameRateOverride::AppOverrideNativeRefreshRates:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001350 return shouldEnableFrameRateOverride(sortedModes)
Ady Abraham68636062022-11-16 17:07:25 -08001351 ? Config::FrameRateOverride::AppOverrideNativeRefreshRates
Ady Abraham8ca643a2022-10-18 18:26:47 -07001352 : Config::FrameRateOverride::Disabled;
1353 }
1354 }();
Ady Abraham4899ff82021-01-06 13:53:29 -08001355
Ady Abraham68636062022-11-16 17:07:25 -08001356 if (mConfig.enableFrameRateOverride ==
1357 Config::FrameRateOverride::AppOverrideNativeRefreshRates) {
1358 for (const auto& [_, mode] : mDisplayModes) {
ramindania04b8a52023-08-07 18:49:47 -07001359 mAppOverrideNativeRefreshRates.try_emplace(mode->getPeakFps(), ftl::unit);
Ady Abraham68636062022-11-16 17:07:25 -08001360 }
1361 }
1362
Ady Abrahamabc27602020-04-08 17:20:29 -07001363 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001364}
1365
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001366bool RefreshRateSelector::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001367 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001368 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
ramindania04b8a52023-08-07 18:49:47 -07001369 if (!policy.primaryRanges.physical.includes(mode->get()->getPeakFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001370 ALOGE("Default mode is not in the primary range.");
1371 return false;
1372 }
1373 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001374 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -07001375 return false;
1376 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001377
Ady Abraham68636062022-11-16 17:07:25 -08001378 const auto& primaryRanges = policy.primaryRanges;
1379 const auto& appRequestRanges = policy.appRequestRanges;
1380 ALOGE_IF(!appRequestRanges.physical.includes(primaryRanges.physical),
Ady Abraham08048ce2022-11-30 18:08:00 -08001381 "Physical range is invalid: primary: %s appRequest: %s",
1382 to_string(primaryRanges.physical).c_str(),
1383 to_string(appRequestRanges.physical).c_str());
1384 ALOGE_IF(!appRequestRanges.render.includes(primaryRanges.render),
1385 "Render range is invalid: primary: %s appRequest: %s",
1386 to_string(primaryRanges.render).c_str(), to_string(appRequestRanges.render).c_str());
Ady Abraham68636062022-11-16 17:07:25 -08001387
1388 return primaryRanges.valid() && appRequestRanges.valid();
Steven Thomasd4071902020-03-24 16:02:53 -07001389}
1390
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001391auto RefreshRateSelector::setPolicy(const PolicyVariant& policy) -> SetPolicyResult {
Dominik Laskowski36dced82022-09-02 09:24:00 -07001392 Policy oldPolicy;
Ady Abrahamace3d052022-11-17 16:25:05 -08001393 PhysicalDisplayId displayId;
Dominik Laskowski36dced82022-09-02 09:24:00 -07001394 {
1395 std::lock_guard lock(mLock);
1396 oldPolicy = *getCurrentPolicyLocked();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001397
Dominik Laskowski36dced82022-09-02 09:24:00 -07001398 const bool valid = ftl::match(
1399 policy,
1400 [this](const auto& policy) {
1401 ftl::FakeGuard guard(mLock);
1402 if (!isPolicyValidLocked(policy)) {
1403 ALOGE("Invalid policy: %s", policy.toString().c_str());
1404 return false;
1405 }
1406
1407 using T = std::decay_t<decltype(policy)>;
1408
1409 if constexpr (std::is_same_v<T, DisplayManagerPolicy>) {
1410 mDisplayManagerPolicy = policy;
1411 } else {
1412 static_assert(std::is_same_v<T, OverridePolicy>);
1413 mOverridePolicy = policy;
1414 }
1415 return true;
1416 },
1417 [this](NoOverridePolicy) {
1418 ftl::FakeGuard guard(mLock);
1419 mOverridePolicy.reset();
1420 return true;
1421 });
1422
1423 if (!valid) {
1424 return SetPolicyResult::Invalid;
1425 }
1426
Ady Abraham68636062022-11-16 17:07:25 -08001427 mGetRankedFrameRatesCache.reset();
Dominik Laskowski36dced82022-09-02 09:24:00 -07001428
Ady Abraham67231722024-03-21 18:06:21 -07001429 const auto& idleScreenConfigOpt = getCurrentPolicyLocked()->idleScreenConfigOpt;
1430 if (idleScreenConfigOpt != oldPolicy.idleScreenConfigOpt) {
1431 if (!idleScreenConfigOpt.has_value()) {
Rachel Lee50edf0f2024-09-10 13:46:23 -07001432 if (mIdleTimer) {
1433 // fallback to legacy timer if existed, otherwise pause the old timer
1434 if (mConfig.legacyIdleTimerTimeout > 0ms) {
1435 mIdleTimer->setInterval(mConfig.legacyIdleTimerTimeout);
1436 mIdleTimer->resume();
1437 } else {
1438 mIdleTimer->pause();
1439 }
Ady Abraham67231722024-03-21 18:06:21 -07001440 }
1441 } else if (idleScreenConfigOpt->timeoutMillis > 0) {
1442 // create a new timer or reconfigure
1443 const auto timeout = std::chrono::milliseconds{idleScreenConfigOpt->timeoutMillis};
1444 if (!mIdleTimer) {
1445 initializeIdleTimer(timeout);
1446 if (mIdleTimerStarted) {
1447 mIdleTimer->start();
1448 }
1449 } else {
1450 mIdleTimer->setInterval(timeout);
1451 mIdleTimer->resume();
1452 }
1453 } else {
1454 if (mIdleTimer) {
1455 mIdleTimer->pause();
1456 }
1457 }
1458 }
1459
1460 if (getCurrentPolicyLocked()->similarExceptIdleConfig(oldPolicy)) {
Dominik Laskowski36dced82022-09-02 09:24:00 -07001461 return SetPolicyResult::Unchanged;
1462 }
Ady Abraham67231722024-03-21 18:06:21 -07001463
Dominik Laskowski36dced82022-09-02 09:24:00 -07001464 constructAvailableRefreshRates();
Ady Abrahamace3d052022-11-17 16:25:05 -08001465
1466 displayId = getActiveModeLocked().modePtr->getPhysicalDisplayId();
Steven Thomasd4071902020-03-24 16:02:53 -07001467 }
Dominik Laskowski36dced82022-09-02 09:24:00 -07001468
Dominik Laskowski36dced82022-09-02 09:24:00 -07001469 const unsigned numModeChanges = std::exchange(mNumModeSwitchesInPolicy, 0u);
1470
1471 ALOGI("Display %s policy changed\n"
1472 "Previous: %s\n"
1473 "Current: %s\n"
1474 "%u mode changes were performed under the previous policy",
1475 to_string(displayId).c_str(), oldPolicy.toString().c_str(), toString(policy).c_str(),
1476 numModeChanges);
1477
1478 return SetPolicyResult::Changed;
Steven Thomasd4071902020-03-24 16:02:53 -07001479}
1480
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001481auto RefreshRateSelector::getCurrentPolicyLocked() const -> const Policy* {
Steven Thomasd4071902020-03-24 16:02:53 -07001482 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
1483}
1484
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001485auto RefreshRateSelector::getCurrentPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001486 std::lock_guard lock(mLock);
1487 return *getCurrentPolicyLocked();
1488}
1489
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001490auto RefreshRateSelector::getDisplayManagerPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001491 std::lock_guard lock(mLock);
1492 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001493}
1494
Ady Abrahamace3d052022-11-17 16:25:05 -08001495bool RefreshRateSelector::isModeAllowed(const FrameRateMode& mode) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001496 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001497 return std::find(mAppRequestFrameRates.begin(), mAppRequestFrameRates.end(), mode) !=
1498 mAppRequestFrameRates.end();
Ady Abraham2139f732019-11-13 18:56:40 -08001499}
1500
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001501void RefreshRateSelector::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001502 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -07001503 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001504 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -07001505
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001506 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -08001507
Ady Abraham68636062022-11-16 17:07:25 -08001508 const auto filterRefreshRates = [&](const FpsRanges& ranges,
1509 const char* rangeName) REQUIRES(mLock) {
1510 const auto filterModes = [&](const DisplayMode& mode) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001511 return mode.getResolution() == defaultMode->getResolution() &&
1512 mode.getDpi() == defaultMode->getDpi() &&
1513 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
ramindania04b8a52023-08-07 18:49:47 -07001514 ranges.physical.includes(mode.getPeakFps()) &&
1515 (supportsFrameRateOverride() || ranges.render.includes(mode.getPeakFps()));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001516 };
Ady Abraham8a82ba62020-01-17 12:43:17 -08001517
Ady Abraham90f7fd22023-08-16 11:02:00 -07001518 auto frameRateModes = createFrameRateModes(*policy, filterModes, ranges.render);
Ady Abraham41bf7c62023-07-20 10:33:06 -07001519 if (frameRateModes.empty()) {
1520 ALOGW("No matching frame rate modes for %s range. policy: %s", rangeName,
1521 policy->toString().c_str());
1522 // TODO(b/292105422): Ideally DisplayManager should not send render ranges smaller than
1523 // the min supported. See b/292047939.
1524 // For not we just ignore the render ranges.
Ady Abraham90f7fd22023-08-16 11:02:00 -07001525 frameRateModes = createFrameRateModes(*policy, filterModes, {});
Ady Abraham41bf7c62023-07-20 10:33:06 -07001526 }
Ady Abraham68636062022-11-16 17:07:25 -08001527 LOG_ALWAYS_FATAL_IF(frameRateModes.empty(),
Ady Abraham41bf7c62023-07-20 10:33:06 -07001528 "No matching frame rate modes for %s range even after ignoring the "
1529 "render range. policy: %s",
1530 rangeName, policy->toString().c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -08001531
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001532 const auto stringifyModes = [&] {
1533 std::string str;
Ady Abraham68636062022-11-16 17:07:25 -08001534 for (const auto& frameRateMode : frameRateModes) {
1535 str += to_string(frameRateMode) + " ";
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001536 }
1537 return str;
1538 };
Rachel Lee45681982024-03-14 18:40:15 -07001539 ALOGV("%s render rates: %s, isVrrDevice? %d", rangeName, stringifyModes().c_str(),
Ady Abrahameba039c2024-07-10 17:45:29 -07001540 mIsVrrDevice.load());
Steven Thomasf734df42020-04-13 21:09:28 -07001541
Ady Abraham68636062022-11-16 17:07:25 -08001542 return frameRateModes;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001543 };
1544
Ady Abraham68636062022-11-16 17:07:25 -08001545 mPrimaryFrameRates = filterRefreshRates(policy->primaryRanges, "primary");
1546 mAppRequestFrameRates = filterRefreshRates(policy->appRequestRanges, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -08001547}
1548
Rachel Lee45681982024-03-14 18:40:15 -07001549bool RefreshRateSelector::isVrrDevice() const {
Rachel Lee45681982024-03-14 18:40:15 -07001550 return mIsVrrDevice;
1551}
1552
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001553Fps RefreshRateSelector::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001554 using namespace fps_approx_ops;
1555
1556 if (frameRate <= mKnownFrameRates.front()) {
1557 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001558 }
1559
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001560 if (frameRate >= mKnownFrameRates.back()) {
1561 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001562 }
1563
Marin Shalamanove8a663d2020-11-24 17:48:00 +01001564 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001565 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001566
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001567 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
1568 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001569 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
1570}
1571
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001572auto RefreshRateSelector::getIdleTimerAction() const -> KernelIdleTimerAction {
Ana Krulecb9afd792020-06-11 13:16:15 -07001573 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001574
ramindania04b8a52023-08-07 18:49:47 -07001575 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getPeakFps();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001576 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -07001577
1578 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
1579 // the min allowed refresh rate is higher than the device min, we do not want to enable the
1580 // timer.
ramindania04b8a52023-08-07 18:49:47 -07001581 if (isStrictlyLess(deviceMinFps, minByPolicy->getPeakFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001582 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001583 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001584
ramindanid72ba162022-09-09 21:33:40 +00001585 const DisplayModePtr& maxByPolicy =
Ady Abrahamace3d052022-11-17 16:25:05 -08001586 getMaxRefreshRateByPolicyLocked(getActiveModeLocked().modePtr->getGroup());
Ana Krulecb9afd792020-06-11 13:16:15 -07001587 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001588 // Turn on the timer when the min of the primary range is below the device min.
1589 if (const Policy* currentPolicy = getCurrentPolicyLocked();
Ady Abraham285f8c12022-10-11 17:12:14 -07001590 isApproxLess(currentPolicy->primaryRanges.physical.min, deviceMinFps)) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001591 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001592 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001593 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001594 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001595
Ana Krulecb9afd792020-06-11 13:16:15 -07001596 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001597 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001598}
1599
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001600int RefreshRateSelector::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -07001601 // This calculation needs to be in sync with the java code
1602 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001603
1604 // The threshold must be smaller than 0.001 in order to differentiate
1605 // between the fractional pairs (e.g. 59.94 and 60).
1606 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001607 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -07001608 const auto numPeriodsRounded = std::round(numPeriods);
1609 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001610 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -07001611 }
1612
Ady Abraham62f216c2020-10-13 19:07:23 -07001613 return static_cast<int>(numPeriodsRounded);
1614}
1615
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001616bool RefreshRateSelector::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001617 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001618 return isFractionalPairOrMultiple(bigger, smaller);
1619 }
1620
1621 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
1622 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001623 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
1624 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001625}
1626
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001627void RefreshRateSelector::dump(utils::Dumper& dumper) const {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001628 using namespace std::string_view_literals;
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001629
Marin Shalamanovba421a82020-11-10 21:49:26 +01001630 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +01001631
Ady Abrahamace3d052022-11-17 16:25:05 -08001632 const auto activeMode = getActiveModeLocked();
Ady Abraham93256082024-05-09 17:04:34 -07001633 dumper.dump("renderRate"sv, to_string(activeMode.fps));
1634 dumper.dump("activeMode"sv, to_string(*activeMode.modePtr));
Marin Shalamanovba421a82020-11-10 21:49:26 +01001635
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001636 dumper.dump("displayModes"sv);
1637 {
1638 utils::Dumper::Indent indent(dumper);
1639 for (const auto& [id, mode] : mDisplayModes) {
1640 dumper.dump({}, to_string(*mode));
1641 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001642 }
1643
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001644 dumper.dump("displayManagerPolicy"sv, mDisplayManagerPolicy.toString());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001645
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001646 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
1647 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001648 dumper.dump("overridePolicy"sv, currentPolicy.toString());
ramindani32cf0602022-03-02 02:30:29 +00001649 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001650
Ady Abraham8ca643a2022-10-18 18:26:47 -07001651 dumper.dump("frameRateOverrideConfig"sv, *ftl::enum_name(mFrameRateOverrideConfig));
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001652
Dominik Laskowski03cfce82022-11-02 12:13:29 -04001653 dumper.dump("idleTimer"sv);
1654 {
1655 utils::Dumper::Indent indent(dumper);
1656 dumper.dump("interval"sv, mIdleTimer.transform(&OneShotTimer::interval));
1657 dumper.dump("controller"sv,
1658 mConfig.kernelIdleTimerController
1659 .and_then(&ftl::enum_name<KernelIdleTimerController>)
1660 .value_or("Platform"sv));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001661 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001662}
1663
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001664std::chrono::milliseconds RefreshRateSelector::getIdleTimerTimeout() {
Ady Abraham67231722024-03-21 18:06:21 -07001665 if (FlagManager::getInstance().idle_screen_refresh_rate_timeout() && mIdleTimer) {
1666 return std::chrono::duration_cast<std::chrono::milliseconds>(mIdleTimer->interval());
1667 }
1668 return mConfig.legacyIdleTimerTimeout;
ramindani32cf0602022-03-02 02:30:29 +00001669}
1670
Rachel Leece6e0042023-06-27 11:22:54 -07001671// TODO(b/293651105): Extract category FpsRange mapping to OEM-configurable config.
1672FpsRange RefreshRateSelector::getFrameRateCategoryRange(FrameRateCategory category) {
1673 switch (category) {
1674 case FrameRateCategory::High:
1675 return FpsRange{90_Hz, 120_Hz};
1676 case FrameRateCategory::Normal:
ramindani9a6cfce2024-03-05 13:00:26 -08001677 return FpsRange{60_Hz, 120_Hz};
Rachel Leece6e0042023-06-27 11:22:54 -07001678 case FrameRateCategory::Low:
Rachel Lee714b1bd2024-06-24 11:22:15 -07001679 return FpsRange{48_Hz, 120_Hz};
Rachel Lee9580ff12023-12-26 17:33:41 -08001680 case FrameRateCategory::HighHint:
Rachel Leece6e0042023-06-27 11:22:54 -07001681 case FrameRateCategory::NoPreference:
1682 case FrameRateCategory::Default:
1683 LOG_ALWAYS_FATAL("Should not get fps range for frame rate category: %s",
1684 ftl::enum_string(category).c_str());
Rachel Leece6e0042023-06-27 11:22:54 -07001685 default:
1686 LOG_ALWAYS_FATAL("Invalid frame rate category for range: %s",
1687 ftl::enum_string(category).c_str());
Rachel Leece6e0042023-06-27 11:22:54 -07001688 }
1689}
1690
Ady Abraham2139f732019-11-13 18:56:40 -08001691} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001692
1693// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001694#pragma clang diagnostic pop // ignored "-Wextra"