blob: a7ba7313230fc4574a0eec808fa10941ae6a9b30 [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>
31#include <ftl/enum.h>
Dominik Laskowskif8734e02022-08-26 09:06:59 -070032#include <ftl/fake_guard.h>
Dominik Laskowski36dced82022-09-02 09:24:00 -070033#include <ftl/match.h>
Ady Abraham8ca643a2022-10-18 18:26:47 -070034#include <ftl/unit.h>
Ady Abrahamccf63862023-01-19 11:44:01 -080035#include <gui/TraceUtils.h>
Ady Abraham68636062022-11-16 17:07:25 -080036#include <scheduler/FrameRateMode.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070037#include <utils/Trace.h>
38
Ady Abraham4899ff82021-01-06 13:53:29 -080039#include "../SurfaceFlingerProperties.h"
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040040#include "RefreshRateSelector.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080041
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
Dominik Laskowskib0054a22022-03-03 09:03:06 -080048struct RefreshRateScore {
Ady Abraham68636062022-11-16 17:07:25 -080049 FrameRateMode frameRateMode;
Ady Abrahamae2e3c72022-08-13 05:12:13 +000050 float overallScore;
51 struct {
Ady Abraham62f51d92022-08-24 22:20:22 +000052 float modeBelowThreshold;
53 float modeAboveThreshold;
54 } fixedRateBelowThresholdLayersScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -080055};
56
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040057constexpr RefreshRateSelector::GlobalSignals kNoSignals;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080058
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040059std::string formatLayerInfo(const RefreshRateSelector::LayerRequirement& layer, float weight) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080060 return base::StringPrintf("%s (type=%s, weight=%.2f, seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070061 ftl::enum_string(layer.vote).c_str(), weight,
62 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010063 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010064}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010065
Marin Shalamanova7fe3042021-01-29 21:02:08 +010066std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070067 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010068 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010069
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070070 // Add all supported refresh rates.
Dominik Laskowskib0054a22022-03-03 09:03:06 -080071 for (const auto& [id, mode] : modes) {
72 knownFrameRates.push_back(mode->getFps());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010073 }
74
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070075 // Sort and remove duplicates.
76 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010077 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070078 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010079 knownFrameRates.end());
80 return knownFrameRates;
81}
82
Ady Abraham68636062022-11-16 17:07:25 -080083std::vector<DisplayModeIterator> sortByRefreshRate(const DisplayModes& modes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080084 std::vector<DisplayModeIterator> sortedModes;
85 sortedModes.reserve(modes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -080086 for (auto it = modes.begin(); it != modes.end(); ++it) {
Ady Abraham68636062022-11-16 17:07:25 -080087 sortedModes.push_back(it);
Dominik Laskowskib0054a22022-03-03 09:03:06 -080088 }
89
90 std::sort(sortedModes.begin(), sortedModes.end(), [](auto it1, auto it2) {
91 const auto& mode1 = it1->second;
92 const auto& mode2 = it2->second;
93
94 if (mode1->getVsyncPeriod() == mode2->getVsyncPeriod()) {
95 return mode1->getGroup() > mode2->getGroup();
96 }
97
98 return mode1->getVsyncPeriod() > mode2->getVsyncPeriod();
99 });
100
101 return sortedModes;
Marin Shalamanov46084422020-10-13 12:33:42 +0200102}
103
Ady Abraham68636062022-11-16 17:07:25 -0800104std::pair<unsigned, unsigned> divisorRange(Fps fps, FpsRange range,
105 RefreshRateSelector::Config::FrameRateOverride config) {
106 if (config != RefreshRateSelector::Config::FrameRateOverride::Enabled) {
107 return {1, 1};
108 }
109
110 using fps_approx_ops::operator/;
Ady Abraham08048ce2022-11-30 18:08:00 -0800111 // use signed type as `fps / range.max` might be 0
112 const auto start = std::max(1, static_cast<int>(fps / range.max) - 1);
Ady Abraham68636062022-11-16 17:07:25 -0800113 const auto end = fps /
114 std::max(range.min, RefreshRateSelector::kMinSupportedFrameRate,
115 fps_approx_ops::operator<);
116
117 return {start, end};
118}
119
Ady Abraham8ca643a2022-10-18 18:26:47 -0700120bool shouldEnableFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800121 for (const auto it1 : sortedModes) {
122 const auto& mode1 = it1->second;
123 for (const auto it2 : sortedModes) {
124 const auto& mode2 = it2->second;
125
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400126 if (RefreshRateSelector::getFrameRateDivisor(mode1->getFps(), mode2->getFps()) >= 2) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800127 return true;
128 }
129 }
130 }
131 return false;
132}
133
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400134std::string toString(const RefreshRateSelector::PolicyVariant& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700135 using namespace std::string_literals;
136
137 return ftl::match(
138 policy,
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400139 [](const RefreshRateSelector::DisplayManagerPolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700140 return "DisplayManagerPolicy"s + policy.toString();
141 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400142 [](const RefreshRateSelector::OverridePolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700143 return "OverridePolicy"s + policy.toString();
144 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400145 [](RefreshRateSelector::NoOverridePolicy) { return "NoOverridePolicy"s; });
Dominik Laskowski36dced82022-09-02 09:24:00 -0700146}
147
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800148} // namespace
149
Ady Abraham68636062022-11-16 17:07:25 -0800150auto RefreshRateSelector::createFrameRateModes(
151 std::function<bool(const DisplayMode&)>&& filterModes, const FpsRange& renderRange) const
152 -> std::vector<FrameRateMode> {
153 struct Key {
154 Fps fps;
155 int32_t group;
156 };
157
158 struct KeyLess {
159 bool operator()(const Key& a, const Key& b) const {
160 using namespace fps_approx_ops;
161 if (a.fps != b.fps) {
162 return a.fps < b.fps;
163 }
164
165 // For the same fps the order doesn't really matter, but we still
166 // want the behaviour of a strictly less operator.
167 // We use the group id as the secondary ordering for that.
168 return a.group < b.group;
169 }
170 };
171
172 std::map<Key, DisplayModeIterator, KeyLess> ratesMap;
173 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
174 const auto& [id, mode] = *it;
175
176 if (!filterModes(*mode)) {
177 continue;
178 }
179 const auto [start, end] =
180 divisorRange(mode->getFps(), renderRange, mConfig.enableFrameRateOverride);
181 for (auto divisor = start; divisor <= end; divisor++) {
182 const auto fps = mode->getFps() / divisor;
183 using fps_approx_ops::operator<;
Ady Abrahamdc0b3a72023-01-04 16:58:27 -0800184 if (divisor > 1 && fps < kMinSupportedFrameRate) {
Ady Abraham68636062022-11-16 17:07:25 -0800185 break;
186 }
187
188 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Enabled &&
189 !renderRange.includes(fps)) {
190 continue;
191 }
192
193 if (mConfig.enableFrameRateOverride ==
194 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
195 !isNativeRefreshRate(fps)) {
196 continue;
197 }
198
199 const auto [existingIter, emplaceHappened] =
200 ratesMap.try_emplace(Key{fps, mode->getGroup()}, it);
201 if (emplaceHappened) {
202 ALOGV("%s: including %s (%s)", __func__, to_string(fps).c_str(),
203 to_string(mode->getFps()).c_str());
204 } else {
205 // We might need to update the map as we found a lower refresh rate
206 if (isStrictlyLess(mode->getFps(), existingIter->second->second->getFps())) {
207 existingIter->second = it;
208 ALOGV("%s: changing %s (%s)", __func__, to_string(fps).c_str(),
209 to_string(mode->getFps()).c_str());
210 }
211 }
212 }
213 }
214
215 std::vector<FrameRateMode> frameRateModes;
216 frameRateModes.reserve(ratesMap.size());
217 for (const auto& [key, mode] : ratesMap) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800218 frameRateModes.emplace_back(FrameRateMode{key.fps, ftl::as_non_null(mode->second)});
Ady Abraham68636062022-11-16 17:07:25 -0800219 }
220
221 // We always want that the lowest frame rate will be corresponding to the
222 // lowest mode for power saving.
223 const auto lowestRefreshRateIt =
224 std::min_element(frameRateModes.begin(), frameRateModes.end(),
225 [](const FrameRateMode& lhs, const FrameRateMode& rhs) {
226 return isStrictlyLess(lhs.modePtr->getFps(),
227 rhs.modePtr->getFps());
228 });
229 frameRateModes.erase(frameRateModes.begin(), lowestRefreshRateIt);
230
231 return frameRateModes;
232}
233
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400234struct RefreshRateSelector::RefreshRateScoreComparator {
ramindanid72ba162022-09-09 21:33:40 +0000235 bool operator()(const RefreshRateScore& lhs, const RefreshRateScore& rhs) const {
Ady Abraham68636062022-11-16 17:07:25 -0800236 const auto& [frameRateMode, overallScore, _] = lhs;
ramindanid72ba162022-09-09 21:33:40 +0000237
Ady Abraham68636062022-11-16 17:07:25 -0800238 std::string name = to_string(frameRateMode);
239
ramindanid72ba162022-09-09 21:33:40 +0000240 ALOGV("%s sorting scores %.2f", name.c_str(), overallScore);
ramindanid72ba162022-09-09 21:33:40 +0000241
Ady Abraham68636062022-11-16 17:07:25 -0800242 if (!ScoredFrameRate::scoresEqual(overallScore, rhs.overallScore)) {
ramindanid72ba162022-09-09 21:33:40 +0000243 return overallScore > rhs.overallScore;
244 }
245
ramindanid72ba162022-09-09 21:33:40 +0000246 if (refreshRateOrder == RefreshRateOrder::Descending) {
247 using fps_approx_ops::operator>;
Ady Abraham68636062022-11-16 17:07:25 -0800248 return frameRateMode.fps > rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000249 } else {
250 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -0800251 return frameRateMode.fps < rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000252 }
253 }
254
255 const RefreshRateOrder refreshRateOrder;
256};
257
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400258std::string RefreshRateSelector::Policy::toString() const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700259 return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
Ady Abraham285f8c12022-10-11 17:12:14 -0700260 ", primaryRanges=%s, appRequestRanges=%s}",
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700261 defaultMode.value(), allowGroupSwitching ? "true" : "false",
Ady Abraham285f8c12022-10-11 17:12:14 -0700262 to_string(primaryRanges).c_str(),
263 to_string(appRequestRanges).c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200264}
265
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400266std::pair<nsecs_t, nsecs_t> RefreshRateSelector::getDisplayFrames(nsecs_t layerPeriod,
267 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800268 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
269 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
270 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
271 quotient++;
272 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800273 }
274
Ady Abraham62a0be22020-12-08 16:54:10 -0800275 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800276}
277
Rachel Leece6e0042023-06-27 11:22:54 -0700278float RefreshRateSelector::calculateNonExactMatchingDefaultLayerScoreLocked(
279 nsecs_t displayPeriod, nsecs_t layerPeriod) const {
280 // Find the actual rate the layer will render, assuming
281 // that layerPeriod is the minimal period to render a frame.
282 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
283 // then the actualLayerPeriod will be 32ms, because it is the
284 // smallest multiple of the display period which is >= layerPeriod.
285 auto actualLayerPeriod = displayPeriod;
286 int multiplier = 1;
287 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
288 multiplier++;
289 actualLayerPeriod = displayPeriod * multiplier;
290 }
291
292 // Because of the threshold we used above it's possible that score is slightly
293 // above 1.
294 return std::min(1.0f, static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
295}
296
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400297float RefreshRateSelector::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
298 Fps refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200299 constexpr float kScoreForFractionalPairs = .8f;
300
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800301 const auto displayPeriod = refreshRate.getPeriodNsecs();
Ady Abraham62a0be22020-12-08 16:54:10 -0800302 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
303 if (layer.vote == LayerVoteType::ExplicitDefault) {
Rachel Leece6e0042023-06-27 11:22:54 -0700304 return calculateNonExactMatchingDefaultLayerScoreLocked(displayPeriod, layerPeriod);
Ady Abraham62a0be22020-12-08 16:54:10 -0800305 }
306
307 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
308 layer.vote == LayerVoteType::Heuristic) {
Ady Abrahambd44e8a2023-07-24 11:30:06 -0700309 using fps_approx_ops::operator<;
310 if (refreshRate < 60_Hz) {
311 const bool favorsAtLeast60 =
312 std::find_if(mFrameRatesThatFavorsAtLeast60.begin(),
313 mFrameRatesThatFavorsAtLeast60.end(), [&](Fps fps) {
314 using fps_approx_ops::operator==;
315 return fps == layer.desiredRefreshRate;
316 }) != mFrameRatesThatFavorsAtLeast60.end();
317 if (favorsAtLeast60) {
318 return 0;
319 }
320 }
321
Ady Abraham68636062022-11-16 17:07:25 -0800322 const float multiplier = refreshRate.getValue() / layer.desiredRefreshRate.getValue();
323
324 // We only want to score this layer as a fractional pair if the content is not
325 // significantly faster than the display rate, at it would cause a significant frame drop.
326 // It is more appropriate to choose a higher display rate even if
327 // a pull-down will be required.
Rachel Lee36426fa2023-03-08 20:13:52 -0800328 constexpr float kMinMultiplier = 0.75f;
Ady Abraham68636062022-11-16 17:07:25 -0800329 if (multiplier >= kMinMultiplier &&
330 isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700331 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200332 }
333
Ady Abraham62a0be22020-12-08 16:54:10 -0800334 // Calculate how many display vsyncs we need to present a single frame for this
335 // layer
336 const auto [displayFramesQuotient, displayFramesRemainder] =
337 getDisplayFrames(layerPeriod, displayPeriod);
338 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
339 if (displayFramesRemainder == 0) {
340 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700341 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800342 }
343
344 if (displayFramesQuotient == 0) {
345 // Layer desired refresh rate is higher than the display rate.
346 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
347 (1.0f / (MAX_FRAMES_TO_FIT + 1));
348 }
349
350 // Layer desired refresh rate is lower than the display rate. Check how well it fits
351 // the cadence.
352 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
353 int iter = 2;
354 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
355 diff = diff - (displayPeriod - diff);
356 iter++;
357 }
358
Ady Abraham05243be2021-09-16 15:58:52 -0700359 return (1.0f / iter);
360 }
361
362 return 0;
363}
364
Ady Abraham68636062022-11-16 17:07:25 -0800365float RefreshRateSelector::calculateDistanceScoreFromMax(Fps refreshRate) const {
366 const auto& maxFps = mAppRequestFrameRates.back().fps;
367 const float ratio = refreshRate.getValue() / maxFps.getValue();
ramindanid72ba162022-09-09 21:33:40 +0000368 // Use ratio^2 to get a lower score the more we get further from peak
369 return ratio * ratio;
370}
371
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400372float RefreshRateSelector::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
373 bool isSeamlessSwitch) const {
Ady Abraham73c3df52023-01-12 18:09:31 -0800374 ATRACE_CALL();
Ady Abraham05243be2021-09-16 15:58:52 -0700375 // Slightly prefer seamless switches.
376 constexpr float kSeamedSwitchPenalty = 0.95f;
377 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
378
Rachel Leece6e0042023-06-27 11:22:54 -0700379 if (layer.vote == LayerVoteType::ExplicitCategory) {
380 if (getFrameRateCategoryRange(layer.frameRateCategory).includes(refreshRate)) {
381 return 1.f;
382 }
383
384 FpsRange categoryRange = getFrameRateCategoryRange(layer.frameRateCategory);
385 using fps_approx_ops::operator<;
386 if (refreshRate < categoryRange.min) {
387 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
388 categoryRange.min
389 .getPeriodNsecs());
390 }
391 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
392 categoryRange.max.getPeriodNsecs());
393 }
394
Ady Abraham05243be2021-09-16 15:58:52 -0700395 // If the layer wants Max, give higher score to the higher refresh rate
396 if (layer.vote == LayerVoteType::Max) {
Ady Abraham68636062022-11-16 17:07:25 -0800397 return calculateDistanceScoreFromMax(refreshRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800398 }
399
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800400 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800401 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Ady Abraham68636062022-11-16 17:07:25 -0800402 if (supportsAppFrameRateOverrideByContent()) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800403 // Since we support frame rate override, allow refresh rates which are
404 // multiples of the layer's request, as those apps would be throttled
405 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800406 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800407 }
408
Ady Abrahamcc315492022-02-17 17:06:39 -0800409 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800410 }
411
Ady Abrahamcc315492022-02-17 17:06:39 -0800412 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700413 // the highest score.
Rachel Leece6e0042023-06-27 11:22:54 -0700414 if (layer.desiredRefreshRate.isValid() &&
415 getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700416 return 1.0f * seamlessness;
417 }
418
Ady Abrahamcc315492022-02-17 17:06:39 -0800419 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700420 // there is a small penalty attached to the score to favor the frame rates
421 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800422 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700423 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
424 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800425}
426
Ady Abraham68636062022-11-16 17:07:25 -0800427auto RefreshRateSelector::getRankedFrameRates(const std::vector<LayerRequirement>& layers,
428 GlobalSignals signals) const -> RankedFrameRates {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200429 std::lock_guard lock(mLock);
430
Ady Abraham68636062022-11-16 17:07:25 -0800431 if (mGetRankedFrameRatesCache &&
432 mGetRankedFrameRatesCache->arguments == std::make_pair(layers, signals)) {
433 return mGetRankedFrameRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200434 }
435
Ady Abraham68636062022-11-16 17:07:25 -0800436 const auto result = getRankedFrameRatesLocked(layers, signals);
437 mGetRankedFrameRatesCache = GetRankedFrameRatesCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200438 return result;
439}
440
Ady Abraham68636062022-11-16 17:07:25 -0800441auto RefreshRateSelector::getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
442 GlobalSignals signals) const
443 -> RankedFrameRates {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000444 using namespace fps_approx_ops;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800445 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800446 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700447
Ady Abrahamace3d052022-11-17 16:25:05 -0800448 const auto& activeMode = *getActiveModeLocked().modePtr;
ramindani38c84982022-08-29 18:02:57 +0000449
Ady Abraham68636062022-11-16 17:07:25 -0800450 // Keep the display at max frame rate for the duration of powering on the display.
ramindani38c84982022-08-29 18:02:57 +0000451 if (signals.powerOnImminent) {
452 ALOGV("Power On Imminent");
Ady Abrahamccf63862023-01-19 11:44:01 -0800453 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Descending);
454 ATRACE_FORMAT_INSTANT("%s (Power On Imminent)",
455 to_string(ranking.front().frameRateMode.fps).c_str());
456 return {ranking, GlobalSignals{.powerOnImminent = true}};
ramindani38c84982022-08-29 18:02:57 +0000457 }
458
Ady Abraham8a82ba62020-01-17 12:43:17 -0800459 int noVoteLayers = 0;
460 int minVoteLayers = 0;
461 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800462 int explicitDefaultVoteLayers = 0;
463 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800464 int explicitExact = 0;
Rachel Leece6e0042023-06-27 11:22:54 -0700465 int explicitCategoryVoteLayers = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100466 int seamedFocusedLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800467
Ady Abraham8a82ba62020-01-17 12:43:17 -0800468 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800469 switch (layer.vote) {
470 case LayerVoteType::NoVote:
471 noVoteLayers++;
472 break;
473 case LayerVoteType::Min:
474 minVoteLayers++;
475 break;
476 case LayerVoteType::Max:
477 maxVoteLayers++;
478 break;
479 case LayerVoteType::ExplicitDefault:
480 explicitDefaultVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800481 break;
482 case LayerVoteType::ExplicitExactOrMultiple:
483 explicitExactOrMultipleVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800484 break;
485 case LayerVoteType::ExplicitExact:
486 explicitExact++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800487 break;
Rachel Leece6e0042023-06-27 11:22:54 -0700488 case LayerVoteType::ExplicitCategory:
489 explicitCategoryVoteLayers++;
490 break;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800491 case LayerVoteType::Heuristic:
492 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800493 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200494
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100495 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
496 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200497 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800498 }
499
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800500 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
Rachel Leece6e0042023-06-27 11:22:54 -0700501 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0 ||
502 explicitCategoryVoteLayers > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700503
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200504 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800505 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700506
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200507 // If the default mode group is different from the group of current mode,
508 // this means a layer requesting a seamed mode switch just disappeared and
509 // we should switch back to the default group.
510 // However if a seamed layer is still present we anchor around the group
511 // of the current mode, in order to prevent unnecessary seamed mode switches
512 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800513 const auto anchorGroup =
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700514 seamedFocusedLayers > 0 ? activeMode.getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200515
Steven Thomasf734df42020-04-13 21:09:28 -0700516 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
517 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800518 if (signals.touch && !hasExplicitVoteLayers) {
ramindanid72ba162022-09-09 21:33:40 +0000519 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800520 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
521 ATRACE_FORMAT_INSTANT("%s (Touch Boost)",
522 to_string(ranking.front().frameRateMode.fps).c_str());
523 return {ranking, GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800524 }
525
Alec Mouri11232a22020-05-14 18:06:25 -0700526 // If the primary range consists of a single refresh rate then we can only
527 // move out the of range if layers explicitly request a different refresh
528 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100529 const bool primaryRangeIsSingleRate =
Ady Abraham285f8c12022-10-11 17:12:14 -0700530 isApproxEqual(policy->primaryRanges.physical.min, policy->primaryRanges.physical.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700531
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800532 if (!signals.touch && signals.idle && !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
ramindanid72ba162022-09-09 21:33:40 +0000533 ALOGV("Idle");
Ady Abrahamccf63862023-01-19 11:44:01 -0800534 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending);
535 ATRACE_FORMAT_INSTANT("%s (Idle)", to_string(ranking.front().frameRateMode.fps).c_str());
536 return {ranking, GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700537 }
538
Steven Thomasdebafed2020-05-18 17:30:35 -0700539 if (layers.empty() || noVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000540 ALOGV("No layers with votes");
Ady Abrahamccf63862023-01-19 11:44:01 -0800541 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
542 ATRACE_FORMAT_INSTANT("%s (No layers with votes)",
543 to_string(ranking.front().frameRateMode.fps).c_str());
544 return {ranking, kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700545 }
546
Ady Abraham8a82ba62020-01-17 12:43:17 -0800547 // Only if all layers want Min we should return Min
548 if (noVoteLayers + minVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000549 ALOGV("All layers Min");
Ady Abrahamccf63862023-01-19 11:44:01 -0800550 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending);
551 ATRACE_FORMAT_INSTANT("%s (All layers Min)",
552 to_string(ranking.front().frameRateMode.fps).c_str());
553 return {ranking, kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800554 }
555
Ady Abraham8a82ba62020-01-17 12:43:17 -0800556 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800557 std::vector<RefreshRateScore> scores;
Ady Abraham68636062022-11-16 17:07:25 -0800558 scores.reserve(mAppRequestFrameRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800559
Ady Abraham68636062022-11-16 17:07:25 -0800560 for (const FrameRateMode& it : mAppRequestFrameRates) {
561 scores.emplace_back(RefreshRateScore{it, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800562 }
563
564 for (const auto& layer : layers) {
Rachel Leece6e0042023-06-27 11:22:54 -0700565 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f, category %s) ",
566 layer.name.c_str(), ftl::enum_string(layer.vote).c_str(), layer.weight,
567 layer.desiredRefreshRate.getValue(),
568 ftl::enum_string(layer.frameRateCategory).c_str());
569 if (layer.isNoVote() || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800570 continue;
571 }
572
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800573 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800574
Ady Abraham68636062022-11-16 17:07:25 -0800575 for (auto& [mode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
576 const auto& [fps, modePtr] = mode;
577 const bool isSeamlessSwitch = modePtr->getGroup() == activeMode.getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200578
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100579 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100580 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800581 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700582 to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200583 continue;
584 }
585
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100586 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
587 !layer.focused) {
588 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100589 " Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800590 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700591 to_string(activeMode).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100592 continue;
593 }
594
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100595 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100596 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100597 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100598 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
599 // disappeared.
Ady Abraham68636062022-11-16 17:07:25 -0800600 const bool isInPolicyForDefault = modePtr->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100601 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100602 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham68636062022-11-16 17:07:25 -0800603 to_string(*modePtr).c_str(), to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200604 continue;
605 }
606
Ady Abrahamb26872a2023-03-29 17:51:20 -0700607 const bool inPrimaryRange = policy->primaryRanges.render.includes(fps);
Alec Mouri11232a22020-05-14 18:06:25 -0700608 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800609 !(layer.focused &&
610 (layer.vote == LayerVoteType::ExplicitDefault ||
611 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700612 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700613 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700614 continue;
615 }
616
Ady Abraham68636062022-11-16 17:07:25 -0800617 const float layerScore = calculateLayerScoreLocked(layer, fps, isSeamlessSwitch);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000618 const float weightedLayerScore = weight * layerScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800619
Ady Abraham13cfb362022-08-13 05:12:13 +0000620 // Layer with fixed source has a special consideration which depends on the
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000621 // mConfig.frameRateMultipleThreshold. We don't want these layers to score
622 // refresh rates above the threshold, but we also don't want to favor the lower
623 // ones by having a greater number of layers scoring them. Instead, we calculate
624 // the score independently for these layers and later decide which
625 // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
626 // score 120 Hz, but desired 60 fps should contribute to the score.
627 const bool fixedSourceLayer = [](LayerVoteType vote) {
628 switch (vote) {
629 case LayerVoteType::ExplicitExactOrMultiple:
630 case LayerVoteType::Heuristic:
631 return true;
632 case LayerVoteType::NoVote:
633 case LayerVoteType::Min:
634 case LayerVoteType::Max:
635 case LayerVoteType::ExplicitDefault:
636 case LayerVoteType::ExplicitExact:
Rachel Leece6e0042023-06-27 11:22:54 -0700637 case LayerVoteType::ExplicitCategory:
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000638 return false;
639 }
640 }(layer.vote);
Ady Abraham62f51d92022-08-24 22:20:22 +0000641 const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000642 layer.desiredRefreshRate <
643 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
Ady Abraham62f51d92022-08-24 22:20:22 +0000644 if (fixedSourceLayer && layerBelowThreshold) {
Ady Abraham13cfb362022-08-13 05:12:13 +0000645 const bool modeAboveThreshold =
Ady Abraham68636062022-11-16 17:07:25 -0800646 modePtr->getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
Ady Abraham62f51d92022-08-24 22:20:22 +0000647 if (modeAboveThreshold) {
Ady Abraham68636062022-11-16 17:07:25 -0800648 ALOGV("%s gives %s (%s) fixed source (above threshold) score of %.4f",
649 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
650 to_string(modePtr->getFps()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000651 fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000652 } else {
Ady Abraham68636062022-11-16 17:07:25 -0800653 ALOGV("%s gives %s (%s) fixed source (below threshold) score of %.4f",
654 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
655 to_string(modePtr->getFps()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000656 fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000657 }
658 } else {
Ady Abraham68636062022-11-16 17:07:25 -0800659 ALOGV("%s gives %s (%s) score of %.4f", formatLayerInfo(layer, weight).c_str(),
660 to_string(fps).c_str(), to_string(modePtr->getFps()).c_str(), layerScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000661 overallScore += weightedLayerScore;
662 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800663 }
664 }
665
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000666 // We want to find the best refresh rate without the fixed source layers,
Ady Abraham62f51d92022-08-24 22:20:22 +0000667 // so we could know whether we should add the modeAboveThreshold scores or not.
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000668 // If the best refresh rate is already above the threshold, it means that
669 // some non-fixed source layers already scored it, so we can just add the score
670 // for all fixed source layers, even the ones that are above the threshold.
671 const bool maxScoreAboveThreshold = [&] {
672 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
673 return false;
674 }
675
676 const auto maxScoreIt =
677 std::max_element(scores.begin(), scores.end(),
678 [](RefreshRateScore max, RefreshRateScore current) {
Ady Abraham68636062022-11-16 17:07:25 -0800679 return current.overallScore > max.overallScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000680 });
Ady Abraham68636062022-11-16 17:07:25 -0800681 ALOGV("%s (%s) is the best refresh rate without fixed source layers. It is %s the "
682 "threshold for "
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000683 "refresh rate multiples",
Ady Abraham68636062022-11-16 17:07:25 -0800684 to_string(maxScoreIt->frameRateMode.fps).c_str(),
685 to_string(maxScoreIt->frameRateMode.modePtr->getFps()).c_str(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000686 maxScoreAboveThreshold ? "above" : "below");
Ady Abraham68636062022-11-16 17:07:25 -0800687 return maxScoreIt->frameRateMode.modePtr->getFps() >=
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000688 Fps::fromValue(mConfig.frameRateMultipleThreshold);
689 }();
690
691 // Now we can add the fixed rate layers score
Ady Abraham68636062022-11-16 17:07:25 -0800692 for (auto& [frameRateMode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000693 overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000694 if (maxScoreAboveThreshold) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000695 overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000696 }
Ady Abraham68636062022-11-16 17:07:25 -0800697 ALOGV("%s (%s) adjusted overallScore is %.4f", to_string(frameRateMode.fps).c_str(),
698 to_string(frameRateMode.modePtr->getFps()).c_str(), overallScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000699 }
700
701 // Now that we scored all the refresh rates we need to pick the one that got the highest
ramindanid72ba162022-09-09 21:33:40 +0000702 // overallScore. Sort the scores based on their overallScore in descending order of priority.
703 const RefreshRateOrder refreshRateOrder =
704 maxVoteLayers > 0 ? RefreshRateOrder::Descending : RefreshRateOrder::Ascending;
705 std::sort(scores.begin(), scores.end(),
706 RefreshRateScoreComparator{.refreshRateOrder = refreshRateOrder});
ramindanid72ba162022-09-09 21:33:40 +0000707
Ady Abraham68636062022-11-16 17:07:25 -0800708 FrameRateRanking ranking;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400709 ranking.reserve(scores.size());
710
711 std::transform(scores.begin(), scores.end(), back_inserter(ranking),
ramindanid72ba162022-09-09 21:33:40 +0000712 [](const RefreshRateScore& score) {
Ady Abraham68636062022-11-16 17:07:25 -0800713 return ScoredFrameRate{score.frameRateMode, score.overallScore};
ramindanid72ba162022-09-09 21:33:40 +0000714 });
Ady Abraham34702102020-02-10 14:12:05 -0800715
Ady Abraham37d46922022-10-05 13:08:51 -0700716 const bool noLayerScore = std::all_of(scores.begin(), scores.end(), [](RefreshRateScore score) {
717 return score.overallScore == 0;
718 });
719
Alec Mouri11232a22020-05-14 18:06:25 -0700720 if (primaryRangeIsSingleRate) {
721 // If we never scored any layers, then choose the rate from the primary
722 // range instead of picking a random score from the app range.
Ady Abraham37d46922022-10-05 13:08:51 -0700723 if (noLayerScore) {
ramindanid72ba162022-09-09 21:33:40 +0000724 ALOGV("Layers not scored");
Ady Abrahamccf63862023-01-19 11:44:01 -0800725 const auto descending = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
726 ATRACE_FORMAT_INSTANT("%s (Layers not scored)",
727 to_string(descending.front().frameRateMode.fps).c_str());
728 return {descending, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700729 } else {
Ady Abrahamccf63862023-01-19 11:44:01 -0800730 ATRACE_FORMAT_INSTANT("%s (primaryRangeIsSingleRate)",
731 to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400732 return {ranking, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700733 }
734 }
735
Steven Thomasf734df42020-04-13 21:09:28 -0700736 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
737 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
738 // vote we should not change it if we get a touch event. Only apply touch boost if it will
739 // actually increase the refresh rate over the normal selection.
Ady Abraham5e4e9832021-06-14 13:40:56 -0700740 const bool touchBoostForExplicitExact = [&] {
Ady Abraham68636062022-11-16 17:07:25 -0800741 if (supportsAppFrameRateOverrideByContent()) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700742 // Enable touch boost if there are other layers besides exact
743 return explicitExact + noVoteLayers != layers.size();
744 } else {
745 // Enable touch boost if there are no exact layers
746 return explicitExact == 0;
747 }
748 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700749
Ady Abraham68636062022-11-16 17:07:25 -0800750 const auto touchRefreshRates = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700751 using fps_approx_ops::operator<;
752
Rachel Leece6e0042023-06-27 11:22:54 -0700753 if (signals.touch && explicitDefaultVoteLayers == 0 && explicitCategoryVoteLayers == 0 &&
754 touchBoostForExplicitExact &&
Ady Abraham68636062022-11-16 17:07:25 -0800755 scores.front().frameRateMode.fps < touchRefreshRates.front().frameRateMode.fps) {
ramindanid72ba162022-09-09 21:33:40 +0000756 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800757 ATRACE_FORMAT_INSTANT("%s (Touch Boost [late])",
758 to_string(touchRefreshRates.front().frameRateMode.fps).c_str());
ramindanid72ba162022-09-09 21:33:40 +0000759 return {touchRefreshRates, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700760 }
761
Ady Abraham37d46922022-10-05 13:08:51 -0700762 // If we never scored any layers, and we don't favor high refresh rates, prefer to stay with the
763 // current config
764 if (noLayerScore && refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abrahamccf63862023-01-19 11:44:01 -0800765 const auto ascendingWithPreferred =
766 rankFrameRates(anchorGroup, RefreshRateOrder::Ascending, activeMode.getId());
767 ATRACE_FORMAT_INSTANT("%s (preferredDisplayMode)",
768 to_string(ascendingWithPreferred.front().frameRateMode.fps).c_str());
769 return {ascendingWithPreferred, kNoSignals};
Ady Abraham37d46922022-10-05 13:08:51 -0700770 }
771
Ady Abrahamccf63862023-01-19 11:44:01 -0800772 ATRACE_FORMAT_INSTANT("%s (scored))", to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400773 return {ranking, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800774}
775
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400776using LayerRequirementPtrs = std::vector<const RefreshRateSelector::LayerRequirement*>;
777using PerUidLayerRequirements = std::unordered_map<uid_t, LayerRequirementPtrs>;
778
779PerUidLayerRequirements groupLayersByUid(
780 const std::vector<RefreshRateSelector::LayerRequirement>& layers) {
781 PerUidLayerRequirements layersByUid;
Ady Abraham62a0be22020-12-08 16:54:10 -0800782 for (const auto& layer : layers) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400783 const auto it = layersByUid.emplace(layer.ownerUid, LayerRequirementPtrs()).first;
784 auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800785 layersWithSameUid.push_back(&layer);
786 }
787
788 // Remove uids that can't have a frame rate override
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400789 for (auto it = layersByUid.begin(); it != layersByUid.end();) {
790 const auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800791 bool skipUid = false;
792 for (const auto& layer : layersWithSameUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400793 using LayerVoteType = RefreshRateSelector::LayerVoteType;
794
795 if (layer->vote == LayerVoteType::Max || layer->vote == LayerVoteType::Heuristic) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800796 skipUid = true;
797 break;
798 }
799 }
800 if (skipUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400801 it = layersByUid.erase(it);
Ady Abraham62a0be22020-12-08 16:54:10 -0800802 } else {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400803 ++it;
Ady Abraham62a0be22020-12-08 16:54:10 -0800804 }
805 }
806
807 return layersByUid;
808}
809
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400810auto RefreshRateSelector::getFrameRateOverrides(const std::vector<LayerRequirement>& layers,
811 Fps displayRefreshRate,
812 GlobalSignals globalSignals) const
813 -> UidToFrameRateOverride {
Ady Abraham62a0be22020-12-08 16:54:10 -0800814 ATRACE_CALL();
Ady Abraham68636062022-11-16 17:07:25 -0800815 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Disabled) {
816 return {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800817 }
818
Ady Abraham68636062022-11-16 17:07:25 -0800819 ALOGV("%s: %zu layers", __func__, layers.size());
820 std::lock_guard lock(mLock);
821
Ady Abraham8ca643a2022-10-18 18:26:47 -0700822 const auto* policyPtr = getCurrentPolicyLocked();
823 // We don't want to run lower than 30fps
824 const Fps minFrameRate = std::max(policyPtr->appRequestRanges.render.min, 30_Hz, isApproxLess);
825
826 using fps_approx_ops::operator/;
827 const unsigned numMultiples = displayRefreshRate / minFrameRate;
828
829 std::vector<std::pair<Fps, float>> scoredFrameRates;
830 scoredFrameRates.reserve(numMultiples);
831
832 for (unsigned n = numMultiples; n > 0; n--) {
833 const Fps divisor = displayRefreshRate / n;
834 if (mConfig.enableFrameRateOverride ==
Ady Abraham68636062022-11-16 17:07:25 -0800835 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
836 !isNativeRefreshRate(divisor)) {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700837 continue;
838 }
839
840 if (policyPtr->appRequestRanges.render.includes(divisor)) {
841 ALOGV("%s: adding %s as a potential frame rate", __func__, to_string(divisor).c_str());
842 scoredFrameRates.emplace_back(divisor, 0);
843 }
844 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800845
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400846 const auto layersByUid = groupLayersByUid(layers);
Ady Abraham62a0be22020-12-08 16:54:10 -0800847 UidToFrameRateOverride frameRateOverrides;
848 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800849 // Layers with ExplicitExactOrMultiple expect touch boost
850 const bool hasExplicitExactOrMultiple =
851 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
852 [](const auto& layer) {
853 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
854 });
855
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700856 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800857 continue;
858 }
859
Ady Abraham8ca643a2022-10-18 18:26:47 -0700860 for (auto& [_, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800861 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -0800862 }
863
864 for (const auto& layer : layersWithSameUid) {
865 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
866 continue;
867 }
868
869 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Rachel Leece6e0042023-06-27 11:22:54 -0700870 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
871 layer->vote != LayerVoteType::ExplicitExact &&
872 layer->vote != LayerVoteType::ExplicitCategory,
873 "Invalid layer vote type for frame rate overrides");
Ady Abraham8ca643a2022-10-18 18:26:47 -0700874 for (auto& [fps, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800875 constexpr bool isSeamlessSwitch = true;
Ady Abraham8ca643a2022-10-18 18:26:47 -0700876 const auto layerScore = calculateLayerScoreLocked(*layer, fps, isSeamlessSwitch);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800877 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -0800878 }
879 }
880
Ady Abraham62a0be22020-12-08 16:54:10 -0800881 // If we never scored any layers, we don't have a preferred frame rate
Ady Abraham8ca643a2022-10-18 18:26:47 -0700882 if (std::all_of(scoredFrameRates.begin(), scoredFrameRates.end(),
883 [](const auto& scoredFrameRate) {
884 const auto [_, score] = scoredFrameRate;
885 return score == 0;
886 })) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800887 continue;
888 }
889
ramindanid72ba162022-09-09 21:33:40 +0000890 // Now that we scored all the refresh rates we need to pick the lowest refresh rate
891 // that got the highest score.
Ady Abraham8ca643a2022-10-18 18:26:47 -0700892 const auto [overrideFps, _] =
893 *std::max_element(scoredFrameRates.begin(), scoredFrameRates.end(),
894 [](const auto& lhsPair, const auto& rhsPair) {
895 const float lhs = lhsPair.second;
896 const float rhs = rhsPair.second;
Ady Abraham68636062022-11-16 17:07:25 -0800897 return lhs < rhs && !ScoredFrameRate::scoresEqual(lhs, rhs);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700898 });
899 ALOGV("%s: overriding to %s for uid=%d", __func__, to_string(overrideFps).c_str(), uid);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700900 ATRACE_FORMAT_INSTANT("%s: overriding to %s for uid=%d", __func__,
901 to_string(overrideFps).c_str(), uid);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700902 frameRateOverrides.emplace(uid, overrideFps);
Ady Abraham62a0be22020-12-08 16:54:10 -0800903 }
904
905 return frameRateOverrides;
906}
907
Ady Abraham0aa373a2022-11-22 13:56:50 -0800908ftl::Optional<FrameRateMode> RefreshRateSelector::onKernelTimerChanged(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800909 std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800910 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100911
Ady Abraham0aa373a2022-11-22 13:56:50 -0800912 const auto current = [&]() REQUIRES(mLock) -> FrameRateMode {
913 if (desiredActiveModeId) {
914 const auto& modePtr = mDisplayModes.get(*desiredActiveModeId)->get();
915 return FrameRateMode{modePtr->getFps(), ftl::as_non_null(modePtr)};
916 }
917
918 return getActiveModeLocked();
919 }();
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100920
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800921 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
Ady Abraham0aa373a2022-11-22 13:56:50 -0800922 if (current.modePtr->getId() == min->getId()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800923 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100924 }
925
Ady Abraham0aa373a2022-11-22 13:56:50 -0800926 return timerExpired ? FrameRateMode{min->getFps(), ftl::as_non_null(min)} : current;
Steven Thomasf734df42020-04-13 21:09:28 -0700927}
928
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400929const DisplayModePtr& RefreshRateSelector::getMinRefreshRateByPolicyLocked() const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800930 const auto& activeMode = *getActiveModeLocked().modePtr;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700931
Ady Abraham68636062022-11-16 17:07:25 -0800932 for (const FrameRateMode& mode : mPrimaryFrameRates) {
933 if (activeMode.getGroup() == mode.modePtr->getGroup()) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800934 return mode.modePtr.get();
Marin Shalamanov46084422020-10-13 12:33:42 +0200935 }
936 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800937
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700938 ALOGE("Can't find min refresh rate by policy with the same mode group as the current mode %s",
939 to_string(activeMode).c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800940
941 // Default to the lowest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -0800942 return mPrimaryFrameRates.front().modePtr.get();
Ady Abraham2139f732019-11-13 18:56:40 -0800943}
944
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400945const DisplayModePtr& RefreshRateSelector::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800946 const ftl::NonNull<DisplayModePtr>* maxByAnchor = &mPrimaryFrameRates.back().modePtr;
947 const ftl::NonNull<DisplayModePtr>* max = &mPrimaryFrameRates.back().modePtr;
Ady Abraham68636062022-11-16 17:07:25 -0800948
949 bool maxByAnchorFound = false;
950 for (auto it = mPrimaryFrameRates.rbegin(); it != mPrimaryFrameRates.rend(); ++it) {
951 using namespace fps_approx_ops;
952 if (it->modePtr->getFps() > (*max)->getFps()) {
953 max = &it->modePtr;
Marin Shalamanov46084422020-10-13 12:33:42 +0200954 }
Ady Abraham68636062022-11-16 17:07:25 -0800955
956 if (anchorGroup == it->modePtr->getGroup() &&
957 it->modePtr->getFps() >= (*maxByAnchor)->getFps()) {
958 maxByAnchorFound = true;
959 maxByAnchor = &it->modePtr;
960 }
961 }
962
963 if (maxByAnchorFound) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800964 return maxByAnchor->get();
Marin Shalamanov46084422020-10-13 12:33:42 +0200965 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800966
ramindanid72ba162022-09-09 21:33:40 +0000967 ALOGE("Can't find max refresh rate by policy with the same group %d", anchorGroup);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800968
969 // Default to the highest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -0800970 return max->get();
Ady Abraham2139f732019-11-13 18:56:40 -0800971}
972
Ady Abraham68636062022-11-16 17:07:25 -0800973auto RefreshRateSelector::rankFrameRates(std::optional<int> anchorGroupOpt,
974 RefreshRateOrder refreshRateOrder,
975 std::optional<DisplayModeId> preferredDisplayModeOpt) const
976 -> FrameRateRanking {
Ady Abrahama5992df2023-01-27 21:10:57 -0800977 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -0800978 const char* const whence = __func__;
Ady Abrahama5992df2023-01-27 21:10:57 -0800979
980 // find the highest frame rate for each display mode
981 ftl::SmallMap<DisplayModeId, Fps, 8> maxRenderRateForMode;
982 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
983 if (ascending) {
984 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
985 // use a lower frame rate when we want Ascending frame rates.
986 for (const auto& frameRateMode : mPrimaryFrameRates) {
987 if (anchorGroupOpt && frameRateMode.modePtr->getGroup() != anchorGroupOpt) {
988 continue;
989 }
990
991 const auto [iter, _] = maxRenderRateForMode.try_emplace(frameRateMode.modePtr->getId(),
992 frameRateMode.fps);
993 if (iter->second < frameRateMode.fps) {
994 iter->second = frameRateMode.fps;
995 }
996 }
997 }
998
Ady Abraham68636062022-11-16 17:07:25 -0800999 std::deque<ScoredFrameRate> ranking;
1000 const auto rankFrameRate = [&](const FrameRateMode& frameRateMode) REQUIRES(mLock) {
1001 const auto& modePtr = frameRateMode.modePtr;
1002 if (anchorGroupOpt && modePtr->getGroup() != anchorGroupOpt) {
Ady Abraham37d46922022-10-05 13:08:51 -07001003 return;
ramindanid72ba162022-09-09 21:33:40 +00001004 }
Ady Abraham37d46922022-10-05 13:08:51 -07001005
Ady Abraham3f965922023-01-23 17:18:29 -08001006 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
ramindanif7075202023-03-10 00:24:34 +00001007 const auto id = modePtr->getId();
Ady Abrahama5992df2023-01-27 21:10:57 -08001008 if (ascending && frameRateMode.fps < *maxRenderRateForMode.get(id)) {
Ady Abraham3f965922023-01-23 17:18:29 -08001009 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1010 // use a lower frame rate when we want Ascending frame rates.
1011 return;
1012 }
1013
Ady Abraham68636062022-11-16 17:07:25 -08001014 float score = calculateDistanceScoreFromMax(frameRateMode.fps);
Ady Abraham3f965922023-01-23 17:18:29 -08001015
1016 if (ascending) {
Ady Abraham37d46922022-10-05 13:08:51 -07001017 score = 1.0f / score;
1018 }
ramindanif7075202023-03-10 00:24:34 +00001019
1020 constexpr float kScore = std::numeric_limits<float>::max();
Ady Abraham37d46922022-10-05 13:08:51 -07001021 if (preferredDisplayModeOpt) {
Ady Abraham68636062022-11-16 17:07:25 -08001022 if (*preferredDisplayModeOpt == modePtr->getId()) {
Ady Abraham68636062022-11-16 17:07:25 -08001023 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
Ady Abraham37d46922022-10-05 13:08:51 -07001024 return;
1025 }
1026 constexpr float kNonPreferredModePenalty = 0.95f;
1027 score *= kNonPreferredModePenalty;
ramindanif7075202023-03-10 00:24:34 +00001028 } else if (ascending && id == getMinRefreshRateByPolicyLocked()->getId()) {
1029 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround
1030 // and actually use a lower frame rate when we want Ascending frame rates.
1031 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
1032 return;
Ady Abraham37d46922022-10-05 13:08:51 -07001033 }
Ady Abraham3f965922023-01-23 17:18:29 -08001034
Ady Abraham68636062022-11-16 17:07:25 -08001035 ALOGV("%s(%s) %s (%s) scored %.2f", whence, ftl::enum_string(refreshRateOrder).c_str(),
1036 to_string(frameRateMode.fps).c_str(), to_string(modePtr->getFps()).c_str(), score);
1037 ranking.emplace_back(ScoredFrameRate{frameRateMode, score});
ramindanid72ba162022-09-09 21:33:40 +00001038 };
1039
1040 if (refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abraham68636062022-11-16 17:07:25 -08001041 std::for_each(mPrimaryFrameRates.begin(), mPrimaryFrameRates.end(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001042 } else {
Ady Abraham68636062022-11-16 17:07:25 -08001043 std::for_each(mPrimaryFrameRates.rbegin(), mPrimaryFrameRates.rend(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001044 }
1045
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001046 if (!ranking.empty() || !anchorGroupOpt) {
1047 return {ranking.begin(), ranking.end()};
ramindanid72ba162022-09-09 21:33:40 +00001048 }
1049
1050 ALOGW("Can't find %s refresh rate by policy with the same mode group"
1051 " as the mode group %d",
1052 refreshRateOrder == RefreshRateOrder::Ascending ? "min" : "max", anchorGroupOpt.value());
1053
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001054 constexpr std::optional<int> kNoAnchorGroup = std::nullopt;
Ady Abraham68636062022-11-16 17:07:25 -08001055 return rankFrameRates(kNoAnchorGroup, refreshRateOrder, preferredDisplayModeOpt);
ramindanid72ba162022-09-09 21:33:40 +00001056}
1057
Ady Abrahamace3d052022-11-17 16:25:05 -08001058FrameRateMode RefreshRateSelector::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -08001059 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001060 return getActiveModeLocked();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001061}
1062
Ady Abrahamace3d052022-11-17 16:25:05 -08001063const FrameRateMode& RefreshRateSelector::getActiveModeLocked() const {
1064 return *mActiveModeOpt;
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001065}
1066
Ady Abrahamace3d052022-11-17 16:25:05 -08001067void RefreshRateSelector::setActiveMode(DisplayModeId modeId, Fps renderFrameRate) {
Ady Abraham2139f732019-11-13 18:56:40 -08001068 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001069
Ady Abraham68636062022-11-16 17:07:25 -08001070 // Invalidate the cached invocation to getRankedFrameRates. This forces
1071 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1072 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001073
Ady Abrahamace3d052022-11-17 16:25:05 -08001074 const auto activeModeOpt = mDisplayModes.get(modeId);
1075 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1076
1077 mActiveModeOpt.emplace(FrameRateMode{renderFrameRate, ftl::as_non_null(activeModeOpt->get())});
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001078}
1079
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001080RefreshRateSelector::RefreshRateSelector(DisplayModes modes, DisplayModeId activeModeId,
1081 Config config)
rnlee3bd610662021-06-23 16:27:57 -07001082 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001083 initializeIdleTimer();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001084 FTL_FAKE_GUARD(kMainThreadContext, updateDisplayModes(std::move(modes), activeModeId));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001085}
1086
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001087void RefreshRateSelector::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +00001088 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001089 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +00001090 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001091 [this] {
1092 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1093 if (const auto callbacks = getIdleTimerCallbacks()) {
1094 callbacks->onReset();
1095 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001096 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001097 [this] {
1098 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1099 if (const auto callbacks = getIdleTimerCallbacks()) {
1100 callbacks->onExpired();
1101 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001102 });
Ady Abraham9a2ea342021-09-03 17:32:34 -07001103 }
1104}
1105
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001106void RefreshRateSelector::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001107 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001108
Ady Abraham68636062022-11-16 17:07:25 -08001109 // Invalidate the cached invocation to getRankedFrameRates. This forces
1110 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1111 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001112
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001113 mDisplayModes = std::move(modes);
Ady Abrahamace3d052022-11-17 16:25:05 -08001114 const auto activeModeOpt = mDisplayModes.get(activeModeId);
1115 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1116 mActiveModeOpt =
1117 FrameRateMode{activeModeOpt->get()->getFps(), ftl::as_non_null(activeModeOpt->get())};
Ady Abrahamabc27602020-04-08 17:20:29 -07001118
Ady Abraham68636062022-11-16 17:07:25 -08001119 const auto sortedModes = sortByRefreshRate(mDisplayModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001120 mMinRefreshRateModeIt = sortedModes.front();
1121 mMaxRefreshRateModeIt = sortedModes.back();
1122
Marin Shalamanov75f37252021-02-10 21:43:57 +01001123 // Reset the policy because the old one may no longer be valid.
1124 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001125 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -08001126
Ady Abraham8ca643a2022-10-18 18:26:47 -07001127 mFrameRateOverrideConfig = [&] {
1128 switch (mConfig.enableFrameRateOverride) {
1129 case Config::FrameRateOverride::Disabled:
Ady Abraham68636062022-11-16 17:07:25 -08001130 case Config::FrameRateOverride::AppOverride:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001131 case Config::FrameRateOverride::Enabled:
1132 return mConfig.enableFrameRateOverride;
Ady Abraham68636062022-11-16 17:07:25 -08001133 case Config::FrameRateOverride::AppOverrideNativeRefreshRates:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001134 return shouldEnableFrameRateOverride(sortedModes)
Ady Abraham68636062022-11-16 17:07:25 -08001135 ? Config::FrameRateOverride::AppOverrideNativeRefreshRates
Ady Abraham8ca643a2022-10-18 18:26:47 -07001136 : Config::FrameRateOverride::Disabled;
1137 }
1138 }();
Ady Abraham4899ff82021-01-06 13:53:29 -08001139
Ady Abraham68636062022-11-16 17:07:25 -08001140 if (mConfig.enableFrameRateOverride ==
1141 Config::FrameRateOverride::AppOverrideNativeRefreshRates) {
1142 for (const auto& [_, mode] : mDisplayModes) {
1143 mAppOverrideNativeRefreshRates.try_emplace(mode->getFps(), ftl::unit);
1144 }
1145 }
1146
Ady Abrahamabc27602020-04-08 17:20:29 -07001147 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001148}
1149
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001150bool RefreshRateSelector::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001151 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001152 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
Ady Abraham285f8c12022-10-11 17:12:14 -07001153 if (!policy.primaryRanges.physical.includes(mode->get()->getFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001154 ALOGE("Default mode is not in the primary range.");
1155 return false;
1156 }
1157 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001158 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -07001159 return false;
1160 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001161
Ady Abraham68636062022-11-16 17:07:25 -08001162 const auto& primaryRanges = policy.primaryRanges;
1163 const auto& appRequestRanges = policy.appRequestRanges;
1164 ALOGE_IF(!appRequestRanges.physical.includes(primaryRanges.physical),
Ady Abraham08048ce2022-11-30 18:08:00 -08001165 "Physical range is invalid: primary: %s appRequest: %s",
1166 to_string(primaryRanges.physical).c_str(),
1167 to_string(appRequestRanges.physical).c_str());
1168 ALOGE_IF(!appRequestRanges.render.includes(primaryRanges.render),
1169 "Render range is invalid: primary: %s appRequest: %s",
1170 to_string(primaryRanges.render).c_str(), to_string(appRequestRanges.render).c_str());
Ady Abraham68636062022-11-16 17:07:25 -08001171
1172 return primaryRanges.valid() && appRequestRanges.valid();
Steven Thomasd4071902020-03-24 16:02:53 -07001173}
1174
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001175auto RefreshRateSelector::setPolicy(const PolicyVariant& policy) -> SetPolicyResult {
Dominik Laskowski36dced82022-09-02 09:24:00 -07001176 Policy oldPolicy;
Ady Abrahamace3d052022-11-17 16:25:05 -08001177 PhysicalDisplayId displayId;
Dominik Laskowski36dced82022-09-02 09:24:00 -07001178 {
1179 std::lock_guard lock(mLock);
1180 oldPolicy = *getCurrentPolicyLocked();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001181
Dominik Laskowski36dced82022-09-02 09:24:00 -07001182 const bool valid = ftl::match(
1183 policy,
1184 [this](const auto& policy) {
1185 ftl::FakeGuard guard(mLock);
1186 if (!isPolicyValidLocked(policy)) {
1187 ALOGE("Invalid policy: %s", policy.toString().c_str());
1188 return false;
1189 }
1190
1191 using T = std::decay_t<decltype(policy)>;
1192
1193 if constexpr (std::is_same_v<T, DisplayManagerPolicy>) {
1194 mDisplayManagerPolicy = policy;
1195 } else {
1196 static_assert(std::is_same_v<T, OverridePolicy>);
1197 mOverridePolicy = policy;
1198 }
1199 return true;
1200 },
1201 [this](NoOverridePolicy) {
1202 ftl::FakeGuard guard(mLock);
1203 mOverridePolicy.reset();
1204 return true;
1205 });
1206
1207 if (!valid) {
1208 return SetPolicyResult::Invalid;
1209 }
1210
Ady Abraham68636062022-11-16 17:07:25 -08001211 mGetRankedFrameRatesCache.reset();
Dominik Laskowski36dced82022-09-02 09:24:00 -07001212
1213 if (*getCurrentPolicyLocked() == oldPolicy) {
1214 return SetPolicyResult::Unchanged;
1215 }
1216 constructAvailableRefreshRates();
Ady Abrahamace3d052022-11-17 16:25:05 -08001217
1218 displayId = getActiveModeLocked().modePtr->getPhysicalDisplayId();
Steven Thomasd4071902020-03-24 16:02:53 -07001219 }
Dominik Laskowski36dced82022-09-02 09:24:00 -07001220
Dominik Laskowski36dced82022-09-02 09:24:00 -07001221 const unsigned numModeChanges = std::exchange(mNumModeSwitchesInPolicy, 0u);
1222
1223 ALOGI("Display %s policy changed\n"
1224 "Previous: %s\n"
1225 "Current: %s\n"
1226 "%u mode changes were performed under the previous policy",
1227 to_string(displayId).c_str(), oldPolicy.toString().c_str(), toString(policy).c_str(),
1228 numModeChanges);
1229
1230 return SetPolicyResult::Changed;
Steven Thomasd4071902020-03-24 16:02:53 -07001231}
1232
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001233auto RefreshRateSelector::getCurrentPolicyLocked() const -> const Policy* {
Steven Thomasd4071902020-03-24 16:02:53 -07001234 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
1235}
1236
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001237auto RefreshRateSelector::getCurrentPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001238 std::lock_guard lock(mLock);
1239 return *getCurrentPolicyLocked();
1240}
1241
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001242auto RefreshRateSelector::getDisplayManagerPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001243 std::lock_guard lock(mLock);
1244 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001245}
1246
Ady Abrahamace3d052022-11-17 16:25:05 -08001247bool RefreshRateSelector::isModeAllowed(const FrameRateMode& mode) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001248 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001249 return std::find(mAppRequestFrameRates.begin(), mAppRequestFrameRates.end(), mode) !=
1250 mAppRequestFrameRates.end();
Ady Abraham2139f732019-11-13 18:56:40 -08001251}
1252
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001253void RefreshRateSelector::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001254 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -07001255 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001256 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -07001257
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001258 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -08001259
Ady Abraham68636062022-11-16 17:07:25 -08001260 const auto filterRefreshRates = [&](const FpsRanges& ranges,
1261 const char* rangeName) REQUIRES(mLock) {
1262 const auto filterModes = [&](const DisplayMode& mode) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001263 return mode.getResolution() == defaultMode->getResolution() &&
1264 mode.getDpi() == defaultMode->getDpi() &&
1265 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
Ady Abraham68636062022-11-16 17:07:25 -08001266 ranges.physical.includes(mode.getFps()) &&
1267 (supportsFrameRateOverride() || ranges.render.includes(mode.getFps()));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001268 };
Ady Abraham8a82ba62020-01-17 12:43:17 -08001269
Ady Abraham41bf7c62023-07-20 10:33:06 -07001270 auto frameRateModes = createFrameRateModes(filterModes, ranges.render);
1271 if (frameRateModes.empty()) {
1272 ALOGW("No matching frame rate modes for %s range. policy: %s", rangeName,
1273 policy->toString().c_str());
1274 // TODO(b/292105422): Ideally DisplayManager should not send render ranges smaller than
1275 // the min supported. See b/292047939.
1276 // For not we just ignore the render ranges.
1277 frameRateModes = createFrameRateModes(filterModes, {});
1278 }
Ady Abraham68636062022-11-16 17:07:25 -08001279 LOG_ALWAYS_FATAL_IF(frameRateModes.empty(),
Ady Abraham41bf7c62023-07-20 10:33:06 -07001280 "No matching frame rate modes for %s range even after ignoring the "
1281 "render range. policy: %s",
1282 rangeName, policy->toString().c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -08001283
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001284 const auto stringifyModes = [&] {
1285 std::string str;
Ady Abraham68636062022-11-16 17:07:25 -08001286 for (const auto& frameRateMode : frameRateModes) {
1287 str += to_string(frameRateMode) + " ";
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001288 }
1289 return str;
1290 };
Ady Abraham68636062022-11-16 17:07:25 -08001291 ALOGV("%s render rates: %s", rangeName, stringifyModes().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -07001292
Ady Abraham68636062022-11-16 17:07:25 -08001293 return frameRateModes;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001294 };
1295
Ady Abraham68636062022-11-16 17:07:25 -08001296 mPrimaryFrameRates = filterRefreshRates(policy->primaryRanges, "primary");
1297 mAppRequestFrameRates = filterRefreshRates(policy->appRequestRanges, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -08001298}
1299
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001300Fps RefreshRateSelector::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001301 using namespace fps_approx_ops;
1302
1303 if (frameRate <= mKnownFrameRates.front()) {
1304 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001305 }
1306
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001307 if (frameRate >= mKnownFrameRates.back()) {
1308 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001309 }
1310
Marin Shalamanove8a663d2020-11-24 17:48:00 +01001311 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001312 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001313
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001314 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
1315 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001316 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
1317}
1318
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001319auto RefreshRateSelector::getIdleTimerAction() const -> KernelIdleTimerAction {
Ana Krulecb9afd792020-06-11 13:16:15 -07001320 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001321
1322 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getFps();
1323 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -07001324
1325 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
1326 // the min allowed refresh rate is higher than the device min, we do not want to enable the
1327 // timer.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001328 if (isStrictlyLess(deviceMinFps, minByPolicy->getFps())) {
1329 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001330 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001331
ramindanid72ba162022-09-09 21:33:40 +00001332 const DisplayModePtr& maxByPolicy =
Ady Abrahamace3d052022-11-17 16:25:05 -08001333 getMaxRefreshRateByPolicyLocked(getActiveModeLocked().modePtr->getGroup());
Ana Krulecb9afd792020-06-11 13:16:15 -07001334 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001335 // Turn on the timer when the min of the primary range is below the device min.
1336 if (const Policy* currentPolicy = getCurrentPolicyLocked();
Ady Abraham285f8c12022-10-11 17:12:14 -07001337 isApproxLess(currentPolicy->primaryRanges.physical.min, deviceMinFps)) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001338 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001339 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001340 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001341 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001342
Ana Krulecb9afd792020-06-11 13:16:15 -07001343 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001344 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001345}
1346
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001347int RefreshRateSelector::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -07001348 // This calculation needs to be in sync with the java code
1349 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001350
1351 // The threshold must be smaller than 0.001 in order to differentiate
1352 // between the fractional pairs (e.g. 59.94 and 60).
1353 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001354 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -07001355 const auto numPeriodsRounded = std::round(numPeriods);
1356 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001357 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -07001358 }
1359
Ady Abraham62f216c2020-10-13 19:07:23 -07001360 return static_cast<int>(numPeriodsRounded);
1361}
1362
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001363bool RefreshRateSelector::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001364 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001365 return isFractionalPairOrMultiple(bigger, smaller);
1366 }
1367
1368 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
1369 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001370 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
1371 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001372}
1373
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001374void RefreshRateSelector::dump(utils::Dumper& dumper) const {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001375 using namespace std::string_view_literals;
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001376
Marin Shalamanovba421a82020-11-10 21:49:26 +01001377 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +01001378
Ady Abrahamace3d052022-11-17 16:25:05 -08001379 const auto activeMode = getActiveModeLocked();
1380 dumper.dump("activeMode"sv, to_string(activeMode));
Marin Shalamanovba421a82020-11-10 21:49:26 +01001381
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001382 dumper.dump("displayModes"sv);
1383 {
1384 utils::Dumper::Indent indent(dumper);
1385 for (const auto& [id, mode] : mDisplayModes) {
1386 dumper.dump({}, to_string(*mode));
1387 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001388 }
1389
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001390 dumper.dump("displayManagerPolicy"sv, mDisplayManagerPolicy.toString());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001391
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001392 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
1393 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001394 dumper.dump("overridePolicy"sv, currentPolicy.toString());
ramindani32cf0602022-03-02 02:30:29 +00001395 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001396
Ady Abraham8ca643a2022-10-18 18:26:47 -07001397 dumper.dump("frameRateOverrideConfig"sv, *ftl::enum_name(mFrameRateOverrideConfig));
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001398
Dominik Laskowski03cfce82022-11-02 12:13:29 -04001399 dumper.dump("idleTimer"sv);
1400 {
1401 utils::Dumper::Indent indent(dumper);
1402 dumper.dump("interval"sv, mIdleTimer.transform(&OneShotTimer::interval));
1403 dumper.dump("controller"sv,
1404 mConfig.kernelIdleTimerController
1405 .and_then(&ftl::enum_name<KernelIdleTimerController>)
1406 .value_or("Platform"sv));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001407 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001408}
1409
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001410std::chrono::milliseconds RefreshRateSelector::getIdleTimerTimeout() {
ramindani32cf0602022-03-02 02:30:29 +00001411 return mConfig.idleTimerTimeout;
1412}
1413
Rachel Leece6e0042023-06-27 11:22:54 -07001414// TODO(b/293651105): Extract category FpsRange mapping to OEM-configurable config.
1415FpsRange RefreshRateSelector::getFrameRateCategoryRange(FrameRateCategory category) {
1416 switch (category) {
1417 case FrameRateCategory::High:
1418 return FpsRange{90_Hz, 120_Hz};
1419 case FrameRateCategory::Normal:
1420 return FpsRange{60_Hz, 90_Hz};
1421 case FrameRateCategory::Low:
1422 return FpsRange{30_Hz, 60_Hz};
1423 case FrameRateCategory::NoPreference:
1424 case FrameRateCategory::Default:
1425 LOG_ALWAYS_FATAL("Should not get fps range for frame rate category: %s",
1426 ftl::enum_string(category).c_str());
1427 return FpsRange{0_Hz, 0_Hz};
1428 default:
1429 LOG_ALWAYS_FATAL("Invalid frame rate category for range: %s",
1430 ftl::enum_string(category).c_str());
1431 return FpsRange{0_Hz, 0_Hz};
1432 }
1433}
1434
Ady Abraham2139f732019-11-13 18:56:40 -08001435} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001436
1437// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001438#pragma clang diagnostic pop // ignored "-Wextra"