blob: 39850c7e1ea11098989a9a2f1491c2ac41843e84 [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>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070027
28#include <android-base/properties.h>
29#include <android-base/stringprintf.h>
30#include <ftl/enum.h>
Dominik Laskowskif8734e02022-08-26 09:06:59 -070031#include <ftl/fake_guard.h>
Dominik Laskowski36dced82022-09-02 09:24:00 -070032#include <ftl/match.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070033#include <utils/Trace.h>
34
Ady Abraham4899ff82021-01-06 13:53:29 -080035#include "../SurfaceFlingerProperties.h"
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070036#include "RefreshRateConfigs.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080037
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080038#undef LOG_TAG
39#define LOG_TAG "RefreshRateConfigs"
40
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080041namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010042namespace {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070043
Dominik Laskowskib0054a22022-03-03 09:03:06 -080044struct RefreshRateScore {
45 DisplayModeIterator modeIt;
Ady Abrahamae2e3c72022-08-13 05:12:13 +000046 float overallScore;
47 struct {
Ady Abraham62f51d92022-08-24 22:20:22 +000048 float modeBelowThreshold;
49 float modeAboveThreshold;
50 } fixedRateBelowThresholdLayersScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -080051};
52
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080053constexpr RefreshRateConfigs::GlobalSignals kNoSignals;
54
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010055std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080056 return base::StringPrintf("%s (type=%s, weight=%.2f, seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070057 ftl::enum_string(layer.vote).c_str(), weight,
58 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010059 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010060}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010061
Marin Shalamanova7fe3042021-01-29 21:02:08 +010062std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070063 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010064 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010065
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070066 // Add all supported refresh rates.
Dominik Laskowskib0054a22022-03-03 09:03:06 -080067 for (const auto& [id, mode] : modes) {
68 knownFrameRates.push_back(mode->getFps());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010069 }
70
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070071 // Sort and remove duplicates.
72 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010073 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070074 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010075 knownFrameRates.end());
76 return knownFrameRates;
77}
78
Dominik Laskowskib0054a22022-03-03 09:03:06 -080079// The Filter is a `bool(const DisplayMode&)` predicate.
80template <typename Filter>
81std::vector<DisplayModeIterator> sortByRefreshRate(const DisplayModes& modes, Filter&& filter) {
82 std::vector<DisplayModeIterator> sortedModes;
83 sortedModes.reserve(modes.size());
Ady Abraham2139f732019-11-13 18:56:40 -080084
Dominik Laskowskib0054a22022-03-03 09:03:06 -080085 for (auto it = modes.begin(); it != modes.end(); ++it) {
86 const auto& [id, mode] = *it;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080087
Dominik Laskowskib0054a22022-03-03 09:03:06 -080088 if (filter(*mode)) {
89 ALOGV("%s: including mode %d", __func__, id.value());
90 sortedModes.push_back(it);
91 }
92 }
93
94 std::sort(sortedModes.begin(), sortedModes.end(), [](auto it1, auto it2) {
95 const auto& mode1 = it1->second;
96 const auto& mode2 = it2->second;
97
98 if (mode1->getVsyncPeriod() == mode2->getVsyncPeriod()) {
99 return mode1->getGroup() > mode2->getGroup();
100 }
101
102 return mode1->getVsyncPeriod() > mode2->getVsyncPeriod();
103 });
104
105 return sortedModes;
Marin Shalamanov46084422020-10-13 12:33:42 +0200106}
107
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800108bool canModesSupportFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
109 for (const auto it1 : sortedModes) {
110 const auto& mode1 = it1->second;
111 for (const auto it2 : sortedModes) {
112 const auto& mode2 = it2->second;
113
114 if (RefreshRateConfigs::getFrameRateDivisor(mode1->getFps(), mode2->getFps()) >= 2) {
115 return true;
116 }
117 }
118 }
119 return false;
120}
121
Dominik Laskowski36dced82022-09-02 09:24:00 -0700122std::string toString(const RefreshRateConfigs::PolicyVariant& policy) {
123 using namespace std::string_literals;
124
125 return ftl::match(
126 policy,
127 [](const RefreshRateConfigs::DisplayManagerPolicy& policy) {
128 return "DisplayManagerPolicy"s + policy.toString();
129 },
130 [](const RefreshRateConfigs::OverridePolicy& policy) {
131 return "OverridePolicy"s + policy.toString();
132 },
133 [](RefreshRateConfigs::NoOverridePolicy) { return "NoOverridePolicy"s; });
134}
135
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800136} // namespace
137
ramindanid72ba162022-09-09 21:33:40 +0000138struct RefreshRateConfigs::RefreshRateScoreComparator {
139 bool operator()(const RefreshRateScore& lhs, const RefreshRateScore& rhs) const {
140 const auto& [modeIt, overallScore, _] = lhs;
141
142 std::string name = to_string(modeIt->second->getFps());
143 ALOGV("%s sorting scores %.2f", name.c_str(), overallScore);
144
145 ATRACE_INT(name.c_str(), static_cast<int>(std::round(overallScore * 100)));
146
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400147 if (!ScoredRefreshRate::scoresEqual(overallScore, rhs.overallScore)) {
ramindanid72ba162022-09-09 21:33:40 +0000148 return overallScore > rhs.overallScore;
149 }
150
151 // If overallScore tie we will pick the higher refresh rate if
152 // high refresh rate is the priority else the lower refresh rate.
153 if (refreshRateOrder == RefreshRateOrder::Descending) {
154 using fps_approx_ops::operator>;
155 return modeIt->second->getFps() > rhs.modeIt->second->getFps();
156 } else {
157 using fps_approx_ops::operator<;
158 return modeIt->second->getFps() < rhs.modeIt->second->getFps();
159 }
160 }
161
162 const RefreshRateOrder refreshRateOrder;
163};
164
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100165std::string RefreshRateConfigs::Policy::toString() const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700166 return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
167 ", primaryRange=%s, appRequestRange=%s}",
168 defaultMode.value(), allowGroupSwitching ? "true" : "false",
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800169 to_string(primaryRange).c_str(), to_string(appRequestRange).c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200170}
171
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800172std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
173 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800174 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
175 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
176 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
177 quotient++;
178 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800179 }
180
Ady Abraham62a0be22020-12-08 16:54:10 -0800181 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800182}
183
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800184float RefreshRateConfigs::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
185 Fps refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200186 constexpr float kScoreForFractionalPairs = .8f;
187
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800188 const auto displayPeriod = refreshRate.getPeriodNsecs();
Ady Abraham62a0be22020-12-08 16:54:10 -0800189 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
190 if (layer.vote == LayerVoteType::ExplicitDefault) {
191 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200192 // that layerPeriod is the minimal period to render a frame.
193 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
194 // then the actualLayerPeriod will be 32ms, because it is the
195 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800196 auto actualLayerPeriod = displayPeriod;
197 int multiplier = 1;
198 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
199 multiplier++;
200 actualLayerPeriod = displayPeriod * multiplier;
201 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200202
203 // Because of the threshold we used above it's possible that score is slightly
204 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800205 return std::min(1.0f,
206 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
207 }
208
209 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
210 layer.vote == LayerVoteType::Heuristic) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800211 if (isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700212 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200213 }
214
Ady Abraham62a0be22020-12-08 16:54:10 -0800215 // Calculate how many display vsyncs we need to present a single frame for this
216 // layer
217 const auto [displayFramesQuotient, displayFramesRemainder] =
218 getDisplayFrames(layerPeriod, displayPeriod);
219 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
220 if (displayFramesRemainder == 0) {
221 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700222 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800223 }
224
225 if (displayFramesQuotient == 0) {
226 // Layer desired refresh rate is higher than the display rate.
227 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
228 (1.0f / (MAX_FRAMES_TO_FIT + 1));
229 }
230
231 // Layer desired refresh rate is lower than the display rate. Check how well it fits
232 // the cadence.
233 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
234 int iter = 2;
235 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
236 diff = diff - (displayPeriod - diff);
237 iter++;
238 }
239
Ady Abraham05243be2021-09-16 15:58:52 -0700240 return (1.0f / iter);
241 }
242
243 return 0;
244}
245
ramindanid72ba162022-09-09 21:33:40 +0000246float RefreshRateConfigs::calculateRefreshRateScoreForFps(Fps refreshRate) const {
247 const float ratio =
248 refreshRate.getValue() / mAppRequestRefreshRates.back()->second->getFps().getValue();
249 // Use ratio^2 to get a lower score the more we get further from peak
250 return ratio * ratio;
251}
252
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800253float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
Ady Abraham05243be2021-09-16 15:58:52 -0700254 bool isSeamlessSwitch) const {
Ady Abraham05243be2021-09-16 15:58:52 -0700255 // Slightly prefer seamless switches.
256 constexpr float kSeamedSwitchPenalty = 0.95f;
257 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
258
259 // If the layer wants Max, give higher score to the higher refresh rate
260 if (layer.vote == LayerVoteType::Max) {
ramindanid72ba162022-09-09 21:33:40 +0000261 return calculateRefreshRateScoreForFps(refreshRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800262 }
263
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800264 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800265 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800266 if (mSupportsFrameRateOverrideByContent) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800267 // Since we support frame rate override, allow refresh rates which are
268 // multiples of the layer's request, as those apps would be throttled
269 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800270 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800271 }
272
Ady Abrahamcc315492022-02-17 17:06:39 -0800273 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800274 }
275
Ady Abrahamcc315492022-02-17 17:06:39 -0800276 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700277 // the highest score.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800278 if (getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700279 return 1.0f * seamlessness;
280 }
281
Ady Abrahamcc315492022-02-17 17:06:39 -0800282 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700283 // there is a small penalty attached to the score to favor the frame rates
284 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800285 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700286 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
287 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800288}
289
ramindanid72ba162022-09-09 21:33:40 +0000290auto RefreshRateConfigs::getRankedRefreshRates(const std::vector<LayerRequirement>& layers,
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400291 GlobalSignals signals) const -> RankedRefreshRates {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200292 std::lock_guard lock(mLock);
293
ramindanid72ba162022-09-09 21:33:40 +0000294 if (mGetRankedRefreshRatesCache &&
295 mGetRankedRefreshRatesCache->arguments == std::make_pair(layers, signals)) {
296 return mGetRankedRefreshRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200297 }
298
ramindanid72ba162022-09-09 21:33:40 +0000299 const auto result = getRankedRefreshRatesLocked(layers, signals);
300 mGetRankedRefreshRatesCache = GetRankedRefreshRatesCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200301 return result;
302}
303
ramindanid72ba162022-09-09 21:33:40 +0000304auto RefreshRateConfigs::getRankedRefreshRatesLocked(const std::vector<LayerRequirement>& layers,
305 GlobalSignals signals) const
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400306 -> RankedRefreshRates {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000307 using namespace fps_approx_ops;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800308 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800309 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700310
ramindani38c84982022-08-29 18:02:57 +0000311 const auto& activeMode = *getActiveModeItLocked()->second;
312
313 // Keep the display at max refresh rate for the duration of powering on the display.
314 if (signals.powerOnImminent) {
315 ALOGV("Power On Imminent");
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400316 return {rankRefreshRates(activeMode.getGroup(), RefreshRateOrder::Descending),
ramindanid72ba162022-09-09 21:33:40 +0000317 GlobalSignals{.powerOnImminent = true}};
ramindani38c84982022-08-29 18:02:57 +0000318 }
319
Ady Abraham8a82ba62020-01-17 12:43:17 -0800320 int noVoteLayers = 0;
321 int minVoteLayers = 0;
322 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800323 int explicitDefaultVoteLayers = 0;
324 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800325 int explicitExact = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100326 int seamedFocusedLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800327
Ady Abraham8a82ba62020-01-17 12:43:17 -0800328 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800329 switch (layer.vote) {
330 case LayerVoteType::NoVote:
331 noVoteLayers++;
332 break;
333 case LayerVoteType::Min:
334 minVoteLayers++;
335 break;
336 case LayerVoteType::Max:
337 maxVoteLayers++;
338 break;
339 case LayerVoteType::ExplicitDefault:
340 explicitDefaultVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800341 break;
342 case LayerVoteType::ExplicitExactOrMultiple:
343 explicitExactOrMultipleVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800344 break;
345 case LayerVoteType::ExplicitExact:
346 explicitExact++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800347 break;
348 case LayerVoteType::Heuristic:
349 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800350 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200351
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100352 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
353 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200354 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800355 }
356
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800357 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
358 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700359
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200360 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800361 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700362
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200363 // If the default mode group is different from the group of current mode,
364 // this means a layer requesting a seamed mode switch just disappeared and
365 // we should switch back to the default group.
366 // However if a seamed layer is still present we anchor around the group
367 // of the current mode, in order to prevent unnecessary seamed mode switches
368 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800369 const auto anchorGroup =
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700370 seamedFocusedLayers > 0 ? activeMode.getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200371
Steven Thomasf734df42020-04-13 21:09:28 -0700372 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
373 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800374 if (signals.touch && !hasExplicitVoteLayers) {
ramindanid72ba162022-09-09 21:33:40 +0000375 ALOGV("Touch Boost");
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400376 return {rankRefreshRates(anchorGroup, RefreshRateOrder::Descending),
ramindanid72ba162022-09-09 21:33:40 +0000377 GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800378 }
379
Alec Mouri11232a22020-05-14 18:06:25 -0700380 // If the primary range consists of a single refresh rate then we can only
381 // move out the of range if layers explicitly request a different refresh
382 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100383 const bool primaryRangeIsSingleRate =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700384 isApproxEqual(policy->primaryRange.min, policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700385
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800386 if (!signals.touch && signals.idle && !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
ramindanid72ba162022-09-09 21:33:40 +0000387 ALOGV("Idle");
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400388 return {rankRefreshRates(activeMode.getGroup(), RefreshRateOrder::Ascending),
ramindanid72ba162022-09-09 21:33:40 +0000389 GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700390 }
391
Steven Thomasdebafed2020-05-18 17:30:35 -0700392 if (layers.empty() || noVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000393 ALOGV("No layers with votes");
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400394 return {rankRefreshRates(anchorGroup, RefreshRateOrder::Descending), kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700395 }
396
Ady Abraham8a82ba62020-01-17 12:43:17 -0800397 // Only if all layers want Min we should return Min
398 if (noVoteLayers + minVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000399 ALOGV("All layers Min");
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400400 return {rankRefreshRates(activeMode.getGroup(), RefreshRateOrder::Ascending), kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800401 }
402
Ady Abraham8a82ba62020-01-17 12:43:17 -0800403 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800404 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700405 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800406
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800407 for (const DisplayModeIterator modeIt : mAppRequestRefreshRates) {
408 scores.emplace_back(RefreshRateScore{modeIt, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800409 }
410
411 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700412 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700413 ftl::enum_string(layer.vote).c_str(), layer.weight,
rnlee3bd610662021-06-23 16:27:57 -0700414 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800415 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800416 continue;
417 }
418
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800419 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800420
Ady Abraham62f51d92022-08-24 22:20:22 +0000421 for (auto& [modeIt, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800422 const auto& [id, mode] = *modeIt;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700423 const bool isSeamlessSwitch = mode->getGroup() == activeMode.getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200424
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100425 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100426 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800427 formatLayerInfo(layer, weight).c_str(), to_string(*mode).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700428 to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200429 continue;
430 }
431
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100432 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
433 !layer.focused) {
434 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100435 " Current mode = %s",
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800436 formatLayerInfo(layer, weight).c_str(), to_string(*mode).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700437 to_string(activeMode).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100438 continue;
439 }
440
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100441 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100442 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100443 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100444 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
445 // disappeared.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800446 const bool isInPolicyForDefault = mode->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100447 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100448 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700449 to_string(*mode).c_str(), to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200450 continue;
451 }
452
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800453 const bool inPrimaryRange = policy->primaryRange.includes(mode->getFps());
Alec Mouri11232a22020-05-14 18:06:25 -0700454 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800455 !(layer.focused &&
456 (layer.vote == LayerVoteType::ExplicitDefault ||
457 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700458 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700459 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700460 continue;
461 }
462
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000463 const float layerScore =
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800464 calculateLayerScoreLocked(layer, mode->getFps(), isSeamlessSwitch);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000465 const float weightedLayerScore = weight * layerScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800466
Ady Abraham13cfb362022-08-13 05:12:13 +0000467 // Layer with fixed source has a special consideration which depends on the
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000468 // mConfig.frameRateMultipleThreshold. We don't want these layers to score
469 // refresh rates above the threshold, but we also don't want to favor the lower
470 // ones by having a greater number of layers scoring them. Instead, we calculate
471 // the score independently for these layers and later decide which
472 // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
473 // score 120 Hz, but desired 60 fps should contribute to the score.
474 const bool fixedSourceLayer = [](LayerVoteType vote) {
475 switch (vote) {
476 case LayerVoteType::ExplicitExactOrMultiple:
477 case LayerVoteType::Heuristic:
478 return true;
479 case LayerVoteType::NoVote:
480 case LayerVoteType::Min:
481 case LayerVoteType::Max:
482 case LayerVoteType::ExplicitDefault:
483 case LayerVoteType::ExplicitExact:
484 return false;
485 }
486 }(layer.vote);
Ady Abraham62f51d92022-08-24 22:20:22 +0000487 const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000488 layer.desiredRefreshRate <
489 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
Ady Abraham62f51d92022-08-24 22:20:22 +0000490 if (fixedSourceLayer && layerBelowThreshold) {
Ady Abraham13cfb362022-08-13 05:12:13 +0000491 const bool modeAboveThreshold =
492 mode->getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
Ady Abraham62f51d92022-08-24 22:20:22 +0000493 if (modeAboveThreshold) {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000494 ALOGV("%s gives %s fixed source (above threshold) score of %.4f",
495 formatLayerInfo(layer, weight).c_str(), to_string(mode->getFps()).c_str(),
496 layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000497 fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000498 } else {
499 ALOGV("%s gives %s fixed source (below threshold) score of %.4f",
500 formatLayerInfo(layer, weight).c_str(), to_string(mode->getFps()).c_str(),
501 layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000502 fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000503 }
504 } else {
505 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
506 to_string(mode->getFps()).c_str(), layerScore);
507 overallScore += weightedLayerScore;
508 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800509 }
510 }
511
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000512 // We want to find the best refresh rate without the fixed source layers,
Ady Abraham62f51d92022-08-24 22:20:22 +0000513 // so we could know whether we should add the modeAboveThreshold scores or not.
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000514 // If the best refresh rate is already above the threshold, it means that
515 // some non-fixed source layers already scored it, so we can just add the score
516 // for all fixed source layers, even the ones that are above the threshold.
517 const bool maxScoreAboveThreshold = [&] {
518 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
519 return false;
520 }
521
522 const auto maxScoreIt =
523 std::max_element(scores.begin(), scores.end(),
524 [](RefreshRateScore max, RefreshRateScore current) {
525 const auto& [modeIt, overallScore, _] = current;
526 return overallScore > max.overallScore;
527 });
528 ALOGV("%s is the best refresh rate without fixed source layers. It is %s the threshold for "
529 "refresh rate multiples",
530 to_string(maxScoreIt->modeIt->second->getFps()).c_str(),
531 maxScoreAboveThreshold ? "above" : "below");
532 return maxScoreIt->modeIt->second->getFps() >=
533 Fps::fromValue(mConfig.frameRateMultipleThreshold);
534 }();
535
536 // Now we can add the fixed rate layers score
Ady Abraham62f51d92022-08-24 22:20:22 +0000537 for (auto& [modeIt, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
538 overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000539 if (maxScoreAboveThreshold) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000540 overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000541 }
542 ALOGV("%s adjusted overallScore is %.4f", to_string(modeIt->second->getFps()).c_str(),
543 overallScore);
544 }
545
546 // Now that we scored all the refresh rates we need to pick the one that got the highest
ramindanid72ba162022-09-09 21:33:40 +0000547 // overallScore. Sort the scores based on their overallScore in descending order of priority.
548 const RefreshRateOrder refreshRateOrder =
549 maxVoteLayers > 0 ? RefreshRateOrder::Descending : RefreshRateOrder::Ascending;
550 std::sort(scores.begin(), scores.end(),
551 RefreshRateScoreComparator{.refreshRateOrder = refreshRateOrder});
ramindanid72ba162022-09-09 21:33:40 +0000552
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400553 RefreshRateRanking ranking;
554 ranking.reserve(scores.size());
555
556 std::transform(scores.begin(), scores.end(), back_inserter(ranking),
ramindanid72ba162022-09-09 21:33:40 +0000557 [](const RefreshRateScore& score) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400558 return ScoredRefreshRate{score.modeIt->second, score.overallScore};
ramindanid72ba162022-09-09 21:33:40 +0000559 });
Ady Abraham34702102020-02-10 14:12:05 -0800560
Ady Abraham37d46922022-10-05 13:08:51 -0700561 const bool noLayerScore = std::all_of(scores.begin(), scores.end(), [](RefreshRateScore score) {
562 return score.overallScore == 0;
563 });
564
Alec Mouri11232a22020-05-14 18:06:25 -0700565 if (primaryRangeIsSingleRate) {
566 // If we never scored any layers, then choose the rate from the primary
567 // range instead of picking a random score from the app range.
Ady Abraham37d46922022-10-05 13:08:51 -0700568 if (noLayerScore) {
ramindanid72ba162022-09-09 21:33:40 +0000569 ALOGV("Layers not scored");
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400570 return {rankRefreshRates(anchorGroup, RefreshRateOrder::Descending), kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700571 } else {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400572 return {ranking, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700573 }
574 }
575
Steven Thomasf734df42020-04-13 21:09:28 -0700576 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
577 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
578 // vote we should not change it if we get a touch event. Only apply touch boost if it will
579 // actually increase the refresh rate over the normal selection.
Ady Abraham5e4e9832021-06-14 13:40:56 -0700580 const bool touchBoostForExplicitExact = [&] {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800581 if (mSupportsFrameRateOverrideByContent) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700582 // Enable touch boost if there are other layers besides exact
583 return explicitExact + noVoteLayers != layers.size();
584 } else {
585 // Enable touch boost if there are no exact layers
586 return explicitExact == 0;
587 }
588 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700589
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400590 const auto touchRefreshRates = rankRefreshRates(anchorGroup, RefreshRateOrder::Descending);
591
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700592 using fps_approx_ops::operator<;
593
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800594 if (signals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400595 scores.front().modeIt->second->getFps() < touchRefreshRates.front().modePtr->getFps()) {
ramindanid72ba162022-09-09 21:33:40 +0000596 ALOGV("Touch Boost");
597 return {touchRefreshRates, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700598 }
599
Ady Abraham37d46922022-10-05 13:08:51 -0700600 // If we never scored any layers, and we don't favor high refresh rates, prefer to stay with the
601 // current config
602 if (noLayerScore && refreshRateOrder == RefreshRateOrder::Ascending) {
603 const auto preferredDisplayMode = activeMode.getId();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400604 return {rankRefreshRates(anchorGroup, RefreshRateOrder::Ascending, preferredDisplayMode),
Ady Abraham37d46922022-10-05 13:08:51 -0700605 kNoSignals};
606 }
607
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400608 return {ranking, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800609}
610
Ady Abraham62a0be22020-12-08 16:54:10 -0800611std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
612groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
613 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
614 for (const auto& layer : layers) {
615 auto iter = layersByUid.emplace(layer.ownerUid,
616 std::vector<const RefreshRateConfigs::LayerRequirement*>());
617 auto& layersWithSameUid = iter.first->second;
618 layersWithSameUid.push_back(&layer);
619 }
620
621 // Remove uids that can't have a frame rate override
622 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
623 const auto& layersWithSameUid = iter->second;
624 bool skipUid = false;
625 for (const auto& layer : layersWithSameUid) {
626 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
627 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
628 skipUid = true;
629 break;
630 }
631 }
632 if (skipUid) {
633 iter = layersByUid.erase(iter);
634 } else {
635 ++iter;
636 }
637 }
638
639 return layersByUid;
640}
641
Ady Abraham62a0be22020-12-08 16:54:10 -0800642RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800643 const std::vector<LayerRequirement>& layers, Fps displayRefreshRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700644 GlobalSignals globalSignals) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800645 ATRACE_CALL();
Ady Abraham62a0be22020-12-08 16:54:10 -0800646
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800647 ALOGV("%s: %zu layers", __func__, layers.size());
648
Ady Abraham62a0be22020-12-08 16:54:10 -0800649 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800650
651 std::vector<RefreshRateScore> scores;
652 scores.reserve(mDisplayModes.size());
653
654 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
655 scores.emplace_back(RefreshRateScore{it, 0.0f});
656 }
657
658 std::sort(scores.begin(), scores.end(), [](const auto& lhs, const auto& rhs) {
659 const auto& mode1 = lhs.modeIt->second;
660 const auto& mode2 = rhs.modeIt->second;
661 return isStrictlyLess(mode1->getFps(), mode2->getFps());
662 });
663
Ady Abraham62a0be22020-12-08 16:54:10 -0800664 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
665 groupLayersByUid(layers);
666 UidToFrameRateOverride frameRateOverrides;
667 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800668 // Layers with ExplicitExactOrMultiple expect touch boost
669 const bool hasExplicitExactOrMultiple =
670 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
671 [](const auto& layer) {
672 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
673 });
674
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700675 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800676 continue;
677 }
678
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000679 for (auto& [_, score, _1] : scores) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800680 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -0800681 }
682
683 for (const auto& layer : layersWithSameUid) {
684 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
685 continue;
686 }
687
688 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800689 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
690 layer->vote != LayerVoteType::ExplicitExact);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000691 for (auto& [modeIt, score, _] : scores) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800692 constexpr bool isSeamlessSwitch = true;
693 const auto layerScore = calculateLayerScoreLocked(*layer, modeIt->second->getFps(),
694 isSeamlessSwitch);
695 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -0800696 }
697 }
698
Ady Abrahamcc315492022-02-17 17:06:39 -0800699 // We just care about the refresh rates which are a divisor of the
Ady Abraham62a0be22020-12-08 16:54:10 -0800700 // display refresh rate
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800701 const auto it = std::remove_if(scores.begin(), scores.end(), [&](RefreshRateScore score) {
702 const auto& [id, mode] = *score.modeIt;
703 return getFrameRateDivisor(displayRefreshRate, mode->getFps()) == 0;
704 });
705 scores.erase(it, scores.end());
Ady Abraham62a0be22020-12-08 16:54:10 -0800706
707 // If we never scored any layers, we don't have a preferred frame rate
708 if (std::all_of(scores.begin(), scores.end(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000709 [](RefreshRateScore score) { return score.overallScore == 0; })) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800710 continue;
711 }
712
ramindanid72ba162022-09-09 21:33:40 +0000713 // Now that we scored all the refresh rates we need to pick the lowest refresh rate
714 // that got the highest score.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800715 const DisplayModePtr& bestRefreshRate =
ramindanid72ba162022-09-09 21:33:40 +0000716 std::min_element(scores.begin(), scores.end(),
717 RefreshRateScoreComparator{.refreshRateOrder =
718 RefreshRateOrder::Ascending})
719 ->modeIt->second;
Ady Abraham5cc2e262021-03-25 13:09:17 -0700720 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800721 }
722
723 return frameRateOverrides;
724}
725
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100726std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800727 std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800728 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100729
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800730 const DisplayModePtr& current = desiredActiveModeId
731 ? mDisplayModes.get(*desiredActiveModeId)->get()
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700732 : getActiveModeItLocked()->second;
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100733
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800734 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
735 if (current == min) {
736 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100737 }
738
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800739 const auto& mode = timerExpired ? min : current;
740 return mode->getFps();
Steven Thomasf734df42020-04-13 21:09:28 -0700741}
742
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800743const DisplayModePtr& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700744 const auto& activeMode = *getActiveModeItLocked()->second;
745
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800746 for (const DisplayModeIterator modeIt : mPrimaryRefreshRates) {
747 const auto& mode = modeIt->second;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700748 if (activeMode.getGroup() == mode->getGroup()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800749 return mode;
Marin Shalamanov46084422020-10-13 12:33:42 +0200750 }
751 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800752
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700753 ALOGE("Can't find min refresh rate by policy with the same mode group as the current mode %s",
754 to_string(activeMode).c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800755
756 // Default to the lowest refresh rate.
757 return mPrimaryRefreshRates.front()->second;
Ady Abraham2139f732019-11-13 18:56:40 -0800758}
759
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800760const DisplayModePtr& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
761 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); ++it) {
762 const auto& mode = (*it)->second;
763 if (anchorGroup == mode->getGroup()) {
764 return mode;
Marin Shalamanov46084422020-10-13 12:33:42 +0200765 }
766 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800767
ramindanid72ba162022-09-09 21:33:40 +0000768 ALOGE("Can't find max refresh rate by policy with the same group %d", anchorGroup);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800769
770 // Default to the highest refresh rate.
771 return mPrimaryRefreshRates.back()->second;
Ady Abraham2139f732019-11-13 18:56:40 -0800772}
773
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400774auto RefreshRateConfigs::rankRefreshRates(
Ady Abraham37d46922022-10-05 13:08:51 -0700775 std::optional<int> anchorGroupOpt, RefreshRateOrder refreshRateOrder,
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400776 std::optional<DisplayModeId> preferredDisplayModeOpt) const -> RefreshRateRanking {
777 std::deque<ScoredRefreshRate> ranking;
778
779 const auto rankRefreshRate = [&](DisplayModeIterator it) REQUIRES(mLock) {
ramindanid72ba162022-09-09 21:33:40 +0000780 const auto& mode = it->second;
Ady Abraham37d46922022-10-05 13:08:51 -0700781 if (anchorGroupOpt && mode->getGroup() != anchorGroupOpt) {
782 return;
ramindanid72ba162022-09-09 21:33:40 +0000783 }
Ady Abraham37d46922022-10-05 13:08:51 -0700784
785 float score = calculateRefreshRateScoreForFps(mode->getFps());
786 const bool inverseScore = (refreshRateOrder == RefreshRateOrder::Ascending);
787 if (inverseScore) {
788 score = 1.0f / score;
789 }
790 if (preferredDisplayModeOpt) {
791 if (*preferredDisplayModeOpt == mode->getId()) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400792 constexpr float kScore = std::numeric_limits<float>::max();
793 ranking.push_front(ScoredRefreshRate{mode, kScore});
Ady Abraham37d46922022-10-05 13:08:51 -0700794 return;
795 }
796 constexpr float kNonPreferredModePenalty = 0.95f;
797 score *= kNonPreferredModePenalty;
798 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400799 ranking.push_back(ScoredRefreshRate{mode, score});
ramindanid72ba162022-09-09 21:33:40 +0000800 };
801
802 if (refreshRateOrder == RefreshRateOrder::Ascending) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400803 std::for_each(mPrimaryRefreshRates.begin(), mPrimaryRefreshRates.end(), rankRefreshRate);
ramindanid72ba162022-09-09 21:33:40 +0000804 } else {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400805 std::for_each(mPrimaryRefreshRates.rbegin(), mPrimaryRefreshRates.rend(), rankRefreshRate);
ramindanid72ba162022-09-09 21:33:40 +0000806 }
807
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400808 if (!ranking.empty() || !anchorGroupOpt) {
809 return {ranking.begin(), ranking.end()};
ramindanid72ba162022-09-09 21:33:40 +0000810 }
811
812 ALOGW("Can't find %s refresh rate by policy with the same mode group"
813 " as the mode group %d",
814 refreshRateOrder == RefreshRateOrder::Ascending ? "min" : "max", anchorGroupOpt.value());
815
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400816 constexpr std::optional<int> kNoAnchorGroup = std::nullopt;
817 return rankRefreshRates(kNoAnchorGroup, refreshRateOrder, preferredDisplayModeOpt);
ramindanid72ba162022-09-09 21:33:40 +0000818}
819
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700820DisplayModePtr RefreshRateConfigs::getActiveModePtr() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800821 std::lock_guard lock(mLock);
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700822 return getActiveModeItLocked()->second;
823}
824
825const DisplayMode& RefreshRateConfigs::getActiveMode() const {
826 // Reads from kMainThreadContext do not require mLock.
827 ftl::FakeGuard guard(mLock);
828 return *mActiveModeIt->second;
829}
830
831DisplayModeIterator RefreshRateConfigs::getActiveModeItLocked() const {
832 // Reads under mLock do not require kMainThreadContext.
833 return FTL_FAKE_GUARD(kMainThreadContext, mActiveModeIt);
Ady Abraham2139f732019-11-13 18:56:40 -0800834}
835
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800836void RefreshRateConfigs::setActiveModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800837 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200838
ramindanid72ba162022-09-09 21:33:40 +0000839 // Invalidate the cached invocation to getRankedRefreshRates. This forces
840 // the refresh rate to be recomputed on the next call to getRankedRefreshRates.
841 mGetRankedRefreshRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200842
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800843 mActiveModeIt = mDisplayModes.find(modeId);
844 LOG_ALWAYS_FATAL_IF(mActiveModeIt == mDisplayModes.end());
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800845}
846
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800847RefreshRateConfigs::RefreshRateConfigs(DisplayModes modes, DisplayModeId activeModeId,
rnlee3bd610662021-06-23 16:27:57 -0700848 Config config)
849 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700850 initializeIdleTimer();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700851 FTL_FAKE_GUARD(kMainThreadContext, updateDisplayModes(std::move(modes), activeModeId));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100852}
853
Ady Abraham9a2ea342021-09-03 17:32:34 -0700854void RefreshRateConfigs::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +0000855 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700856 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +0000857 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800858 [this] {
859 std::scoped_lock lock(mIdleTimerCallbacksMutex);
860 if (const auto callbacks = getIdleTimerCallbacks()) {
861 callbacks->onReset();
862 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700863 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800864 [this] {
865 std::scoped_lock lock(mIdleTimerCallbacksMutex);
866 if (const auto callbacks = getIdleTimerCallbacks()) {
867 callbacks->onExpired();
868 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700869 });
Ady Abraham9a2ea342021-09-03 17:32:34 -0700870 }
871}
872
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800873void RefreshRateConfigs::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100874 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200875
ramindanid72ba162022-09-09 21:33:40 +0000876 // Invalidate the cached invocation to getRankedRefreshRates. This forces
877 // the refresh rate to be recomputed on the next call to getRankedRefreshRates.
878 mGetRankedRefreshRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200879
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800880 mDisplayModes = std::move(modes);
881 mActiveModeIt = mDisplayModes.find(activeModeId);
882 LOG_ALWAYS_FATAL_IF(mActiveModeIt == mDisplayModes.end());
Ady Abrahamabc27602020-04-08 17:20:29 -0700883
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800884 const auto sortedModes =
885 sortByRefreshRate(mDisplayModes, [](const DisplayMode&) { return true; });
886 mMinRefreshRateModeIt = sortedModes.front();
887 mMaxRefreshRateModeIt = sortedModes.back();
888
Marin Shalamanov75f37252021-02-10 21:43:57 +0100889 // Reset the policy because the old one may no longer be valid.
890 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800891 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -0800892
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800893 mSupportsFrameRateOverrideByContent =
894 mConfig.enableFrameRateOverride && canModesSupportFrameRateOverride(sortedModes);
Ady Abraham4899ff82021-01-06 13:53:29 -0800895
Ady Abrahamabc27602020-04-08 17:20:29 -0700896 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800897}
898
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100899bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100900 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800901 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
902 if (!policy.primaryRange.includes(mode->get()->getFps())) {
903 ALOGE("Default mode is not in the primary range.");
904 return false;
905 }
906 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100907 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700908 return false;
909 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700910
911 using namespace fps_approx_ops;
912 return policy.appRequestRange.min <= policy.primaryRange.min &&
913 policy.appRequestRange.max >= policy.primaryRange.max;
Steven Thomasd4071902020-03-24 16:02:53 -0700914}
915
Dominik Laskowski36dced82022-09-02 09:24:00 -0700916auto RefreshRateConfigs::setPolicy(const PolicyVariant& policy) -> SetPolicyResult {
917 Policy oldPolicy;
918 {
919 std::lock_guard lock(mLock);
920 oldPolicy = *getCurrentPolicyLocked();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100921
Dominik Laskowski36dced82022-09-02 09:24:00 -0700922 const bool valid = ftl::match(
923 policy,
924 [this](const auto& policy) {
925 ftl::FakeGuard guard(mLock);
926 if (!isPolicyValidLocked(policy)) {
927 ALOGE("Invalid policy: %s", policy.toString().c_str());
928 return false;
929 }
930
931 using T = std::decay_t<decltype(policy)>;
932
933 if constexpr (std::is_same_v<T, DisplayManagerPolicy>) {
934 mDisplayManagerPolicy = policy;
935 } else {
936 static_assert(std::is_same_v<T, OverridePolicy>);
937 mOverridePolicy = policy;
938 }
939 return true;
940 },
941 [this](NoOverridePolicy) {
942 ftl::FakeGuard guard(mLock);
943 mOverridePolicy.reset();
944 return true;
945 });
946
947 if (!valid) {
948 return SetPolicyResult::Invalid;
949 }
950
951 mGetRankedRefreshRatesCache.reset();
952
953 if (*getCurrentPolicyLocked() == oldPolicy) {
954 return SetPolicyResult::Unchanged;
955 }
956 constructAvailableRefreshRates();
Steven Thomasd4071902020-03-24 16:02:53 -0700957 }
Dominik Laskowski36dced82022-09-02 09:24:00 -0700958
959 const auto displayId = getActiveMode().getPhysicalDisplayId();
960 const unsigned numModeChanges = std::exchange(mNumModeSwitchesInPolicy, 0u);
961
962 ALOGI("Display %s policy changed\n"
963 "Previous: %s\n"
964 "Current: %s\n"
965 "%u mode changes were performed under the previous policy",
966 to_string(displayId).c_str(), oldPolicy.toString().c_str(), toString(policy).c_str(),
967 numModeChanges);
968
969 return SetPolicyResult::Changed;
Steven Thomasd4071902020-03-24 16:02:53 -0700970}
971
972const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
973 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
974}
975
976RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
977 std::lock_guard lock(mLock);
978 return *getCurrentPolicyLocked();
979}
980
981RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
982 std::lock_guard lock(mLock);
983 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100984}
985
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100986bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100987 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800988 return std::any_of(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
989 [modeId](DisplayModeIterator modeIt) {
990 return modeIt->second->getId() == modeId;
991 });
Ady Abraham2139f732019-11-13 18:56:40 -0800992}
993
994void RefreshRateConfigs::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800995 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -0700996 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800997 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700998
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800999 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -08001000
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001001 const auto filterRefreshRates = [&](FpsRange range, const char* rangeName) REQUIRES(mLock) {
1002 const auto filter = [&](const DisplayMode& mode) {
1003 return mode.getResolution() == defaultMode->getResolution() &&
1004 mode.getDpi() == defaultMode->getDpi() &&
1005 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
1006 range.includes(mode.getFps());
1007 };
Ady Abraham8a82ba62020-01-17 12:43:17 -08001008
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001009 const auto modes = sortByRefreshRate(mDisplayModes, filter);
1010 LOG_ALWAYS_FATAL_IF(modes.empty(), "No matching modes for %s range %s", rangeName,
1011 to_string(range).c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -08001012
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001013 const auto stringifyModes = [&] {
1014 std::string str;
1015 for (const auto modeIt : modes) {
1016 str += to_string(modeIt->second->getFps());
1017 str.push_back(' ');
1018 }
1019 return str;
1020 };
1021 ALOGV("%s refresh rates: %s", rangeName, stringifyModes().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -07001022
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001023 return modes;
1024 };
1025
1026 mPrimaryRefreshRates = filterRefreshRates(policy->primaryRange, "primary");
1027 mAppRequestRefreshRates = filterRefreshRates(policy->appRequestRange, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -08001028}
1029
Marin Shalamanove8a663d2020-11-24 17:48:00 +01001030Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001031 using namespace fps_approx_ops;
1032
1033 if (frameRate <= mKnownFrameRates.front()) {
1034 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001035 }
1036
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001037 if (frameRate >= mKnownFrameRates.back()) {
1038 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001039 }
1040
Marin Shalamanove8a663d2020-11-24 17:48:00 +01001041 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001042 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001043
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001044 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
1045 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001046 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
1047}
1048
Ana Krulecb9afd792020-06-11 13:16:15 -07001049RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
1050 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001051
1052 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getFps();
1053 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -07001054
1055 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
1056 // the min allowed refresh rate is higher than the device min, we do not want to enable the
1057 // timer.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001058 if (isStrictlyLess(deviceMinFps, minByPolicy->getFps())) {
1059 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001060 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001061
ramindanid72ba162022-09-09 21:33:40 +00001062 const DisplayModePtr& maxByPolicy =
1063 getMaxRefreshRateByPolicyLocked(getActiveModeItLocked()->second->getGroup());
Ana Krulecb9afd792020-06-11 13:16:15 -07001064 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001065 // Turn on the timer when the min of the primary range is below the device min.
1066 if (const Policy* currentPolicy = getCurrentPolicyLocked();
1067 isApproxLess(currentPolicy->primaryRange.min, deviceMinFps)) {
1068 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001069 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001070 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001071 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001072
Ana Krulecb9afd792020-06-11 13:16:15 -07001073 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001074 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001075}
1076
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001077int RefreshRateConfigs::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -07001078 // This calculation needs to be in sync with the java code
1079 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001080
1081 // The threshold must be smaller than 0.001 in order to differentiate
1082 // between the fractional pairs (e.g. 59.94 and 60).
1083 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001084 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -07001085 const auto numPeriodsRounded = std::round(numPeriods);
1086 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001087 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -07001088 }
1089
Ady Abraham62f216c2020-10-13 19:07:23 -07001090 return static_cast<int>(numPeriodsRounded);
1091}
1092
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001093bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001094 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001095 return isFractionalPairOrMultiple(bigger, smaller);
1096 }
1097
1098 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
1099 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001100 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
1101 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001102}
1103
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001104void RefreshRateConfigs::dump(utils::Dumper& dumper) const {
1105 using namespace std::string_view_literals;
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001106
Marin Shalamanovba421a82020-11-10 21:49:26 +01001107 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +01001108
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001109 const auto activeModeId = getActiveModeItLocked()->first;
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001110 dumper.dump("activeModeId"sv, std::to_string(activeModeId.value()));
Marin Shalamanovba421a82020-11-10 21:49:26 +01001111
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001112 dumper.dump("displayModes"sv);
1113 {
1114 utils::Dumper::Indent indent(dumper);
1115 for (const auto& [id, mode] : mDisplayModes) {
1116 dumper.dump({}, to_string(*mode));
1117 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001118 }
1119
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001120 dumper.dump("displayManagerPolicy"sv, mDisplayManagerPolicy.toString());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001121
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001122 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
1123 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001124 dumper.dump("overridePolicy"sv, currentPolicy.toString());
ramindani32cf0602022-03-02 02:30:29 +00001125 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001126
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001127 dumper.dump("supportsFrameRateOverrideByContent"sv, mSupportsFrameRateOverrideByContent);
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001128
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001129 std::string idleTimer;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001130 if (mIdleTimer) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001131 idleTimer = mIdleTimer->dump();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001132 } else {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001133 idleTimer = "off"sv;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001134 }
1135
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001136 if (const auto controller = mConfig.kernelIdleTimerController) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001137 base::StringAppendF(&idleTimer, " (kernel via %s)", ftl::enum_string(*controller).c_str());
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001138 } else {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001139 idleTimer += " (platform)"sv;
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001140 }
1141
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001142 dumper.dump("idleTimer"sv, idleTimer);
Marin Shalamanovba421a82020-11-10 21:49:26 +01001143}
1144
ramindani32cf0602022-03-02 02:30:29 +00001145std::chrono::milliseconds RefreshRateConfigs::getIdleTimerTimeout() {
1146 return mConfig.idleTimerTimeout;
1147}
1148
Ady Abraham2139f732019-11-13 18:56:40 -08001149} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001150
1151// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001152#pragma clang diagnostic pop // ignored "-Wextra"