blob: 81ffe0f20e94a6345d0795cbb9aea394a8d8753b [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";
Ady Abrahamdd5bfa92021-01-07 17:56:08 -080086 case LayerVoteType::ExplicitExact:
87 return "ExplicitExact";
Ady Abrahama6b676e2020-05-27 14:29:09 -070088 }
89}
90
Marin Shalamanovb6674e72020-11-06 13:05:57 +010091std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +010092 return base::StringPrintf("default config ID: %zu, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010093 ", primary range: %s, app request range: %s",
94 defaultConfig.value(), allowGroupSwitching,
95 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020096}
97
Ady Abraham4ccdcb42020-02-11 17:34:34 -080098std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
99 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800100 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
101 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
102 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
103 quotient++;
104 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800105 }
106
Ady Abraham62a0be22020-12-08 16:54:10 -0800107 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800108}
109
Ady Abraham62a0be22020-12-08 16:54:10 -0800110float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
111 const RefreshRate& refreshRate,
112 bool isSeamlessSwitch) const {
113 // Slightly prefer seamless switches.
114 constexpr float kSeamedSwitchPenalty = 0.95f;
115 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
116
117 // If the layer wants Max, give higher score to the higher refresh rate
118 if (layer.vote == LayerVoteType::Max) {
119 const auto ratio =
120 refreshRate.fps.getValue() / mAppRequestRefreshRates.back()->fps.getValue();
121 // use ratio^2 to get a lower score the more we get further from peak
122 return ratio * ratio;
123 }
124
125 const auto displayPeriod = refreshRate.getVsyncPeriod();
126 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
127 if (layer.vote == LayerVoteType::ExplicitDefault) {
128 // Find the actual rate the layer will render, assuming
129 // that layerPeriod is the minimal time to render a frame
130 auto actualLayerPeriod = displayPeriod;
131 int multiplier = 1;
132 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
133 multiplier++;
134 actualLayerPeriod = displayPeriod * multiplier;
135 }
136 return std::min(1.0f,
137 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
138 }
139
140 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
141 layer.vote == LayerVoteType::Heuristic) {
142 // Calculate how many display vsyncs we need to present a single frame for this
143 // layer
144 const auto [displayFramesQuotient, displayFramesRemainder] =
145 getDisplayFrames(layerPeriod, displayPeriod);
146 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
147 if (displayFramesRemainder == 0) {
148 // Layer desired refresh rate matches the display rate.
149 return 1.0f * seamlessness;
150 }
151
152 if (displayFramesQuotient == 0) {
153 // Layer desired refresh rate is higher than the display rate.
154 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
155 (1.0f / (MAX_FRAMES_TO_FIT + 1));
156 }
157
158 // Layer desired refresh rate is lower than the display rate. Check how well it fits
159 // the cadence.
160 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
161 int iter = 2;
162 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
163 diff = diff - (displayPeriod - diff);
164 iter++;
165 }
166
167 return (1.0f / iter) * seamlessness;
168 }
169
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800170 if (layer.vote == LayerVoteType::ExplicitExact) {
171 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
172 if (mSupportsFrameRateOverride) {
173 // Since we support frame rate override, allow refresh rates which are
174 // multiples of the layer's request, as those apps would be throttled
175 // down to run at the desired refresh rate.
176 return divider > 0;
177 }
178
179 return divider == 1;
180 }
181
Ady Abraham62a0be22020-12-08 16:54:10 -0800182 return 0;
183}
184
185struct RefreshRateScore {
186 const RefreshRate* refreshRate;
187 float score;
188};
189
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100190RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
191 const GlobalSignals& globalSignals,
192 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800193 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200194 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800195
Ady Abrahamdfd62162020-06-10 16:11:56 -0700196 if (outSignalsConsidered) *outSignalsConsidered = {};
197 const auto setTouchConsidered = [&] {
198 if (outSignalsConsidered) {
199 outSignalsConsidered->touch = true;
200 }
201 };
202
203 const auto setIdleConsidered = [&] {
204 if (outSignalsConsidered) {
205 outSignalsConsidered->idle = true;
206 }
207 };
208
Ady Abraham8a82ba62020-01-17 12:43:17 -0800209 std::lock_guard lock(mLock);
210
211 int noVoteLayers = 0;
212 int minVoteLayers = 0;
213 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800214 int explicitDefaultVoteLayers = 0;
215 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800216 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800217 float maxExplicitWeight = 0;
Marin Shalamanov46084422020-10-13 12:33:42 +0200218 int seamedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800219 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800220 switch (layer.vote) {
221 case LayerVoteType::NoVote:
222 noVoteLayers++;
223 break;
224 case LayerVoteType::Min:
225 minVoteLayers++;
226 break;
227 case LayerVoteType::Max:
228 maxVoteLayers++;
229 break;
230 case LayerVoteType::ExplicitDefault:
231 explicitDefaultVoteLayers++;
232 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
233 break;
234 case LayerVoteType::ExplicitExactOrMultiple:
235 explicitExactOrMultipleVoteLayers++;
236 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
237 break;
238 case LayerVoteType::ExplicitExact:
239 explicitExact++;
240 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
241 break;
242 case LayerVoteType::Heuristic:
243 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800244 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200245
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100246 if (layer.seamlessness == Seamlessness::SeamedAndSeamless) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200247 seamedLayers++;
248 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800249 }
250
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800251 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
252 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700253
Steven Thomasf734df42020-04-13 21:09:28 -0700254 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
255 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700256 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700257 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700258 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700259 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800260 }
261
Alec Mouri11232a22020-05-14 18:06:25 -0700262 // If the primary range consists of a single refresh rate then we can only
263 // move out the of range if layers explicitly request a different refresh
264 // rate.
265 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100266 const bool primaryRangeIsSingleRate =
267 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700268
Ady Abrahamdfd62162020-06-10 16:11:56 -0700269 if (!globalSignals.touch && globalSignals.idle &&
270 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700271 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700272 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700273 return getMinRefreshRateByPolicyLocked();
274 }
275
Steven Thomasdebafed2020-05-18 17:30:35 -0700276 if (layers.empty() || noVoteLayers == layers.size()) {
277 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700278 }
279
Ady Abraham8a82ba62020-01-17 12:43:17 -0800280 // Only if all layers want Min we should return Min
281 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700282 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700283 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800284 }
285
Ady Abraham8a82ba62020-01-17 12:43:17 -0800286 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800287 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700288 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800289
Steven Thomasf734df42020-04-13 21:09:28 -0700290 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800291 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800292 }
293
Marin Shalamanov46084422020-10-13 12:33:42 +0200294 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig);
295
Ady Abraham8a82ba62020-01-17 12:43:17 -0800296 for (const auto& layer : layers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700297 ALOGV("Calculating score for %s (%s, weight %.2f)", layer.name.c_str(),
298 layerVoteTypeString(layer.vote).c_str(), layer.weight);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800299 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800300 continue;
301 }
302
Ady Abraham71c437d2020-01-31 15:56:57 -0800303 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800304
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800305 for (auto i = 0u; i < scores.size(); i++) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800306 const bool isSeamlessSwitch = scores[i].refreshRate->getConfigGroup() ==
307 mCurrentRefreshRate->getConfigGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200308
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100309 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
310 ALOGV("%s ignores %s to avoid non-seamless switch. Current config = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800311 formatLayerInfo(layer, weight).c_str(),
312 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100313 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200314 continue;
315 }
316
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100317 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
318 !layer.focused) {
319 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
320 " Current config = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800321 formatLayerInfo(layer, weight).c_str(),
322 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100323 mCurrentRefreshRate->toString().c_str());
324 continue;
325 }
326
327 // Layers with default seamlessness vote for the current config group if
328 // there are layers with seamlessness=SeamedAndSeamless and for the default
329 // config group otherwise. In second case, if the current config group is different
330 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
331 // disappeared.
332 const bool isInPolicyForDefault = seamedLayers > 0
Ady Abraham62a0be22020-12-08 16:54:10 -0800333 ? scores[i].refreshRate->getConfigGroup() ==
334 mCurrentRefreshRate->getConfigGroup()
335 : scores[i].refreshRate->getConfigGroup() == defaultConfig->getConfigGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100336
337 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault &&
338 !layer.focused) {
339 ALOGV("%s ignores %s. Current config = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800340 scores[i].refreshRate->toString().c_str(),
341 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200342 continue;
343 }
344
Ady Abraham62a0be22020-12-08 16:54:10 -0800345 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
346 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700347 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800348 !(layer.focused &&
349 (layer.vote == LayerVoteType::ExplicitDefault ||
350 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700351 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700352 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700353 continue;
354 }
355
Ady Abraham62a0be22020-12-08 16:54:10 -0800356 const auto layerScore =
357 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
358 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
359 scores[i].refreshRate->getName().c_str(), layerScore);
360 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800361 }
362 }
363
Ady Abraham34702102020-02-10 14:12:05 -0800364 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
365 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
366 // or the lower otherwise.
367 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
368 ? getBestRefreshRate(scores.rbegin(), scores.rend())
369 : getBestRefreshRate(scores.begin(), scores.end());
370
Alec Mouri11232a22020-05-14 18:06:25 -0700371 if (primaryRangeIsSingleRate) {
372 // If we never scored any layers, then choose the rate from the primary
373 // range instead of picking a random score from the app range.
374 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800375 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700376 ALOGV("layers not scored - choose %s",
377 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700378 return getMaxRefreshRateByPolicyLocked();
379 } else {
380 return *bestRefreshRate;
381 }
382 }
383
Steven Thomasf734df42020-04-13 21:09:28 -0700384 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
385 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
386 // vote we should not change it if we get a touch event. Only apply touch boost if it will
387 // actually increase the refresh rate over the normal selection.
388 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700389
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800390 bool touchBoostForExplicitExact = explicitExact == 0 || mSupportsFrameRateOverride;
391 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100392 bestRefreshRate->fps.lessThanWithMargin(touchRefreshRate.fps)) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700393 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700394 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700395 return touchRefreshRate;
396 }
397
Ady Abrahamde7156e2020-02-28 17:29:39 -0800398 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800399}
400
Ady Abraham62a0be22020-12-08 16:54:10 -0800401std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
402groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
403 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
404 for (const auto& layer : layers) {
405 auto iter = layersByUid.emplace(layer.ownerUid,
406 std::vector<const RefreshRateConfigs::LayerRequirement*>());
407 auto& layersWithSameUid = iter.first->second;
408 layersWithSameUid.push_back(&layer);
409 }
410
411 // Remove uids that can't have a frame rate override
412 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
413 const auto& layersWithSameUid = iter->second;
414 bool skipUid = false;
415 for (const auto& layer : layersWithSameUid) {
416 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
417 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
418 skipUid = true;
419 break;
420 }
421 }
422 if (skipUid) {
423 iter = layersByUid.erase(iter);
424 } else {
425 ++iter;
426 }
427 }
428
429 return layersByUid;
430}
431
432std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
433 const AllRefreshRatesMapType& refreshRates) {
434 std::vector<RefreshRateScore> scores;
435 scores.reserve(refreshRates.size());
436 for (const auto& [ignored, refreshRate] : refreshRates) {
437 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
438 }
439 std::sort(scores.begin(), scores.end(),
440 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
441 return scores;
442}
443
444RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800445 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800446 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800447 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800448
Ady Abraham64c2fc02020-12-29 12:07:50 -0800449 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800450 std::lock_guard lock(mLock);
451 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
452 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
453 groupLayersByUid(layers);
454 UidToFrameRateOverride frameRateOverrides;
455 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800456 // Layers with ExplicitExactOrMultiple expect touch boost
457 const bool hasExplicitExactOrMultiple =
458 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
459 [](const auto& layer) {
460 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
461 });
462
463 if (touch && hasExplicitExactOrMultiple) {
464 continue;
465 }
466
Ady Abraham62a0be22020-12-08 16:54:10 -0800467 for (auto& score : scores) {
468 score.score = 0;
469 }
470
471 for (const auto& layer : layersWithSameUid) {
472 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
473 continue;
474 }
475
476 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800477 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
478 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800479 for (RefreshRateScore& score : scores) {
480 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
481 /*isSeamlessSwitch*/ true);
482 score.score += layer->weight * layerScore;
483 }
484 }
485
486 // We just care about the refresh rates which are a divider of the
487 // display refresh rate
488 auto iter =
489 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
490 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
491 });
492 scores.erase(iter, scores.end());
493
494 // If we never scored any layers, we don't have a preferred frame rate
495 if (std::all_of(scores.begin(), scores.end(),
496 [](const RefreshRateScore& score) { return score.score == 0; })) {
497 continue;
498 }
499
500 // Now that we scored all the refresh rates we need to pick the one that got the highest
501 // score.
502 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
503
504 // If the nest refresh rate is the current one, we don't have an override
505 if (!bestRefreshRate->getFps().equalsWithMargin(displayFrameRate)) {
506 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
507 }
508 }
509
510 return frameRateOverrides;
511}
512
Ady Abraham34702102020-02-10 14:12:05 -0800513template <typename Iter>
514const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800515 constexpr auto EPSILON = 0.001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800516 const RefreshRate* bestRefreshRate = begin->refreshRate;
517 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800518 for (auto i = begin; i != end; ++i) {
519 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100520 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800521
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100522 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800523
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800524 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800525 max = score;
526 bestRefreshRate = refreshRate;
527 }
528 }
529
Ady Abraham34702102020-02-10 14:12:05 -0800530 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800531}
532
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100533std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100534 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800535 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100536
537 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
538 : *mCurrentRefreshRate;
539 const auto& min = *mMinSupportedRefreshRate;
540
541 if (current != min) {
542 const auto& refreshRate = timerExpired ? min : current;
543 return refreshRate.getFps();
544 }
545
546 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700547}
548
549const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200550 for (auto refreshRate : mPrimaryRefreshRates) {
551 if (mCurrentRefreshRate->getConfigGroup() == refreshRate->getConfigGroup()) {
552 return *refreshRate;
553 }
554 }
555 ALOGE("Can't find min refresh rate by policy with the same config group"
556 " as the current config %s",
557 mCurrentRefreshRate->toString().c_str());
558 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700559 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800560}
561
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100562RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800563 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700564 return getMaxRefreshRateByPolicyLocked();
565}
566
567const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200568 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
569 const auto& refreshRate = (**it);
570 if (mCurrentRefreshRate->getConfigGroup() == refreshRate.getConfigGroup()) {
571 return refreshRate;
572 }
573 }
574 ALOGE("Can't find max refresh rate by policy with the same config group"
575 " as the current config %s",
576 mCurrentRefreshRate->toString().c_str());
577 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700578 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800579}
580
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100581RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800582 std::lock_guard lock(mLock);
583 return *mCurrentRefreshRate;
584}
585
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100586RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800587 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800588 return getCurrentRefreshRateByPolicyLocked();
589}
590
591const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700592 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
593 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800594 return *mCurrentRefreshRate;
595 }
Steven Thomasd4071902020-03-24 16:02:53 -0700596 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultConfig);
Ana Krulec5d477912020-02-07 12:02:38 -0800597}
598
Marin Shalamanov23c44202020-12-22 19:09:20 +0100599void RefreshRateConfigs::setCurrentConfigId(DisplayModeId configId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800600 std::lock_guard lock(mLock);
Ady Abraham2e1dd892020-03-05 13:48:36 -0800601 mCurrentRefreshRate = mRefreshRates.at(configId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800602}
603
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800604RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& configs, DisplayModeId currentConfigId,
605 bool enableFrameRateOverride)
606 : mKnownFrameRates(constructKnownFrameRates(configs)),
607 mEnableFrameRateOverride(enableFrameRateOverride) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100608 updateDisplayConfigs(configs, currentConfigId);
609}
610
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100611void RefreshRateConfigs::updateDisplayConfigs(const DisplayModes& configs,
Marin Shalamanov23c44202020-12-22 19:09:20 +0100612 DisplayModeId currentConfigId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100613 std::lock_guard lock(mLock);
Ady Abrahamabc27602020-04-08 17:20:29 -0700614 LOG_ALWAYS_FATAL_IF(configs.empty());
615 LOG_ALWAYS_FATAL_IF(currentConfigId.value() >= configs.size());
616
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100617 mRefreshRates.clear();
Marin Shalamanov23c44202020-12-22 19:09:20 +0100618 for (const auto& config : configs) {
619 const auto configId = config->getId();
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100620 const auto fps = Fps::fromPeriodNsecs(config->getVsyncPeriod());
Ady Abrahamabc27602020-04-08 17:20:29 -0700621 mRefreshRates.emplace(configId,
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100622 std::make_unique<RefreshRate>(configId, config, fps,
Ady Abrahamabc27602020-04-08 17:20:29 -0700623 RefreshRate::ConstructorTag(0)));
624 if (configId == currentConfigId) {
625 mCurrentRefreshRate = mRefreshRates.at(configId).get();
626 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800627 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700628
629 std::vector<const RefreshRate*> sortedConfigs;
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100630 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedConfigs);
Ady Abrahamabc27602020-04-08 17:20:29 -0700631 mDisplayManagerPolicy.defaultConfig = currentConfigId;
632 mMinSupportedRefreshRate = sortedConfigs.front();
633 mMaxSupportedRefreshRate = sortedConfigs.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800634
635 mSupportsFrameRateOverride = false;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800636 if (mEnableFrameRateOverride) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800637 for (const auto& config1 : sortedConfigs) {
638 for (const auto& config2 : sortedConfigs) {
639 if (getFrameRateDivider(config1->getFps(), config2->getFps()) >= 2) {
640 mSupportsFrameRateOverride = true;
641 break;
642 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800643 }
644 }
645 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800646
Ady Abrahamabc27602020-04-08 17:20:29 -0700647 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800648}
649
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100650bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Steven Thomasd4071902020-03-24 16:02:53 -0700651 // defaultConfig must be a valid config, and within the given refresh rate range.
652 auto iter = mRefreshRates.find(policy.defaultConfig);
653 if (iter == mRefreshRates.end()) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100654 ALOGE("Default config is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700655 return false;
656 }
657 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700658 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100659 ALOGE("Default config is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700660 return false;
661 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100662 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
663 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700664}
665
666status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800667 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100668 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100669 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100670 return BAD_VALUE;
671 }
Steven Thomasd4071902020-03-24 16:02:53 -0700672 Policy previousPolicy = *getCurrentPolicyLocked();
673 mDisplayManagerPolicy = policy;
674 if (*getCurrentPolicyLocked() == previousPolicy) {
675 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100676 }
Ady Abraham2139f732019-11-13 18:56:40 -0800677 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100678 return NO_ERROR;
679}
680
Steven Thomasd4071902020-03-24 16:02:53 -0700681status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100682 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100683 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700684 return BAD_VALUE;
685 }
686 Policy previousPolicy = *getCurrentPolicyLocked();
687 mOverridePolicy = policy;
688 if (*getCurrentPolicyLocked() == previousPolicy) {
689 return CURRENT_POLICY_UNCHANGED;
690 }
691 constructAvailableRefreshRates();
692 return NO_ERROR;
693}
694
695const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
696 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
697}
698
699RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
700 std::lock_guard lock(mLock);
701 return *getCurrentPolicyLocked();
702}
703
704RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
705 std::lock_guard lock(mLock);
706 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100707}
708
Marin Shalamanov23c44202020-12-22 19:09:20 +0100709bool RefreshRateConfigs::isConfigAllowed(DisplayModeId config) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100710 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700711 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100712 if (refreshRate->configId == config) {
713 return true;
714 }
715 }
716 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800717}
718
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100719void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800720 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
721 std::vector<const RefreshRate*>* outRefreshRates) {
722 outRefreshRates->clear();
723 outRefreshRates->reserve(mRefreshRates.size());
724 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800725 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +0100726 ALOGV("getSortedRefreshRateListLocked: config %zu added to list policy",
Ady Abraham2e1dd892020-03-05 13:48:36 -0800727 refreshRate->configId.value());
728 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800729 }
730 }
731
732 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
733 [](const auto refreshRate1, const auto refreshRate2) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700734 if (refreshRate1->hwcConfig->getVsyncPeriod() !=
735 refreshRate2->hwcConfig->getVsyncPeriod()) {
736 return refreshRate1->hwcConfig->getVsyncPeriod() >
737 refreshRate2->hwcConfig->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700738 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -0700739 return refreshRate1->hwcConfig->getConfigGroup() >
740 refreshRate2->hwcConfig->getConfigGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700741 }
Ady Abraham2139f732019-11-13 18:56:40 -0800742 });
743}
744
745void RefreshRateConfigs::constructAvailableRefreshRates() {
746 // Filter configs based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700747 const Policy* policy = getCurrentPolicyLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700748 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig)->hwcConfig;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100749 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700750
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100751 auto filterRefreshRates = [&](Fps min, Fps max, const char* listName,
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100752 std::vector<const RefreshRate*>*
753 outRefreshRates) REQUIRES(mLock) {
754 getSortedRefreshRateListLocked(
Steven Thomasf734df42020-04-13 21:09:28 -0700755 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
756 const auto& hwcConfig = refreshRate.hwcConfig;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800757
Steven Thomasf734df42020-04-13 21:09:28 -0700758 return hwcConfig->getHeight() == defaultConfig->getHeight() &&
759 hwcConfig->getWidth() == defaultConfig->getWidth() &&
760 hwcConfig->getDpiX() == defaultConfig->getDpiX() &&
761 hwcConfig->getDpiY() == defaultConfig->getDpiY() &&
762 (policy->allowGroupSwitching ||
763 hwcConfig->getConfigGroup() == defaultConfig->getConfigGroup()) &&
764 refreshRate.inPolicy(min, max);
765 },
766 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800767
Steven Thomasf734df42020-04-13 21:09:28 -0700768 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100769 "No matching configs for %s range: min=%s max=%s", listName,
770 to_string(min).c_str(), to_string(max).c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700771 auto stringifyRefreshRates = [&]() -> std::string {
772 std::string str;
773 for (auto refreshRate : *outRefreshRates) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100774 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700775 }
776 return str;
777 };
778 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
779 };
780
781 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
782 &mPrimaryRefreshRates);
783 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
784 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800785}
786
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100787Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
788 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700789 return *mKnownFrameRates.begin();
790 }
791
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100792 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700793 return *std::prev(mKnownFrameRates.end());
794 }
795
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100796 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
797 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700798
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100799 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
800 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700801 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
802}
803
Ana Krulecb9afd792020-06-11 13:16:15 -0700804RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
805 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100806 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700807 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
808 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
809
810 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
811 // the min allowed refresh rate is higher than the device min, we do not want to enable the
812 // timer.
813 if (deviceMin < minByPolicy) {
814 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
815 }
816 if (minByPolicy == maxByPolicy) {
817 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
818 // max are all the same. This saves us extra unnecessary calls to sysprop.
819 if (deviceMin == minByPolicy) {
820 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
821 }
822 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
823 }
824 // Turn on the timer in all other cases.
825 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
826}
827
Ady Abraham62a0be22020-12-08 16:54:10 -0800828int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700829 // This calculation needs to be in sync with the java code
830 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
831 constexpr float kThreshold = 0.1f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800832 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700833 const auto numPeriodsRounded = std::round(numPeriods);
834 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800835 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700836 }
837
Ady Abraham62f216c2020-10-13 19:07:23 -0700838 return static_cast<int>(numPeriodsRounded);
839}
840
Ady Abraham62a0be22020-12-08 16:54:10 -0800841int RefreshRateConfigs::getRefreshRateDivider(Fps frameRate) const {
Ady Abraham62f216c2020-10-13 19:07:23 -0700842 std::lock_guard lock(mLock);
Ady Abraham62a0be22020-12-08 16:54:10 -0800843 return getFrameRateDivider(mCurrentRefreshRate->getFps(), frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700844}
845
Marin Shalamanovba421a82020-11-10 21:49:26 +0100846void RefreshRateConfigs::dump(std::string& result) const {
847 std::lock_guard lock(mLock);
848 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (DisplayManager): %s\n\n",
849 mDisplayManagerPolicy.toString().c_str());
850 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
851 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
852 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (Override): %s\n\n",
853 currentPolicy.toString().c_str());
854 }
855
856 auto config = mCurrentRefreshRate->hwcConfig;
857 base::StringAppendF(&result, "Current config: %s\n", mCurrentRefreshRate->toString().c_str());
858
859 result.append("Refresh rates:\n");
860 for (const auto& [id, refreshRate] : mRefreshRates) {
861 config = refreshRate->hwcConfig;
862 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
863 }
864
Ady Abraham64c2fc02020-12-29 12:07:50 -0800865 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
866 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100867 result.append("\n");
868}
869
Ady Abraham2139f732019-11-13 18:56:40 -0800870} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100871
872// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800873#pragma clang diagnostic pop // ignored "-Wextra"