blob: 35b382ed050cddfe530c1f01852777ed648ecb72 [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 Abraham62a0be22020-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 Abraham62a0be22020-12-08 16:54:10 -080085 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -080086}
87
Ady Abraham62a0be22020-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 Abraham62a0be22020-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 Abraham62a0be22020-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 Abraham62a0be22020-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 Abraham62a0be22020-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 Abraham62a0be22020-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 Abraham62a0be22020-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 Abraham62a0be22020-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 Abraham62a0be22020-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 Abraham62a0be22020-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 Abraham62a0be22020-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 Abraham62a0be22020-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();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800397 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800398
Ady Abraham64c2fc02020-12-29 12:07:50 -0800399 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800400 std::lock_guard lock(mLock);
401 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
402 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
403 groupLayersByUid(layers);
404 UidToFrameRateOverride frameRateOverrides;
405 for (const auto& [uid, layersWithSameUid] : layersByUid) {
406 for (auto& score : scores) {
407 score.score = 0;
408 }
409
410 for (const auto& layer : layersWithSameUid) {
411 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
412 continue;
413 }
414
415 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
416 layer->vote != LayerVoteType::ExplicitExactOrMultiple);
417 for (RefreshRateScore& score : scores) {
418 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
419 /*isSeamlessSwitch*/ true);
420 score.score += layer->weight * layerScore;
421 }
422 }
423
424 // We just care about the refresh rates which are a divider of the
425 // display refresh rate
426 auto iter =
427 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
428 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
429 });
430 scores.erase(iter, scores.end());
431
432 // If we never scored any layers, we don't have a preferred frame rate
433 if (std::all_of(scores.begin(), scores.end(),
434 [](const RefreshRateScore& score) { return score.score == 0; })) {
435 continue;
436 }
437
438 // Now that we scored all the refresh rates we need to pick the one that got the highest
439 // score.
440 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
441
442 // If the nest refresh rate is the current one, we don't have an override
443 if (!bestRefreshRate->getFps().equalsWithMargin(displayFrameRate)) {
444 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
445 }
446 }
447
448 return frameRateOverrides;
449}
450
Ady Abraham34702102020-02-10 14:12:05 -0800451template <typename Iter>
452const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800453 constexpr auto EPSILON = 0.001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800454 const RefreshRate* bestRefreshRate = begin->refreshRate;
455 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800456 for (auto i = begin; i != end; ++i) {
457 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100458 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800459
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100460 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800461
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800462 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800463 max = score;
464 bestRefreshRate = refreshRate;
465 }
466 }
467
Ady Abraham34702102020-02-10 14:12:05 -0800468 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800469}
470
Ady Abraham2139f732019-11-13 18:56:40 -0800471const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicy() const {
472 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700473 return getMinRefreshRateByPolicyLocked();
474}
475
476const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200477 for (auto refreshRate : mPrimaryRefreshRates) {
478 if (mCurrentRefreshRate->getConfigGroup() == refreshRate->getConfigGroup()) {
479 return *refreshRate;
480 }
481 }
482 ALOGE("Can't find min refresh rate by policy with the same config group"
483 " as the current config %s",
484 mCurrentRefreshRate->toString().c_str());
485 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700486 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800487}
488
489const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
490 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700491 return getMaxRefreshRateByPolicyLocked();
492}
493
494const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200495 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
496 const auto& refreshRate = (**it);
497 if (mCurrentRefreshRate->getConfigGroup() == refreshRate.getConfigGroup()) {
498 return refreshRate;
499 }
500 }
501 ALOGE("Can't find max refresh rate by policy with the same config group"
502 " as the current config %s",
503 mCurrentRefreshRate->toString().c_str());
504 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700505 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800506}
507
508const RefreshRate& RefreshRateConfigs::getCurrentRefreshRate() const {
509 std::lock_guard lock(mLock);
510 return *mCurrentRefreshRate;
511}
512
Ana Krulec5d477912020-02-07 12:02:38 -0800513const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
514 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800515 return getCurrentRefreshRateByPolicyLocked();
516}
517
518const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700519 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
520 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800521 return *mCurrentRefreshRate;
522 }
Steven Thomasd4071902020-03-24 16:02:53 -0700523 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultConfig);
Ana Krulec5d477912020-02-07 12:02:38 -0800524}
525
Ady Abraham2139f732019-11-13 18:56:40 -0800526void RefreshRateConfigs::setCurrentConfigId(HwcConfigIndexType configId) {
527 std::lock_guard lock(mLock);
Ady Abraham2e1dd892020-03-05 13:48:36 -0800528 mCurrentRefreshRate = mRefreshRates.at(configId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800529}
530
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800531RefreshRateConfigs::RefreshRateConfigs(
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800532 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs,
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700533 HwcConfigIndexType currentConfigId)
534 : mKnownFrameRates(constructKnownFrameRates(configs)) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700535 LOG_ALWAYS_FATAL_IF(configs.empty());
Marin Shalamanov6e840172020-12-14 22:13:28 +0100536 LOG_ALWAYS_FATAL_IF(currentConfigId.value() < 0);
Ady Abrahamabc27602020-04-08 17:20:29 -0700537 LOG_ALWAYS_FATAL_IF(currentConfigId.value() >= configs.size());
538
539 for (auto configId = HwcConfigIndexType(0); configId.value() < configs.size(); configId++) {
540 const auto& config = configs.at(static_cast<size_t>(configId.value()));
Ady Abrahamabc27602020-04-08 17:20:29 -0700541 mRefreshRates.emplace(configId,
542 std::make_unique<RefreshRate>(configId, config,
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100543 Fps::fromPeriodNsecs(
544 config->getVsyncPeriod()),
Ady Abrahamabc27602020-04-08 17:20:29 -0700545 RefreshRate::ConstructorTag(0)));
546 if (configId == currentConfigId) {
547 mCurrentRefreshRate = mRefreshRates.at(configId).get();
548 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800549 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700550
551 std::vector<const RefreshRate*> sortedConfigs;
552 getSortedRefreshRateList([](const RefreshRate&) { return true; }, &sortedConfigs);
553 mDisplayManagerPolicy.defaultConfig = currentConfigId;
554 mMinSupportedRefreshRate = sortedConfigs.front();
555 mMaxSupportedRefreshRate = sortedConfigs.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800556
557 mSupportsFrameRateOverride = false;
558 for (const auto& config1 : sortedConfigs) {
559 for (const auto& config2 : sortedConfigs) {
560 if (getFrameRateDivider(config1->getFps(), config2->getFps()) >= 2) {
561 mSupportsFrameRateOverride = true;
562 break;
563 }
564 }
565 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700566 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800567}
568
Steven Thomasd4071902020-03-24 16:02:53 -0700569bool RefreshRateConfigs::isPolicyValid(const Policy& policy) {
570 // defaultConfig must be a valid config, and within the given refresh rate range.
571 auto iter = mRefreshRates.find(policy.defaultConfig);
572 if (iter == mRefreshRates.end()) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100573 ALOGE("Default config is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700574 return false;
575 }
576 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700577 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100578 ALOGE("Default config is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700579 return false;
580 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100581 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
582 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700583}
584
585status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800586 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700587 if (!isPolicyValid(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100588 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100589 return BAD_VALUE;
590 }
Steven Thomasd4071902020-03-24 16:02:53 -0700591 Policy previousPolicy = *getCurrentPolicyLocked();
592 mDisplayManagerPolicy = policy;
593 if (*getCurrentPolicyLocked() == previousPolicy) {
594 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100595 }
Ady Abraham2139f732019-11-13 18:56:40 -0800596 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100597 return NO_ERROR;
598}
599
Steven Thomasd4071902020-03-24 16:02:53 -0700600status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100601 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700602 if (policy && !isPolicyValid(*policy)) {
603 return BAD_VALUE;
604 }
605 Policy previousPolicy = *getCurrentPolicyLocked();
606 mOverridePolicy = policy;
607 if (*getCurrentPolicyLocked() == previousPolicy) {
608 return CURRENT_POLICY_UNCHANGED;
609 }
610 constructAvailableRefreshRates();
611 return NO_ERROR;
612}
613
614const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
615 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
616}
617
618RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
619 std::lock_guard lock(mLock);
620 return *getCurrentPolicyLocked();
621}
622
623RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
624 std::lock_guard lock(mLock);
625 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100626}
627
628bool RefreshRateConfigs::isConfigAllowed(HwcConfigIndexType config) const {
629 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700630 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100631 if (refreshRate->configId == config) {
632 return true;
633 }
634 }
635 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800636}
637
638void RefreshRateConfigs::getSortedRefreshRateList(
639 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
640 std::vector<const RefreshRate*>* outRefreshRates) {
641 outRefreshRates->clear();
642 outRefreshRates->reserve(mRefreshRates.size());
643 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800644 if (shouldAddRefreshRate(*refreshRate)) {
Ady Abraham2139f732019-11-13 18:56:40 -0800645 ALOGV("getSortedRefreshRateList: config %d added to list policy",
Ady Abraham2e1dd892020-03-05 13:48:36 -0800646 refreshRate->configId.value());
647 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800648 }
649 }
650
651 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
652 [](const auto refreshRate1, const auto refreshRate2) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700653 if (refreshRate1->hwcConfig->getVsyncPeriod() !=
654 refreshRate2->hwcConfig->getVsyncPeriod()) {
655 return refreshRate1->hwcConfig->getVsyncPeriod() >
656 refreshRate2->hwcConfig->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700657 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -0700658 return refreshRate1->hwcConfig->getConfigGroup() >
659 refreshRate2->hwcConfig->getConfigGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700660 }
Ady Abraham2139f732019-11-13 18:56:40 -0800661 });
662}
663
664void RefreshRateConfigs::constructAvailableRefreshRates() {
665 // Filter configs based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700666 const Policy* policy = getCurrentPolicyLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700667 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig)->hwcConfig;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100668 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700669
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100670 auto filterRefreshRates = [&](Fps min, Fps max, const char* listName,
Steven Thomasf734df42020-04-13 21:09:28 -0700671 std::vector<const RefreshRate*>* outRefreshRates) {
672 getSortedRefreshRateList(
673 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
674 const auto& hwcConfig = refreshRate.hwcConfig;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800675
Steven Thomasf734df42020-04-13 21:09:28 -0700676 return hwcConfig->getHeight() == defaultConfig->getHeight() &&
677 hwcConfig->getWidth() == defaultConfig->getWidth() &&
678 hwcConfig->getDpiX() == defaultConfig->getDpiX() &&
679 hwcConfig->getDpiY() == defaultConfig->getDpiY() &&
680 (policy->allowGroupSwitching ||
681 hwcConfig->getConfigGroup() == defaultConfig->getConfigGroup()) &&
682 refreshRate.inPolicy(min, max);
683 },
684 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800685
Steven Thomasf734df42020-04-13 21:09:28 -0700686 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100687 "No matching configs for %s range: min=%s max=%s", listName,
688 to_string(min).c_str(), to_string(max).c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700689 auto stringifyRefreshRates = [&]() -> std::string {
690 std::string str;
691 for (auto refreshRate : *outRefreshRates) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100692 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700693 }
694 return str;
695 };
696 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
697 };
698
699 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
700 &mPrimaryRefreshRates);
701 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
702 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800703}
704
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100705std::vector<Fps> RefreshRateConfigs::constructKnownFrameRates(
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700706 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100707 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 -0700708 knownFrameRates.reserve(knownFrameRates.size() + configs.size());
709
710 // Add all supported refresh rates to the set
711 for (const auto& config : configs) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100712 const auto refreshRate = Fps::fromPeriodNsecs(config->getVsyncPeriod());
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700713 knownFrameRates.emplace_back(refreshRate);
714 }
715
716 // Sort and remove duplicates
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100717 std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700718 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100719 Fps::EqualsWithMargin()),
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700720 knownFrameRates.end());
721 return knownFrameRates;
722}
723
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100724Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
725 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700726 return *mKnownFrameRates.begin();
727 }
728
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100729 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700730 return *std::prev(mKnownFrameRates.end());
731 }
732
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100733 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
734 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700735
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100736 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
737 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700738 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
739}
740
Ana Krulecb9afd792020-06-11 13:16:15 -0700741RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
742 std::lock_guard lock(mLock);
743 const auto& deviceMin = getMinRefreshRate();
744 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
745 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
746
747 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
748 // the min allowed refresh rate is higher than the device min, we do not want to enable the
749 // timer.
750 if (deviceMin < minByPolicy) {
751 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
752 }
753 if (minByPolicy == maxByPolicy) {
754 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
755 // max are all the same. This saves us extra unnecessary calls to sysprop.
756 if (deviceMin == minByPolicy) {
757 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
758 }
759 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
760 }
761 // Turn on the timer in all other cases.
762 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
763}
764
Ady Abraham62a0be22020-12-08 16:54:10 -0800765int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700766 // This calculation needs to be in sync with the java code
767 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
768 constexpr float kThreshold = 0.1f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800769 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700770 const auto numPeriodsRounded = std::round(numPeriods);
771 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800772 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700773 }
774
Ady Abraham62f216c2020-10-13 19:07:23 -0700775 return static_cast<int>(numPeriodsRounded);
776}
777
Ady Abraham62a0be22020-12-08 16:54:10 -0800778int RefreshRateConfigs::getRefreshRateDivider(Fps frameRate) const {
Ady Abraham62f216c2020-10-13 19:07:23 -0700779 std::lock_guard lock(mLock);
Ady Abraham62a0be22020-12-08 16:54:10 -0800780 return getFrameRateDivider(mCurrentRefreshRate->getFps(), frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700781}
782
Marin Shalamanovba421a82020-11-10 21:49:26 +0100783void RefreshRateConfigs::dump(std::string& result) const {
784 std::lock_guard lock(mLock);
785 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (DisplayManager): %s\n\n",
786 mDisplayManagerPolicy.toString().c_str());
787 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
788 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
789 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (Override): %s\n\n",
790 currentPolicy.toString().c_str());
791 }
792
793 auto config = mCurrentRefreshRate->hwcConfig;
794 base::StringAppendF(&result, "Current config: %s\n", mCurrentRefreshRate->toString().c_str());
795
796 result.append("Refresh rates:\n");
797 for (const auto& [id, refreshRate] : mRefreshRates) {
798 config = refreshRate->hwcConfig;
799 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
800 }
801
Ady Abraham64c2fc02020-12-29 12:07:50 -0800802 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
803 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100804 result.append("\n");
805}
806
Ady Abraham2139f732019-11-13 18:56:40 -0800807} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100808
809// TODO(b/129481165): remove the #pragma below and fix conversion issues
810#pragma clang diagnostic pop // ignored "-Wextra"