blob: b02596ac535325277f2fbe95bdc6efaec7a30f29 [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(
492 std::optional<HwcConfigIndexType> 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
Ady Abraham2139f732019-11-13 18:56:40 -0800557void RefreshRateConfigs::setCurrentConfigId(HwcConfigIndexType configId) {
558 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 Shalamanov3ea1d602020-12-16 19:59:39 +0100562RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& configs,
563 HwcConfigIndexType currentConfigId)
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700564 : mKnownFrameRates(constructKnownFrameRates(configs)) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100565 updateDisplayConfigs(configs, currentConfigId);
566}
567
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100568void RefreshRateConfigs::updateDisplayConfigs(const DisplayModes& configs,
569 HwcConfigIndexType currentConfigId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100570 std::lock_guard lock(mLock);
Ady Abrahamabc27602020-04-08 17:20:29 -0700571 LOG_ALWAYS_FATAL_IF(configs.empty());
572 LOG_ALWAYS_FATAL_IF(currentConfigId.value() >= configs.size());
573
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100574 mRefreshRates.clear();
Ady Abrahamabc27602020-04-08 17:20:29 -0700575 for (auto configId = HwcConfigIndexType(0); configId.value() < configs.size(); configId++) {
576 const auto& config = configs.at(static_cast<size_t>(configId.value()));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100577 const auto fps = Fps::fromPeriodNsecs(config->getVsyncPeriod());
Ady Abrahamabc27602020-04-08 17:20:29 -0700578 mRefreshRates.emplace(configId,
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100579 std::make_unique<RefreshRate>(configId, config, fps,
Ady Abrahamabc27602020-04-08 17:20:29 -0700580 RefreshRate::ConstructorTag(0)));
581 if (configId == currentConfigId) {
582 mCurrentRefreshRate = mRefreshRates.at(configId).get();
583 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800584 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700585
586 std::vector<const RefreshRate*> sortedConfigs;
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100587 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedConfigs);
Ady Abrahamabc27602020-04-08 17:20:29 -0700588 mDisplayManagerPolicy.defaultConfig = currentConfigId;
589 mMinSupportedRefreshRate = sortedConfigs.front();
590 mMaxSupportedRefreshRate = sortedConfigs.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800591
592 mSupportsFrameRateOverride = false;
Ady Abraham4899ff82021-01-06 13:53:29 -0800593 if (android::sysprop::enable_frame_rate_override(true)) {
594 for (const auto& config1 : sortedConfigs) {
595 for (const auto& config2 : sortedConfigs) {
596 if (getFrameRateDivider(config1->getFps(), config2->getFps()) >= 2) {
597 mSupportsFrameRateOverride = true;
598 break;
599 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800600 }
601 }
602 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800603
Ady Abrahamabc27602020-04-08 17:20:29 -0700604 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800605}
606
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100607bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Steven Thomasd4071902020-03-24 16:02:53 -0700608 // defaultConfig must be a valid config, and within the given refresh rate range.
609 auto iter = mRefreshRates.find(policy.defaultConfig);
610 if (iter == mRefreshRates.end()) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100611 ALOGE("Default config is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700612 return false;
613 }
614 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700615 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100616 ALOGE("Default config is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700617 return false;
618 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100619 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
620 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700621}
622
623status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800624 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100625 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100626 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100627 return BAD_VALUE;
628 }
Steven Thomasd4071902020-03-24 16:02:53 -0700629 Policy previousPolicy = *getCurrentPolicyLocked();
630 mDisplayManagerPolicy = policy;
631 if (*getCurrentPolicyLocked() == previousPolicy) {
632 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100633 }
Ady Abraham2139f732019-11-13 18:56:40 -0800634 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100635 return NO_ERROR;
636}
637
Steven Thomasd4071902020-03-24 16:02:53 -0700638status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100639 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100640 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700641 return BAD_VALUE;
642 }
643 Policy previousPolicy = *getCurrentPolicyLocked();
644 mOverridePolicy = policy;
645 if (*getCurrentPolicyLocked() == previousPolicy) {
646 return CURRENT_POLICY_UNCHANGED;
647 }
648 constructAvailableRefreshRates();
649 return NO_ERROR;
650}
651
652const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
653 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
654}
655
656RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
657 std::lock_guard lock(mLock);
658 return *getCurrentPolicyLocked();
659}
660
661RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
662 std::lock_guard lock(mLock);
663 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100664}
665
666bool RefreshRateConfigs::isConfigAllowed(HwcConfigIndexType config) const {
667 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700668 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100669 if (refreshRate->configId == config) {
670 return true;
671 }
672 }
673 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800674}
675
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100676void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800677 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
678 std::vector<const RefreshRate*>* outRefreshRates) {
679 outRefreshRates->clear();
680 outRefreshRates->reserve(mRefreshRates.size());
681 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800682 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100683 ALOGV("getSortedRefreshRateListLocked: config %zu added to list policy",
Ady Abraham2e1dd892020-03-05 13:48:36 -0800684 refreshRate->configId.value());
685 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800686 }
687 }
688
689 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
690 [](const auto refreshRate1, const auto refreshRate2) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700691 if (refreshRate1->hwcConfig->getVsyncPeriod() !=
692 refreshRate2->hwcConfig->getVsyncPeriod()) {
693 return refreshRate1->hwcConfig->getVsyncPeriod() >
694 refreshRate2->hwcConfig->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700695 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -0700696 return refreshRate1->hwcConfig->getConfigGroup() >
697 refreshRate2->hwcConfig->getConfigGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700698 }
Ady Abraham2139f732019-11-13 18:56:40 -0800699 });
700}
701
702void RefreshRateConfigs::constructAvailableRefreshRates() {
703 // Filter configs based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700704 const Policy* policy = getCurrentPolicyLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700705 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig)->hwcConfig;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100706 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700707
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100708 auto filterRefreshRates = [&](Fps min, Fps max, const char* listName,
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100709 std::vector<const RefreshRate*>*
710 outRefreshRates) REQUIRES(mLock) {
711 getSortedRefreshRateListLocked(
Steven Thomasf734df42020-04-13 21:09:28 -0700712 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
713 const auto& hwcConfig = refreshRate.hwcConfig;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800714
Steven Thomasf734df42020-04-13 21:09:28 -0700715 return hwcConfig->getHeight() == defaultConfig->getHeight() &&
716 hwcConfig->getWidth() == defaultConfig->getWidth() &&
717 hwcConfig->getDpiX() == defaultConfig->getDpiX() &&
718 hwcConfig->getDpiY() == defaultConfig->getDpiY() &&
719 (policy->allowGroupSwitching ||
720 hwcConfig->getConfigGroup() == defaultConfig->getConfigGroup()) &&
721 refreshRate.inPolicy(min, max);
722 },
723 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800724
Steven Thomasf734df42020-04-13 21:09:28 -0700725 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100726 "No matching configs for %s range: min=%s max=%s", listName,
727 to_string(min).c_str(), to_string(max).c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700728 auto stringifyRefreshRates = [&]() -> std::string {
729 std::string str;
730 for (auto refreshRate : *outRefreshRates) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100731 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700732 }
733 return str;
734 };
735 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
736 };
737
738 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
739 &mPrimaryRefreshRates);
740 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
741 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800742}
743
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100744Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
745 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700746 return *mKnownFrameRates.begin();
747 }
748
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100749 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700750 return *std::prev(mKnownFrameRates.end());
751 }
752
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100753 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
754 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700755
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100756 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
757 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700758 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
759}
760
Ana Krulecb9afd792020-06-11 13:16:15 -0700761RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
762 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100763 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700764 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
765 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
766
767 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
768 // the min allowed refresh rate is higher than the device min, we do not want to enable the
769 // timer.
770 if (deviceMin < minByPolicy) {
771 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
772 }
773 if (minByPolicy == maxByPolicy) {
774 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
775 // max are all the same. This saves us extra unnecessary calls to sysprop.
776 if (deviceMin == minByPolicy) {
777 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
778 }
779 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
780 }
781 // Turn on the timer in all other cases.
782 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
783}
784
Ady Abraham62a0be22020-12-08 16:54:10 -0800785int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700786 // This calculation needs to be in sync with the java code
787 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
788 constexpr float kThreshold = 0.1f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800789 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700790 const auto numPeriodsRounded = std::round(numPeriods);
791 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800792 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700793 }
794
Ady Abraham62f216c2020-10-13 19:07:23 -0700795 return static_cast<int>(numPeriodsRounded);
796}
797
Ady Abraham62a0be22020-12-08 16:54:10 -0800798int RefreshRateConfigs::getRefreshRateDivider(Fps frameRate) const {
Ady Abraham62f216c2020-10-13 19:07:23 -0700799 std::lock_guard lock(mLock);
Ady Abraham62a0be22020-12-08 16:54:10 -0800800 return getFrameRateDivider(mCurrentRefreshRate->getFps(), frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700801}
802
Marin Shalamanovba421a82020-11-10 21:49:26 +0100803void RefreshRateConfigs::dump(std::string& result) const {
804 std::lock_guard lock(mLock);
805 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (DisplayManager): %s\n\n",
806 mDisplayManagerPolicy.toString().c_str());
807 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
808 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
809 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (Override): %s\n\n",
810 currentPolicy.toString().c_str());
811 }
812
813 auto config = mCurrentRefreshRate->hwcConfig;
814 base::StringAppendF(&result, "Current config: %s\n", mCurrentRefreshRate->toString().c_str());
815
816 result.append("Refresh rates:\n");
817 for (const auto& [id, refreshRate] : mRefreshRates) {
818 config = refreshRate->hwcConfig;
819 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
820 }
821
Ady Abraham64c2fc02020-12-29 12:07:50 -0800822 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
823 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100824 result.append("\n");
825}
826
Ady Abraham2139f732019-11-13 18:56:40 -0800827} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100828
829// TODO(b/129481165): remove the #pragma below and fix conversion issues
830#pragma clang diagnostic pop // ignored "-Wextra"