blob: 0f1e26750ec07ed1f875f4c4ac5c8b269b6a7c6d [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 Abrahamb4b1e0a2019-11-20 18:25:35 -080024#include "RefreshRateConfigs.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080025#include <android-base/stringprintf.h>
26#include <utils/Trace.h>
27#include <chrono>
28#include <cmath>
Ady Abraham4899ff82021-01-06 13:53:29 -080029#include "../SurfaceFlingerProperties.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080030
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080031#undef LOG_TAG
32#define LOG_TAG "RefreshRateConfigs"
33
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080034namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010035namespace {
36std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010037 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010038 RefreshRateConfigs::layerVoteTypeString(layer.vote).c_str(), weight,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010039 toString(layer.seamlessness).c_str(),
40 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010041}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010042
Marin Shalamanov3ea1d602020-12-16 19:59:39 +010043std::vector<Fps> constructKnownFrameRates(const DisplayModes& configs) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010044 std::vector<Fps> knownFrameRates = {Fps(24.0f), Fps(30.0f), Fps(45.0f), Fps(60.0f), Fps(72.0f)};
45 knownFrameRates.reserve(knownFrameRates.size() + configs.size());
46
47 // Add all supported refresh rates to the set
48 for (const auto& config : configs) {
49 const auto refreshRate = Fps::fromPeriodNsecs(config->getVsyncPeriod());
50 knownFrameRates.emplace_back(refreshRate);
51 }
52
53 // Sort and remove duplicates
54 std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
55 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
56 Fps::EqualsWithMargin()),
57 knownFrameRates.end());
58 return knownFrameRates;
59}
60
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010061} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080062
63using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080064using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080065
Marin Shalamanov46084422020-10-13 12:33:42 +020066std::string RefreshRate::toString() const {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +010067 return base::StringPrintf("{id=%zu, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
68 getConfigId().value(), hwcConfig->getHwcId(), getFps().getValue(),
Marin Shalamanov46084422020-10-13 12:33:42 +020069 hwcConfig->getWidth(), hwcConfig->getHeight(), getConfigGroup());
70}
71
Ady Abrahama6b676e2020-05-27 14:29:09 -070072std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
73 switch (vote) {
74 case LayerVoteType::NoVote:
75 return "NoVote";
76 case LayerVoteType::Min:
77 return "Min";
78 case LayerVoteType::Max:
79 return "Max";
80 case LayerVoteType::Heuristic:
81 return "Heuristic";
82 case LayerVoteType::ExplicitDefault:
83 return "ExplicitDefault";
84 case LayerVoteType::ExplicitExactOrMultiple:
85 return "ExplicitExactOrMultiple";
86 }
87}
88
Marin Shalamanovb6674e72020-11-06 13:05:57 +010089std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +010090 return base::StringPrintf("default config ID: %zu, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010091 ", primary range: %s, app request range: %s",
92 defaultConfig.value(), allowGroupSwitching,
93 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020094}
95
Ady Abraham4ccdcb42020-02-11 17:34:34 -080096std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
97 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -080098 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
99 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
100 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
101 quotient++;
102 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800103 }
104
Ady Abraham62a0be22020-12-08 16:54:10 -0800105 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800106}
107
Ady Abraham62a0be22020-12-08 16:54:10 -0800108float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
109 const RefreshRate& refreshRate,
110 bool isSeamlessSwitch) const {
111 // Slightly prefer seamless switches.
112 constexpr float kSeamedSwitchPenalty = 0.95f;
113 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
114
115 // If the layer wants Max, give higher score to the higher refresh rate
116 if (layer.vote == LayerVoteType::Max) {
117 const auto ratio =
118 refreshRate.fps.getValue() / mAppRequestRefreshRates.back()->fps.getValue();
119 // use ratio^2 to get a lower score the more we get further from peak
120 return ratio * ratio;
121 }
122
123 const auto displayPeriod = refreshRate.getVsyncPeriod();
124 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
125 if (layer.vote == LayerVoteType::ExplicitDefault) {
126 // Find the actual rate the layer will render, assuming
127 // that layerPeriod is the minimal time to render a frame
128 auto actualLayerPeriod = displayPeriod;
129 int multiplier = 1;
130 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
131 multiplier++;
132 actualLayerPeriod = displayPeriod * multiplier;
133 }
134 return std::min(1.0f,
135 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
136 }
137
138 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
139 layer.vote == LayerVoteType::Heuristic) {
140 // Calculate how many display vsyncs we need to present a single frame for this
141 // layer
142 const auto [displayFramesQuotient, displayFramesRemainder] =
143 getDisplayFrames(layerPeriod, displayPeriod);
144 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
145 if (displayFramesRemainder == 0) {
146 // Layer desired refresh rate matches the display rate.
147 return 1.0f * seamlessness;
148 }
149
150 if (displayFramesQuotient == 0) {
151 // Layer desired refresh rate is higher than the display rate.
152 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
153 (1.0f / (MAX_FRAMES_TO_FIT + 1));
154 }
155
156 // Layer desired refresh rate is lower than the display rate. Check how well it fits
157 // the cadence.
158 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
159 int iter = 2;
160 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
161 diff = diff - (displayPeriod - diff);
162 iter++;
163 }
164
165 return (1.0f / iter) * seamlessness;
166 }
167
168 return 0;
169}
170
171struct RefreshRateScore {
172 const RefreshRate* refreshRate;
173 float score;
174};
175
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100176RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
177 const GlobalSignals& globalSignals,
178 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800179 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200180 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800181
Ady Abrahamdfd62162020-06-10 16:11:56 -0700182 if (outSignalsConsidered) *outSignalsConsidered = {};
183 const auto setTouchConsidered = [&] {
184 if (outSignalsConsidered) {
185 outSignalsConsidered->touch = true;
186 }
187 };
188
189 const auto setIdleConsidered = [&] {
190 if (outSignalsConsidered) {
191 outSignalsConsidered->idle = true;
192 }
193 };
194
Ady Abraham8a82ba62020-01-17 12:43:17 -0800195 std::lock_guard lock(mLock);
196
197 int noVoteLayers = 0;
198 int minVoteLayers = 0;
199 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800200 int explicitDefaultVoteLayers = 0;
201 int explicitExactOrMultipleVoteLayers = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800202 float maxExplicitWeight = 0;
Marin Shalamanov46084422020-10-13 12:33:42 +0200203 int seamedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800204 for (const auto& layer : layers) {
Ady Abraham6fb599b2020-03-05 13:48:22 -0800205 if (layer.vote == LayerVoteType::NoVote) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800206 noVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800207 } else if (layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800208 minVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800209 } else if (layer.vote == LayerVoteType::Max) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800210 maxVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800211 } else if (layer.vote == LayerVoteType::ExplicitDefault) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800212 explicitDefaultVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800213 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
214 } else if (layer.vote == LayerVoteType::ExplicitExactOrMultiple) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800215 explicitExactOrMultipleVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800216 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
217 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200218
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100219 if (layer.seamlessness == Seamlessness::SeamedAndSeamless) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200220 seamedLayers++;
221 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800222 }
223
Alec Mouri11232a22020-05-14 18:06:25 -0700224 const bool hasExplicitVoteLayers =
225 explicitDefaultVoteLayers > 0 || explicitExactOrMultipleVoteLayers > 0;
226
Steven Thomasf734df42020-04-13 21:09:28 -0700227 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
228 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700229 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700230 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700231 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700232 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800233 }
234
Alec Mouri11232a22020-05-14 18:06:25 -0700235 // If the primary range consists of a single refresh rate then we can only
236 // move out the of range if layers explicitly request a different refresh
237 // rate.
238 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100239 const bool primaryRangeIsSingleRate =
240 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700241
Ady Abrahamdfd62162020-06-10 16:11:56 -0700242 if (!globalSignals.touch && globalSignals.idle &&
243 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700244 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700245 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700246 return getMinRefreshRateByPolicyLocked();
247 }
248
Steven Thomasdebafed2020-05-18 17:30:35 -0700249 if (layers.empty() || noVoteLayers == layers.size()) {
250 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700251 }
252
Ady Abraham8a82ba62020-01-17 12:43:17 -0800253 // Only if all layers want Min we should return Min
254 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700255 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700256 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800257 }
258
Ady Abraham8a82ba62020-01-17 12:43:17 -0800259 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800260 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700261 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800262
Steven Thomasf734df42020-04-13 21:09:28 -0700263 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800264 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800265 }
266
Marin Shalamanov46084422020-10-13 12:33:42 +0200267 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig);
268
Ady Abraham8a82ba62020-01-17 12:43:17 -0800269 for (const auto& layer : layers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700270 ALOGV("Calculating score for %s (%s, weight %.2f)", layer.name.c_str(),
271 layerVoteTypeString(layer.vote).c_str(), layer.weight);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800272 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800273 continue;
274 }
275
Ady Abraham71c437d2020-01-31 15:56:57 -0800276 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800277
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800278 for (auto i = 0u; i < scores.size(); i++) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800279 const bool isSeamlessSwitch = scores[i].refreshRate->getConfigGroup() ==
280 mCurrentRefreshRate->getConfigGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200281
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100282 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
283 ALOGV("%s ignores %s to avoid non-seamless switch. Current config = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800284 formatLayerInfo(layer, weight).c_str(),
285 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100286 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200287 continue;
288 }
289
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100290 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
291 !layer.focused) {
292 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
293 " Current config = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800294 formatLayerInfo(layer, weight).c_str(),
295 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100296 mCurrentRefreshRate->toString().c_str());
297 continue;
298 }
299
300 // Layers with default seamlessness vote for the current config group if
301 // there are layers with seamlessness=SeamedAndSeamless and for the default
302 // config group otherwise. In second case, if the current config group is different
303 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
304 // disappeared.
305 const bool isInPolicyForDefault = seamedLayers > 0
Ady Abraham62a0be22020-12-08 16:54:10 -0800306 ? scores[i].refreshRate->getConfigGroup() ==
307 mCurrentRefreshRate->getConfigGroup()
308 : scores[i].refreshRate->getConfigGroup() == defaultConfig->getConfigGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100309
310 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault &&
311 !layer.focused) {
312 ALOGV("%s ignores %s. Current config = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800313 scores[i].refreshRate->toString().c_str(),
314 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200315 continue;
316 }
317
Ady Abraham62a0be22020-12-08 16:54:10 -0800318 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
319 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700320 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abraham20c029c2020-07-06 12:58:05 -0700321 !(layer.focused && layer.vote == LayerVoteType::ExplicitDefault)) {
322 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700323 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700324 continue;
325 }
326
Ady Abraham62a0be22020-12-08 16:54:10 -0800327 const auto layerScore =
328 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
329 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
330 scores[i].refreshRate->getName().c_str(), layerScore);
331 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800332 }
333 }
334
Ady Abraham34702102020-02-10 14:12:05 -0800335 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
336 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
337 // or the lower otherwise.
338 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
339 ? getBestRefreshRate(scores.rbegin(), scores.rend())
340 : getBestRefreshRate(scores.begin(), scores.end());
341
Alec Mouri11232a22020-05-14 18:06:25 -0700342 if (primaryRangeIsSingleRate) {
343 // If we never scored any layers, then choose the rate from the primary
344 // range instead of picking a random score from the app range.
345 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800346 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700347 ALOGV("layers not scored - choose %s",
348 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700349 return getMaxRefreshRateByPolicyLocked();
350 } else {
351 return *bestRefreshRate;
352 }
353 }
354
Steven Thomasf734df42020-04-13 21:09:28 -0700355 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
356 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
357 // vote we should not change it if we get a touch event. Only apply touch boost if it will
358 // actually increase the refresh rate over the normal selection.
359 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700360
Ady Abrahamdfd62162020-06-10 16:11:56 -0700361 if (globalSignals.touch && explicitDefaultVoteLayers == 0 &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100362 bestRefreshRate->fps.lessThanWithMargin(touchRefreshRate.fps)) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700363 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700364 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700365 return touchRefreshRate;
366 }
367
Ady Abrahamde7156e2020-02-28 17:29:39 -0800368 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800369}
370
Ady Abraham62a0be22020-12-08 16:54:10 -0800371std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
372groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
373 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
374 for (const auto& layer : layers) {
375 auto iter = layersByUid.emplace(layer.ownerUid,
376 std::vector<const RefreshRateConfigs::LayerRequirement*>());
377 auto& layersWithSameUid = iter.first->second;
378 layersWithSameUid.push_back(&layer);
379 }
380
381 // Remove uids that can't have a frame rate override
382 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
383 const auto& layersWithSameUid = iter->second;
384 bool skipUid = false;
385 for (const auto& layer : layersWithSameUid) {
386 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
387 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
388 skipUid = true;
389 break;
390 }
391 }
392 if (skipUid) {
393 iter = layersByUid.erase(iter);
394 } else {
395 ++iter;
396 }
397 }
398
399 return layersByUid;
400}
401
402std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
403 const AllRefreshRatesMapType& refreshRates) {
404 std::vector<RefreshRateScore> scores;
405 scores.reserve(refreshRates.size());
406 for (const auto& [ignored, refreshRate] : refreshRates) {
407 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
408 }
409 std::sort(scores.begin(), scores.end(),
410 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
411 return scores;
412}
413
414RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
415 const std::vector<LayerRequirement>& layers, Fps displayFrameRate) const {
416 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800417 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800418
Ady Abraham64c2fc02020-12-29 12:07:50 -0800419 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800420 std::lock_guard lock(mLock);
421 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
422 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
423 groupLayersByUid(layers);
424 UidToFrameRateOverride frameRateOverrides;
425 for (const auto& [uid, layersWithSameUid] : layersByUid) {
426 for (auto& score : scores) {
427 score.score = 0;
428 }
429
430 for (const auto& layer : layersWithSameUid) {
431 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
432 continue;
433 }
434
435 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
436 layer->vote != LayerVoteType::ExplicitExactOrMultiple);
437 for (RefreshRateScore& score : scores) {
438 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
439 /*isSeamlessSwitch*/ true);
440 score.score += layer->weight * layerScore;
441 }
442 }
443
444 // We just care about the refresh rates which are a divider of the
445 // display refresh rate
446 auto iter =
447 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
448 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
449 });
450 scores.erase(iter, scores.end());
451
452 // If we never scored any layers, we don't have a preferred frame rate
453 if (std::all_of(scores.begin(), scores.end(),
454 [](const RefreshRateScore& score) { return score.score == 0; })) {
455 continue;
456 }
457
458 // Now that we scored all the refresh rates we need to pick the one that got the highest
459 // score.
460 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
461
462 // If the nest refresh rate is the current one, we don't have an override
463 if (!bestRefreshRate->getFps().equalsWithMargin(displayFrameRate)) {
464 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
465 }
466 }
467
468 return frameRateOverrides;
469}
470
Ady Abraham34702102020-02-10 14:12:05 -0800471template <typename Iter>
472const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800473 constexpr auto EPSILON = 0.001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800474 const RefreshRate* bestRefreshRate = begin->refreshRate;
475 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800476 for (auto i = begin; i != end; ++i) {
477 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100478 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800479
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100480 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800481
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800482 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800483 max = score;
484 bestRefreshRate = refreshRate;
485 }
486 }
487
Ady Abraham34702102020-02-10 14:12:05 -0800488 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800489}
490
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100491std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100492 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800493 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100494
495 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
496 : *mCurrentRefreshRate;
497 const auto& min = *mMinSupportedRefreshRate;
498
499 if (current != min) {
500 const auto& refreshRate = timerExpired ? min : current;
501 return refreshRate.getFps();
502 }
503
504 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700505}
506
507const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200508 for (auto refreshRate : mPrimaryRefreshRates) {
509 if (mCurrentRefreshRate->getConfigGroup() == refreshRate->getConfigGroup()) {
510 return *refreshRate;
511 }
512 }
513 ALOGE("Can't find min refresh rate by policy with the same config group"
514 " as the current config %s",
515 mCurrentRefreshRate->toString().c_str());
516 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700517 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800518}
519
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100520RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800521 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700522 return getMaxRefreshRateByPolicyLocked();
523}
524
525const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200526 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
527 const auto& refreshRate = (**it);
528 if (mCurrentRefreshRate->getConfigGroup() == refreshRate.getConfigGroup()) {
529 return refreshRate;
530 }
531 }
532 ALOGE("Can't find max refresh rate by policy with the same config group"
533 " as the current config %s",
534 mCurrentRefreshRate->toString().c_str());
535 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700536 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800537}
538
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100539RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800540 std::lock_guard lock(mLock);
541 return *mCurrentRefreshRate;
542}
543
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100544RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800545 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800546 return getCurrentRefreshRateByPolicyLocked();
547}
548
549const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700550 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
551 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800552 return *mCurrentRefreshRate;
553 }
Steven Thomasd4071902020-03-24 16:02:53 -0700554 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultConfig);
Ana Krulec5d477912020-02-07 12:02:38 -0800555}
556
Marin Shalamanov23c44202020-12-22 19:09:20 +0100557void RefreshRateConfigs::setCurrentConfigId(DisplayModeId configId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800558 std::lock_guard lock(mLock);
Ady Abraham2e1dd892020-03-05 13:48:36 -0800559 mCurrentRefreshRate = mRefreshRates.at(configId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800560}
561
Marin Shalamanov23c44202020-12-22 19:09:20 +0100562RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& configs, DisplayModeId currentConfigId)
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700563 : mKnownFrameRates(constructKnownFrameRates(configs)) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100564 updateDisplayConfigs(configs, currentConfigId);
565}
566
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100567void RefreshRateConfigs::updateDisplayConfigs(const DisplayModes& configs,
Marin Shalamanov23c44202020-12-22 19:09:20 +0100568 DisplayModeId currentConfigId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100569 std::lock_guard lock(mLock);
Ady Abrahamabc27602020-04-08 17:20:29 -0700570 LOG_ALWAYS_FATAL_IF(configs.empty());
571 LOG_ALWAYS_FATAL_IF(currentConfigId.value() >= configs.size());
572
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100573 mRefreshRates.clear();
Marin Shalamanov23c44202020-12-22 19:09:20 +0100574 for (const auto& config : configs) {
575 const auto configId = config->getId();
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100576 const auto fps = Fps::fromPeriodNsecs(config->getVsyncPeriod());
Ady Abrahamabc27602020-04-08 17:20:29 -0700577 mRefreshRates.emplace(configId,
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100578 std::make_unique<RefreshRate>(configId, config, fps,
Ady Abrahamabc27602020-04-08 17:20:29 -0700579 RefreshRate::ConstructorTag(0)));
580 if (configId == currentConfigId) {
581 mCurrentRefreshRate = mRefreshRates.at(configId).get();
582 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800583 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700584
585 std::vector<const RefreshRate*> sortedConfigs;
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100586 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedConfigs);
Ady Abrahamabc27602020-04-08 17:20:29 -0700587 mDisplayManagerPolicy.defaultConfig = currentConfigId;
588 mMinSupportedRefreshRate = sortedConfigs.front();
589 mMaxSupportedRefreshRate = sortedConfigs.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800590
591 mSupportsFrameRateOverride = false;
Ady Abraham4899ff82021-01-06 13:53:29 -0800592 if (android::sysprop::enable_frame_rate_override(true)) {
593 for (const auto& config1 : sortedConfigs) {
594 for (const auto& config2 : sortedConfigs) {
595 if (getFrameRateDivider(config1->getFps(), config2->getFps()) >= 2) {
596 mSupportsFrameRateOverride = true;
597 break;
598 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800599 }
600 }
601 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800602
Ady Abrahamabc27602020-04-08 17:20:29 -0700603 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800604}
605
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100606bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Steven Thomasd4071902020-03-24 16:02:53 -0700607 // defaultConfig must be a valid config, and within the given refresh rate range.
608 auto iter = mRefreshRates.find(policy.defaultConfig);
609 if (iter == mRefreshRates.end()) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100610 ALOGE("Default config is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700611 return false;
612 }
613 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700614 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100615 ALOGE("Default config is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700616 return false;
617 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100618 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
619 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700620}
621
622status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800623 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100624 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100625 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100626 return BAD_VALUE;
627 }
Steven Thomasd4071902020-03-24 16:02:53 -0700628 Policy previousPolicy = *getCurrentPolicyLocked();
629 mDisplayManagerPolicy = policy;
630 if (*getCurrentPolicyLocked() == previousPolicy) {
631 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100632 }
Ady Abraham2139f732019-11-13 18:56:40 -0800633 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100634 return NO_ERROR;
635}
636
Steven Thomasd4071902020-03-24 16:02:53 -0700637status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100638 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100639 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700640 return BAD_VALUE;
641 }
642 Policy previousPolicy = *getCurrentPolicyLocked();
643 mOverridePolicy = policy;
644 if (*getCurrentPolicyLocked() == previousPolicy) {
645 return CURRENT_POLICY_UNCHANGED;
646 }
647 constructAvailableRefreshRates();
648 return NO_ERROR;
649}
650
651const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
652 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
653}
654
655RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
656 std::lock_guard lock(mLock);
657 return *getCurrentPolicyLocked();
658}
659
660RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
661 std::lock_guard lock(mLock);
662 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100663}
664
Marin Shalamanov23c44202020-12-22 19:09:20 +0100665bool RefreshRateConfigs::isConfigAllowed(DisplayModeId config) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100666 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700667 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100668 if (refreshRate->configId == config) {
669 return true;
670 }
671 }
672 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800673}
674
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100675void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800676 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
677 std::vector<const RefreshRate*>* outRefreshRates) {
678 outRefreshRates->clear();
679 outRefreshRates->reserve(mRefreshRates.size());
680 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800681 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100682 ALOGV("getSortedRefreshRateListLocked: config %zu added to list policy",
Ady Abraham2e1dd892020-03-05 13:48:36 -0800683 refreshRate->configId.value());
684 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800685 }
686 }
687
688 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
689 [](const auto refreshRate1, const auto refreshRate2) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700690 if (refreshRate1->hwcConfig->getVsyncPeriod() !=
691 refreshRate2->hwcConfig->getVsyncPeriod()) {
692 return refreshRate1->hwcConfig->getVsyncPeriod() >
693 refreshRate2->hwcConfig->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700694 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -0700695 return refreshRate1->hwcConfig->getConfigGroup() >
696 refreshRate2->hwcConfig->getConfigGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700697 }
Ady Abraham2139f732019-11-13 18:56:40 -0800698 });
699}
700
701void RefreshRateConfigs::constructAvailableRefreshRates() {
702 // Filter configs based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700703 const Policy* policy = getCurrentPolicyLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700704 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig)->hwcConfig;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100705 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700706
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100707 auto filterRefreshRates = [&](Fps min, Fps max, const char* listName,
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100708 std::vector<const RefreshRate*>*
709 outRefreshRates) REQUIRES(mLock) {
710 getSortedRefreshRateListLocked(
Steven Thomasf734df42020-04-13 21:09:28 -0700711 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
712 const auto& hwcConfig = refreshRate.hwcConfig;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800713
Steven Thomasf734df42020-04-13 21:09:28 -0700714 return hwcConfig->getHeight() == defaultConfig->getHeight() &&
715 hwcConfig->getWidth() == defaultConfig->getWidth() &&
716 hwcConfig->getDpiX() == defaultConfig->getDpiX() &&
717 hwcConfig->getDpiY() == defaultConfig->getDpiY() &&
718 (policy->allowGroupSwitching ||
719 hwcConfig->getConfigGroup() == defaultConfig->getConfigGroup()) &&
720 refreshRate.inPolicy(min, max);
721 },
722 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800723
Steven Thomasf734df42020-04-13 21:09:28 -0700724 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100725 "No matching configs for %s range: min=%s max=%s", listName,
726 to_string(min).c_str(), to_string(max).c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700727 auto stringifyRefreshRates = [&]() -> std::string {
728 std::string str;
729 for (auto refreshRate : *outRefreshRates) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100730 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700731 }
732 return str;
733 };
734 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
735 };
736
737 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
738 &mPrimaryRefreshRates);
739 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
740 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800741}
742
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100743Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
744 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700745 return *mKnownFrameRates.begin();
746 }
747
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100748 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700749 return *std::prev(mKnownFrameRates.end());
750 }
751
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100752 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
753 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700754
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100755 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
756 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700757 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
758}
759
Ana Krulecb9afd792020-06-11 13:16:15 -0700760RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
761 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100762 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700763 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
764 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
765
766 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
767 // the min allowed refresh rate is higher than the device min, we do not want to enable the
768 // timer.
769 if (deviceMin < minByPolicy) {
770 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
771 }
772 if (minByPolicy == maxByPolicy) {
773 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
774 // max are all the same. This saves us extra unnecessary calls to sysprop.
775 if (deviceMin == minByPolicy) {
776 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
777 }
778 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
779 }
780 // Turn on the timer in all other cases.
781 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
782}
783
Ady Abraham62a0be22020-12-08 16:54:10 -0800784int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700785 // This calculation needs to be in sync with the java code
786 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
787 constexpr float kThreshold = 0.1f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800788 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700789 const auto numPeriodsRounded = std::round(numPeriods);
790 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800791 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700792 }
793
Ady Abraham62f216c2020-10-13 19:07:23 -0700794 return static_cast<int>(numPeriodsRounded);
795}
796
Ady Abraham62a0be22020-12-08 16:54:10 -0800797int RefreshRateConfigs::getRefreshRateDivider(Fps frameRate) const {
Ady Abraham62f216c2020-10-13 19:07:23 -0700798 std::lock_guard lock(mLock);
Ady Abraham62a0be22020-12-08 16:54:10 -0800799 return getFrameRateDivider(mCurrentRefreshRate->getFps(), frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700800}
801
Marin Shalamanovba421a82020-11-10 21:49:26 +0100802void RefreshRateConfigs::dump(std::string& result) const {
803 std::lock_guard lock(mLock);
804 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (DisplayManager): %s\n\n",
805 mDisplayManagerPolicy.toString().c_str());
806 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
807 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
808 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (Override): %s\n\n",
809 currentPolicy.toString().c_str());
810 }
811
812 auto config = mCurrentRefreshRate->hwcConfig;
813 base::StringAppendF(&result, "Current config: %s\n", mCurrentRefreshRate->toString().c_str());
814
815 result.append("Refresh rates:\n");
816 for (const auto& [id, refreshRate] : mRefreshRates) {
817 config = refreshRate->hwcConfig;
818 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
819 }
820
Ady Abraham64c2fc02020-12-29 12:07:50 -0800821 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
822 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100823 result.append("\n");
824}
825
Ady Abraham2139f732019-11-13 18:56:40 -0800826} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100827
828// TODO(b/129481165): remove the #pragma below and fix conversion issues
829#pragma clang diagnostic pop // ignored "-Wextra"