blob: 200701209be25317f1323c253604a85502092fb9 [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>
29
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080030#undef LOG_TAG
31#define LOG_TAG "RefreshRateConfigs"
32
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080033namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010034namespace {
35std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010036 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010037 RefreshRateConfigs::layerVoteTypeString(layer.vote).c_str(), weight,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010038 toString(layer.seamlessness).c_str(),
39 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010040}
41} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080042
43using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080044using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080045
Marin Shalamanov46084422020-10-13 12:33:42 +020046std::string RefreshRate::toString() const {
47 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanove8a663d2020-11-24 17:48:00 +010048 getConfigId().value(), hwcConfig->getId(), getFps().getValue(),
Marin Shalamanov46084422020-10-13 12:33:42 +020049 hwcConfig->getWidth(), hwcConfig->getHeight(), getConfigGroup());
50}
51
Ady Abrahama6b676e2020-05-27 14:29:09 -070052std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
53 switch (vote) {
54 case LayerVoteType::NoVote:
55 return "NoVote";
56 case LayerVoteType::Min:
57 return "Min";
58 case LayerVoteType::Max:
59 return "Max";
60 case LayerVoteType::Heuristic:
61 return "Heuristic";
62 case LayerVoteType::ExplicitDefault:
63 return "ExplicitDefault";
64 case LayerVoteType::ExplicitExactOrMultiple:
65 return "ExplicitExactOrMultiple";
66 }
67}
68
Marin Shalamanovb6674e72020-11-06 13:05:57 +010069std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020070 return base::StringPrintf("default config ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010071 ", primary range: %s, app request range: %s",
72 defaultConfig.value(), allowGroupSwitching,
73 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020074}
75
Ady Abraham4ccdcb42020-02-11 17:34:34 -080076std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
77 nsecs_t displayPeriod) const {
Ady Abraham2c6716b2020-12-08 16:54:10 -080078 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
79 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
80 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
81 quotient++;
82 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -080083 }
84
Ady Abraham2c6716b2020-12-08 16:54:10 -080085 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -080086}
87
Ady Abraham2c6716b2020-12-08 16:54:10 -080088float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
89 const RefreshRate& refreshRate,
90 bool isSeamlessSwitch) const {
91 // Slightly prefer seamless switches.
92 constexpr float kSeamedSwitchPenalty = 0.95f;
93 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
94
95 // If the layer wants Max, give higher score to the higher refresh rate
96 if (layer.vote == LayerVoteType::Max) {
97 const auto ratio =
98 refreshRate.fps.getValue() / mAppRequestRefreshRates.back()->fps.getValue();
99 // use ratio^2 to get a lower score the more we get further from peak
100 return ratio * ratio;
101 }
102
103 const auto displayPeriod = refreshRate.getVsyncPeriod();
104 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
105 if (layer.vote == LayerVoteType::ExplicitDefault) {
106 // Find the actual rate the layer will render, assuming
107 // that layerPeriod is the minimal time to render a frame
108 auto actualLayerPeriod = displayPeriod;
109 int multiplier = 1;
110 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
111 multiplier++;
112 actualLayerPeriod = displayPeriod * multiplier;
113 }
114 return std::min(1.0f,
115 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
116 }
117
118 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
119 layer.vote == LayerVoteType::Heuristic) {
120 // Calculate how many display vsyncs we need to present a single frame for this
121 // layer
122 const auto [displayFramesQuotient, displayFramesRemainder] =
123 getDisplayFrames(layerPeriod, displayPeriod);
124 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
125 if (displayFramesRemainder == 0) {
126 // Layer desired refresh rate matches the display rate.
127 return 1.0f * seamlessness;
128 }
129
130 if (displayFramesQuotient == 0) {
131 // Layer desired refresh rate is higher than the display rate.
132 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
133 (1.0f / (MAX_FRAMES_TO_FIT + 1));
134 }
135
136 // Layer desired refresh rate is lower than the display rate. Check how well it fits
137 // the cadence.
138 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
139 int iter = 2;
140 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
141 diff = diff - (displayPeriod - diff);
142 iter++;
143 }
144
145 return (1.0f / iter) * seamlessness;
146 }
147
148 return 0;
149}
150
151struct RefreshRateScore {
152 const RefreshRate* refreshRate;
153 float score;
154};
155
Steven Thomasbb374322020-04-28 22:47:16 -0700156const RefreshRate& RefreshRateConfigs::getBestRefreshRate(
Ady Abrahamdfd62162020-06-10 16:11:56 -0700157 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
158 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800159 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200160 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800161
Ady Abrahamdfd62162020-06-10 16:11:56 -0700162 if (outSignalsConsidered) *outSignalsConsidered = {};
163 const auto setTouchConsidered = [&] {
164 if (outSignalsConsidered) {
165 outSignalsConsidered->touch = true;
166 }
167 };
168
169 const auto setIdleConsidered = [&] {
170 if (outSignalsConsidered) {
171 outSignalsConsidered->idle = true;
172 }
173 };
174
Ady Abraham8a82ba62020-01-17 12:43:17 -0800175 std::lock_guard lock(mLock);
176
177 int noVoteLayers = 0;
178 int minVoteLayers = 0;
179 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800180 int explicitDefaultVoteLayers = 0;
181 int explicitExactOrMultipleVoteLayers = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800182 float maxExplicitWeight = 0;
Marin Shalamanov46084422020-10-13 12:33:42 +0200183 int seamedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800184 for (const auto& layer : layers) {
Ady Abraham6fb599b2020-03-05 13:48:22 -0800185 if (layer.vote == LayerVoteType::NoVote) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800186 noVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800187 } else if (layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800188 minVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800189 } else if (layer.vote == LayerVoteType::Max) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800190 maxVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800191 } else if (layer.vote == LayerVoteType::ExplicitDefault) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800192 explicitDefaultVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800193 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
194 } else if (layer.vote == LayerVoteType::ExplicitExactOrMultiple) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800195 explicitExactOrMultipleVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800196 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
197 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200198
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100199 if (layer.seamlessness == Seamlessness::SeamedAndSeamless) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200200 seamedLayers++;
201 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800202 }
203
Alec Mouri11232a22020-05-14 18:06:25 -0700204 const bool hasExplicitVoteLayers =
205 explicitDefaultVoteLayers > 0 || explicitExactOrMultipleVoteLayers > 0;
206
Steven Thomasf734df42020-04-13 21:09:28 -0700207 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
208 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700209 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700210 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700211 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700212 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800213 }
214
Alec Mouri11232a22020-05-14 18:06:25 -0700215 // If the primary range consists of a single refresh rate then we can only
216 // move out the of range if layers explicitly request a different refresh
217 // rate.
218 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100219 const bool primaryRangeIsSingleRate =
220 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700221
Ady Abrahamdfd62162020-06-10 16:11:56 -0700222 if (!globalSignals.touch && globalSignals.idle &&
223 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700224 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700225 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700226 return getMinRefreshRateByPolicyLocked();
227 }
228
Steven Thomasdebafed2020-05-18 17:30:35 -0700229 if (layers.empty() || noVoteLayers == layers.size()) {
230 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700231 }
232
Ady Abraham8a82ba62020-01-17 12:43:17 -0800233 // Only if all layers want Min we should return Min
234 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700235 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700236 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800237 }
238
Ady Abraham8a82ba62020-01-17 12:43:17 -0800239 // Find the best refresh rate based on score
Ady Abraham2c6716b2020-12-08 16:54:10 -0800240 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700241 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800242
Steven Thomasf734df42020-04-13 21:09:28 -0700243 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham2c6716b2020-12-08 16:54:10 -0800244 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800245 }
246
Marin Shalamanov46084422020-10-13 12:33:42 +0200247 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig);
248
Ady Abraham8a82ba62020-01-17 12:43:17 -0800249 for (const auto& layer : layers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700250 ALOGV("Calculating score for %s (%s, weight %.2f)", layer.name.c_str(),
251 layerVoteTypeString(layer.vote).c_str(), layer.weight);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800252 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800253 continue;
254 }
255
Ady Abraham71c437d2020-01-31 15:56:57 -0800256 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800257
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800258 for (auto i = 0u; i < scores.size(); i++) {
Ady Abraham2c6716b2020-12-08 16:54:10 -0800259 const bool isSeamlessSwitch = scores[i].refreshRate->getConfigGroup() ==
260 mCurrentRefreshRate->getConfigGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200261
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100262 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
263 ALOGV("%s ignores %s to avoid non-seamless switch. Current config = %s",
Ady Abraham2c6716b2020-12-08 16:54:10 -0800264 formatLayerInfo(layer, weight).c_str(),
265 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100266 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200267 continue;
268 }
269
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100270 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
271 !layer.focused) {
272 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
273 " Current config = %s",
Ady Abraham2c6716b2020-12-08 16:54:10 -0800274 formatLayerInfo(layer, weight).c_str(),
275 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100276 mCurrentRefreshRate->toString().c_str());
277 continue;
278 }
279
280 // Layers with default seamlessness vote for the current config group if
281 // there are layers with seamlessness=SeamedAndSeamless and for the default
282 // config group otherwise. In second case, if the current config group is different
283 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
284 // disappeared.
285 const bool isInPolicyForDefault = seamedLayers > 0
Ady Abraham2c6716b2020-12-08 16:54:10 -0800286 ? scores[i].refreshRate->getConfigGroup() ==
287 mCurrentRefreshRate->getConfigGroup()
288 : scores[i].refreshRate->getConfigGroup() == defaultConfig->getConfigGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100289
290 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault &&
291 !layer.focused) {
292 ALOGV("%s ignores %s. Current config = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham2c6716b2020-12-08 16:54:10 -0800293 scores[i].refreshRate->toString().c_str(),
294 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200295 continue;
296 }
297
Ady Abraham2c6716b2020-12-08 16:54:10 -0800298 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
299 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700300 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abraham20c029c2020-07-06 12:58:05 -0700301 !(layer.focused && layer.vote == LayerVoteType::ExplicitDefault)) {
302 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700303 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700304 continue;
305 }
306
Ady Abraham2c6716b2020-12-08 16:54:10 -0800307 const auto layerScore =
308 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
309 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
310 scores[i].refreshRate->getName().c_str(), layerScore);
311 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800312 }
313 }
314
Ady Abraham34702102020-02-10 14:12:05 -0800315 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
316 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
317 // or the lower otherwise.
318 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
319 ? getBestRefreshRate(scores.rbegin(), scores.rend())
320 : getBestRefreshRate(scores.begin(), scores.end());
321
Alec Mouri11232a22020-05-14 18:06:25 -0700322 if (primaryRangeIsSingleRate) {
323 // If we never scored any layers, then choose the rate from the primary
324 // range instead of picking a random score from the app range.
325 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham2c6716b2020-12-08 16:54:10 -0800326 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700327 ALOGV("layers not scored - choose %s",
328 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700329 return getMaxRefreshRateByPolicyLocked();
330 } else {
331 return *bestRefreshRate;
332 }
333 }
334
Steven Thomasf734df42020-04-13 21:09:28 -0700335 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
336 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
337 // vote we should not change it if we get a touch event. Only apply touch boost if it will
338 // actually increase the refresh rate over the normal selection.
339 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700340
Ady Abrahamdfd62162020-06-10 16:11:56 -0700341 if (globalSignals.touch && explicitDefaultVoteLayers == 0 &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100342 bestRefreshRate->fps.lessThanWithMargin(touchRefreshRate.fps)) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700343 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700344 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700345 return touchRefreshRate;
346 }
347
Ady Abrahamde7156e2020-02-28 17:29:39 -0800348 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800349}
350
Ady Abraham2c6716b2020-12-08 16:54:10 -0800351std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
352groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
353 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
354 for (const auto& layer : layers) {
355 auto iter = layersByUid.emplace(layer.ownerUid,
356 std::vector<const RefreshRateConfigs::LayerRequirement*>());
357 auto& layersWithSameUid = iter.first->second;
358 layersWithSameUid.push_back(&layer);
359 }
360
361 // Remove uids that can't have a frame rate override
362 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
363 const auto& layersWithSameUid = iter->second;
364 bool skipUid = false;
365 for (const auto& layer : layersWithSameUid) {
366 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
367 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
368 skipUid = true;
369 break;
370 }
371 }
372 if (skipUid) {
373 iter = layersByUid.erase(iter);
374 } else {
375 ++iter;
376 }
377 }
378
379 return layersByUid;
380}
381
382std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
383 const AllRefreshRatesMapType& refreshRates) {
384 std::vector<RefreshRateScore> scores;
385 scores.reserve(refreshRates.size());
386 for (const auto& [ignored, refreshRate] : refreshRates) {
387 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
388 }
389 std::sort(scores.begin(), scores.end(),
390 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
391 return scores;
392}
393
394RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
395 const std::vector<LayerRequirement>& layers, Fps displayFrameRate) const {
396 ATRACE_CALL();
397 ALOGV("getFrameRateOverrides %zu layers", layers.size());
398
399 std::lock_guard lock(mLock);
400 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
401 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
402 groupLayersByUid(layers);
403 UidToFrameRateOverride frameRateOverrides;
404 for (const auto& [uid, layersWithSameUid] : layersByUid) {
405 for (auto& score : scores) {
406 score.score = 0;
407 }
408
409 for (const auto& layer : layersWithSameUid) {
410 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
411 continue;
412 }
413
414 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
415 layer->vote != LayerVoteType::ExplicitExactOrMultiple);
416 for (RefreshRateScore& score : scores) {
417 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
418 /*isSeamlessSwitch*/ true);
419 score.score += layer->weight * layerScore;
420 }
421 }
422
423 // We just care about the refresh rates which are a divider of the
424 // display refresh rate
425 auto iter =
426 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
427 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
428 });
429 scores.erase(iter, scores.end());
430
431 // If we never scored any layers, we don't have a preferred frame rate
432 if (std::all_of(scores.begin(), scores.end(),
433 [](const RefreshRateScore& score) { return score.score == 0; })) {
434 continue;
435 }
436
437 // Now that we scored all the refresh rates we need to pick the one that got the highest
438 // score.
439 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
440
441 // If the nest refresh rate is the current one, we don't have an override
442 if (!bestRefreshRate->getFps().equalsWithMargin(displayFrameRate)) {
443 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
444 }
445 }
446
447 return frameRateOverrides;
448}
449
Ady Abraham34702102020-02-10 14:12:05 -0800450template <typename Iter>
451const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800452 constexpr auto EPSILON = 0.001f;
Ady Abraham2c6716b2020-12-08 16:54:10 -0800453 const RefreshRate* bestRefreshRate = begin->refreshRate;
454 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800455 for (auto i = begin; i != end; ++i) {
456 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100457 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800458
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100459 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800460
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800461 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800462 max = score;
463 bestRefreshRate = refreshRate;
464 }
465 }
466
Ady Abraham34702102020-02-10 14:12:05 -0800467 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800468}
469
Ady Abraham2139f732019-11-13 18:56:40 -0800470const AllRefreshRatesMapType& RefreshRateConfigs::getAllRefreshRates() const {
471 return mRefreshRates;
472}
473
474const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicy() const {
475 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700476 return getMinRefreshRateByPolicyLocked();
477}
478
479const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200480 for (auto refreshRate : mPrimaryRefreshRates) {
481 if (mCurrentRefreshRate->getConfigGroup() == refreshRate->getConfigGroup()) {
482 return *refreshRate;
483 }
484 }
485 ALOGE("Can't find min refresh rate by policy with the same config group"
486 " as the current config %s",
487 mCurrentRefreshRate->toString().c_str());
488 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700489 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800490}
491
492const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
493 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700494 return getMaxRefreshRateByPolicyLocked();
495}
496
497const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200498 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
499 const auto& refreshRate = (**it);
500 if (mCurrentRefreshRate->getConfigGroup() == refreshRate.getConfigGroup()) {
501 return refreshRate;
502 }
503 }
504 ALOGE("Can't find max refresh rate by policy with the same config group"
505 " as the current config %s",
506 mCurrentRefreshRate->toString().c_str());
507 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700508 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800509}
510
511const RefreshRate& RefreshRateConfigs::getCurrentRefreshRate() const {
512 std::lock_guard lock(mLock);
513 return *mCurrentRefreshRate;
514}
515
Ana Krulec5d477912020-02-07 12:02:38 -0800516const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
517 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800518 return getCurrentRefreshRateByPolicyLocked();
519}
520
521const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700522 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
523 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800524 return *mCurrentRefreshRate;
525 }
Steven Thomasd4071902020-03-24 16:02:53 -0700526 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultConfig);
Ana Krulec5d477912020-02-07 12:02:38 -0800527}
528
Ady Abraham2139f732019-11-13 18:56:40 -0800529void RefreshRateConfigs::setCurrentConfigId(HwcConfigIndexType configId) {
530 std::lock_guard lock(mLock);
Ady Abraham2e1dd892020-03-05 13:48:36 -0800531 mCurrentRefreshRate = mRefreshRates.at(configId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800532}
533
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800534RefreshRateConfigs::RefreshRateConfigs(
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800535 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs,
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700536 HwcConfigIndexType currentConfigId)
537 : mKnownFrameRates(constructKnownFrameRates(configs)) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700538 LOG_ALWAYS_FATAL_IF(configs.empty());
539 LOG_ALWAYS_FATAL_IF(currentConfigId.value() >= configs.size());
540
541 for (auto configId = HwcConfigIndexType(0); configId.value() < configs.size(); configId++) {
542 const auto& config = configs.at(static_cast<size_t>(configId.value()));
Ady Abrahamabc27602020-04-08 17:20:29 -0700543 mRefreshRates.emplace(configId,
544 std::make_unique<RefreshRate>(configId, config,
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100545 Fps::fromPeriodNsecs(
546 config->getVsyncPeriod()),
Ady Abrahamabc27602020-04-08 17:20:29 -0700547 RefreshRate::ConstructorTag(0)));
548 if (configId == currentConfigId) {
549 mCurrentRefreshRate = mRefreshRates.at(configId).get();
550 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800551 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700552
553 std::vector<const RefreshRate*> sortedConfigs;
554 getSortedRefreshRateList([](const RefreshRate&) { return true; }, &sortedConfigs);
555 mDisplayManagerPolicy.defaultConfig = currentConfigId;
556 mMinSupportedRefreshRate = sortedConfigs.front();
557 mMaxSupportedRefreshRate = sortedConfigs.back();
558 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800559}
560
Steven Thomasd4071902020-03-24 16:02:53 -0700561bool RefreshRateConfigs::isPolicyValid(const Policy& policy) {
562 // defaultConfig must be a valid config, and within the given refresh rate range.
563 auto iter = mRefreshRates.find(policy.defaultConfig);
564 if (iter == mRefreshRates.end()) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100565 ALOGE("Default config is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700566 return false;
567 }
568 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700569 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100570 ALOGE("Default config is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700571 return false;
572 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100573 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
574 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700575}
576
577status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800578 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700579 if (!isPolicyValid(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100580 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100581 return BAD_VALUE;
582 }
Steven Thomasd4071902020-03-24 16:02:53 -0700583 Policy previousPolicy = *getCurrentPolicyLocked();
584 mDisplayManagerPolicy = policy;
585 if (*getCurrentPolicyLocked() == previousPolicy) {
586 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100587 }
Ady Abraham2139f732019-11-13 18:56:40 -0800588 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100589 return NO_ERROR;
590}
591
Steven Thomasd4071902020-03-24 16:02:53 -0700592status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100593 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700594 if (policy && !isPolicyValid(*policy)) {
595 return BAD_VALUE;
596 }
597 Policy previousPolicy = *getCurrentPolicyLocked();
598 mOverridePolicy = policy;
599 if (*getCurrentPolicyLocked() == previousPolicy) {
600 return CURRENT_POLICY_UNCHANGED;
601 }
602 constructAvailableRefreshRates();
603 return NO_ERROR;
604}
605
606const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
607 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
608}
609
610RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
611 std::lock_guard lock(mLock);
612 return *getCurrentPolicyLocked();
613}
614
615RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
616 std::lock_guard lock(mLock);
617 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100618}
619
620bool RefreshRateConfigs::isConfigAllowed(HwcConfigIndexType config) const {
621 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700622 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100623 if (refreshRate->configId == config) {
624 return true;
625 }
626 }
627 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800628}
629
630void RefreshRateConfigs::getSortedRefreshRateList(
631 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
632 std::vector<const RefreshRate*>* outRefreshRates) {
633 outRefreshRates->clear();
634 outRefreshRates->reserve(mRefreshRates.size());
635 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800636 if (shouldAddRefreshRate(*refreshRate)) {
Ady Abraham2139f732019-11-13 18:56:40 -0800637 ALOGV("getSortedRefreshRateList: config %d added to list policy",
Ady Abraham2e1dd892020-03-05 13:48:36 -0800638 refreshRate->configId.value());
639 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800640 }
641 }
642
643 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
644 [](const auto refreshRate1, const auto refreshRate2) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700645 if (refreshRate1->hwcConfig->getVsyncPeriod() !=
646 refreshRate2->hwcConfig->getVsyncPeriod()) {
647 return refreshRate1->hwcConfig->getVsyncPeriod() >
648 refreshRate2->hwcConfig->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700649 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -0700650 return refreshRate1->hwcConfig->getConfigGroup() >
651 refreshRate2->hwcConfig->getConfigGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700652 }
Ady Abraham2139f732019-11-13 18:56:40 -0800653 });
654}
655
656void RefreshRateConfigs::constructAvailableRefreshRates() {
657 // Filter configs based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700658 const Policy* policy = getCurrentPolicyLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700659 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig)->hwcConfig;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100660 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700661
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100662 auto filterRefreshRates = [&](Fps min, Fps max, const char* listName,
Steven Thomasf734df42020-04-13 21:09:28 -0700663 std::vector<const RefreshRate*>* outRefreshRates) {
664 getSortedRefreshRateList(
665 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
666 const auto& hwcConfig = refreshRate.hwcConfig;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800667
Steven Thomasf734df42020-04-13 21:09:28 -0700668 return hwcConfig->getHeight() == defaultConfig->getHeight() &&
669 hwcConfig->getWidth() == defaultConfig->getWidth() &&
670 hwcConfig->getDpiX() == defaultConfig->getDpiX() &&
671 hwcConfig->getDpiY() == defaultConfig->getDpiY() &&
672 (policy->allowGroupSwitching ||
673 hwcConfig->getConfigGroup() == defaultConfig->getConfigGroup()) &&
674 refreshRate.inPolicy(min, max);
675 },
676 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800677
Steven Thomasf734df42020-04-13 21:09:28 -0700678 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100679 "No matching configs for %s range: min=%s max=%s", listName,
680 to_string(min).c_str(), to_string(max).c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700681 auto stringifyRefreshRates = [&]() -> std::string {
682 std::string str;
683 for (auto refreshRate : *outRefreshRates) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100684 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700685 }
686 return str;
687 };
688 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
689 };
690
691 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
692 &mPrimaryRefreshRates);
693 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
694 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800695}
696
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100697std::vector<Fps> RefreshRateConfigs::constructKnownFrameRates(
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700698 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100699 std::vector<Fps> knownFrameRates = {Fps(24.0f), Fps(30.0f), Fps(45.0f), Fps(60.0f), Fps(72.0f)};
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700700 knownFrameRates.reserve(knownFrameRates.size() + configs.size());
701
702 // Add all supported refresh rates to the set
703 for (const auto& config : configs) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100704 const auto refreshRate = Fps::fromPeriodNsecs(config->getVsyncPeriod());
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700705 knownFrameRates.emplace_back(refreshRate);
706 }
707
708 // Sort and remove duplicates
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100709 std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700710 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100711 Fps::EqualsWithMargin()),
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700712 knownFrameRates.end());
713 return knownFrameRates;
714}
715
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100716Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
717 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700718 return *mKnownFrameRates.begin();
719 }
720
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100721 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700722 return *std::prev(mKnownFrameRates.end());
723 }
724
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100725 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
726 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700727
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100728 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
729 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700730 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
731}
732
Ana Krulecb9afd792020-06-11 13:16:15 -0700733RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
734 std::lock_guard lock(mLock);
735 const auto& deviceMin = getMinRefreshRate();
736 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
737 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
738
739 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
740 // the min allowed refresh rate is higher than the device min, we do not want to enable the
741 // timer.
742 if (deviceMin < minByPolicy) {
743 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
744 }
745 if (minByPolicy == maxByPolicy) {
746 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
747 // max are all the same. This saves us extra unnecessary calls to sysprop.
748 if (deviceMin == minByPolicy) {
749 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
750 }
751 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
752 }
753 // Turn on the timer in all other cases.
754 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
755}
756
Ady Abraham2c6716b2020-12-08 16:54:10 -0800757int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700758 // This calculation needs to be in sync with the java code
759 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
760 constexpr float kThreshold = 0.1f;
Ady Abraham2c6716b2020-12-08 16:54:10 -0800761 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700762 const auto numPeriodsRounded = std::round(numPeriods);
763 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham2c6716b2020-12-08 16:54:10 -0800764 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700765 }
766
Ady Abraham62f216c2020-10-13 19:07:23 -0700767 return static_cast<int>(numPeriodsRounded);
768}
769
Ady Abraham2c6716b2020-12-08 16:54:10 -0800770int RefreshRateConfigs::getRefreshRateDivider(Fps frameRate) const {
Ady Abraham62f216c2020-10-13 19:07:23 -0700771 std::lock_guard lock(mLock);
Ady Abraham2c6716b2020-12-08 16:54:10 -0800772 return getFrameRateDivider(mCurrentRefreshRate->getFps(), frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700773}
774
Marin Shalamanovba421a82020-11-10 21:49:26 +0100775void RefreshRateConfigs::dump(std::string& result) const {
776 std::lock_guard lock(mLock);
777 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (DisplayManager): %s\n\n",
778 mDisplayManagerPolicy.toString().c_str());
779 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
780 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
781 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (Override): %s\n\n",
782 currentPolicy.toString().c_str());
783 }
784
785 auto config = mCurrentRefreshRate->hwcConfig;
786 base::StringAppendF(&result, "Current config: %s\n", mCurrentRefreshRate->toString().c_str());
787
788 result.append("Refresh rates:\n");
789 for (const auto& [id, refreshRate] : mRefreshRates) {
790 config = refreshRate->hwcConfig;
791 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
792 }
793
794 result.append("\n");
795}
796
Ady Abraham2139f732019-11-13 18:56:40 -0800797} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100798
799// TODO(b/129481165): remove the #pragma below and fix conversion issues
800#pragma clang diagnostic pop // ignored "-Wextra"