blob: c42c81208e6a5022ef098afd78b2ef06e4daa504 [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}
42} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080043
44using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080045using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080046
Marin Shalamanov46084422020-10-13 12:33:42 +020047std::string RefreshRate::toString() const {
48 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanove8a663d2020-11-24 17:48:00 +010049 getConfigId().value(), hwcConfig->getId(), getFps().getValue(),
Marin Shalamanov46084422020-10-13 12:33:42 +020050 hwcConfig->getWidth(), hwcConfig->getHeight(), getConfigGroup());
51}
52
Ady Abrahama6b676e2020-05-27 14:29:09 -070053std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
54 switch (vote) {
55 case LayerVoteType::NoVote:
56 return "NoVote";
57 case LayerVoteType::Min:
58 return "Min";
59 case LayerVoteType::Max:
60 return "Max";
61 case LayerVoteType::Heuristic:
62 return "Heuristic";
63 case LayerVoteType::ExplicitDefault:
64 return "ExplicitDefault";
65 case LayerVoteType::ExplicitExactOrMultiple:
66 return "ExplicitExactOrMultiple";
67 }
68}
69
Marin Shalamanovb6674e72020-11-06 13:05:57 +010070std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020071 return base::StringPrintf("default config ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010072 ", primary range: %s, app request range: %s",
73 defaultConfig.value(), allowGroupSwitching,
74 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020075}
76
Ady Abraham4ccdcb42020-02-11 17:34:34 -080077std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
78 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -080079 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
80 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
81 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
82 quotient++;
83 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -080084 }
85
Ady Abraham62a0be22020-12-08 16:54:10 -080086 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -080087}
88
Ady Abraham62a0be22020-12-08 16:54:10 -080089float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
90 const RefreshRate& refreshRate,
91 bool isSeamlessSwitch) const {
92 // Slightly prefer seamless switches.
93 constexpr float kSeamedSwitchPenalty = 0.95f;
94 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
95
96 // If the layer wants Max, give higher score to the higher refresh rate
97 if (layer.vote == LayerVoteType::Max) {
98 const auto ratio =
99 refreshRate.fps.getValue() / mAppRequestRefreshRates.back()->fps.getValue();
100 // use ratio^2 to get a lower score the more we get further from peak
101 return ratio * ratio;
102 }
103
104 const auto displayPeriod = refreshRate.getVsyncPeriod();
105 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
106 if (layer.vote == LayerVoteType::ExplicitDefault) {
107 // Find the actual rate the layer will render, assuming
108 // that layerPeriod is the minimal time to render a frame
109 auto actualLayerPeriod = displayPeriod;
110 int multiplier = 1;
111 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
112 multiplier++;
113 actualLayerPeriod = displayPeriod * multiplier;
114 }
115 return std::min(1.0f,
116 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
117 }
118
119 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
120 layer.vote == LayerVoteType::Heuristic) {
121 // Calculate how many display vsyncs we need to present a single frame for this
122 // layer
123 const auto [displayFramesQuotient, displayFramesRemainder] =
124 getDisplayFrames(layerPeriod, displayPeriod);
125 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
126 if (displayFramesRemainder == 0) {
127 // Layer desired refresh rate matches the display rate.
128 return 1.0f * seamlessness;
129 }
130
131 if (displayFramesQuotient == 0) {
132 // Layer desired refresh rate is higher than the display rate.
133 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
134 (1.0f / (MAX_FRAMES_TO_FIT + 1));
135 }
136
137 // Layer desired refresh rate is lower than the display rate. Check how well it fits
138 // the cadence.
139 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
140 int iter = 2;
141 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
142 diff = diff - (displayPeriod - diff);
143 iter++;
144 }
145
146 return (1.0f / iter) * seamlessness;
147 }
148
149 return 0;
150}
151
152struct RefreshRateScore {
153 const RefreshRate* refreshRate;
154 float score;
155};
156
Steven Thomasbb374322020-04-28 22:47:16 -0700157const RefreshRate& RefreshRateConfigs::getBestRefreshRate(
Ady Abrahamdfd62162020-06-10 16:11:56 -0700158 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
159 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800160 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200161 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800162
Ady Abrahamdfd62162020-06-10 16:11:56 -0700163 if (outSignalsConsidered) *outSignalsConsidered = {};
164 const auto setTouchConsidered = [&] {
165 if (outSignalsConsidered) {
166 outSignalsConsidered->touch = true;
167 }
168 };
169
170 const auto setIdleConsidered = [&] {
171 if (outSignalsConsidered) {
172 outSignalsConsidered->idle = true;
173 }
174 };
175
Ady Abraham8a82ba62020-01-17 12:43:17 -0800176 std::lock_guard lock(mLock);
177
178 int noVoteLayers = 0;
179 int minVoteLayers = 0;
180 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800181 int explicitDefaultVoteLayers = 0;
182 int explicitExactOrMultipleVoteLayers = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800183 float maxExplicitWeight = 0;
Marin Shalamanov46084422020-10-13 12:33:42 +0200184 int seamedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800185 for (const auto& layer : layers) {
Ady Abraham6fb599b2020-03-05 13:48:22 -0800186 if (layer.vote == LayerVoteType::NoVote) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800187 noVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800188 } else if (layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800189 minVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800190 } else if (layer.vote == LayerVoteType::Max) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800191 maxVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800192 } else if (layer.vote == LayerVoteType::ExplicitDefault) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800193 explicitDefaultVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800194 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
195 } else if (layer.vote == LayerVoteType::ExplicitExactOrMultiple) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800196 explicitExactOrMultipleVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800197 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
198 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200199
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100200 if (layer.seamlessness == Seamlessness::SeamedAndSeamless) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200201 seamedLayers++;
202 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800203 }
204
Alec Mouri11232a22020-05-14 18:06:25 -0700205 const bool hasExplicitVoteLayers =
206 explicitDefaultVoteLayers > 0 || explicitExactOrMultipleVoteLayers > 0;
207
Steven Thomasf734df42020-04-13 21:09:28 -0700208 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
209 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700210 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700211 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700212 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700213 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800214 }
215
Alec Mouri11232a22020-05-14 18:06:25 -0700216 // If the primary range consists of a single refresh rate then we can only
217 // move out the of range if layers explicitly request a different refresh
218 // rate.
219 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100220 const bool primaryRangeIsSingleRate =
221 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700222
Ady Abrahamdfd62162020-06-10 16:11:56 -0700223 if (!globalSignals.touch && globalSignals.idle &&
224 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700225 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700226 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700227 return getMinRefreshRateByPolicyLocked();
228 }
229
Steven Thomasdebafed2020-05-18 17:30:35 -0700230 if (layers.empty() || noVoteLayers == layers.size()) {
231 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700232 }
233
Ady Abraham8a82ba62020-01-17 12:43:17 -0800234 // Only if all layers want Min we should return Min
235 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700236 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700237 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800238 }
239
Ady Abraham8a82ba62020-01-17 12:43:17 -0800240 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800241 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700242 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800243
Steven Thomasf734df42020-04-13 21:09:28 -0700244 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800245 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800246 }
247
Marin Shalamanov46084422020-10-13 12:33:42 +0200248 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig);
249
Ady Abraham8a82ba62020-01-17 12:43:17 -0800250 for (const auto& layer : layers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700251 ALOGV("Calculating score for %s (%s, weight %.2f)", layer.name.c_str(),
252 layerVoteTypeString(layer.vote).c_str(), layer.weight);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800253 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800254 continue;
255 }
256
Ady Abraham71c437d2020-01-31 15:56:57 -0800257 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800258
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800259 for (auto i = 0u; i < scores.size(); i++) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800260 const bool isSeamlessSwitch = scores[i].refreshRate->getConfigGroup() ==
261 mCurrentRefreshRate->getConfigGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200262
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100263 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
264 ALOGV("%s ignores %s to avoid non-seamless switch. Current config = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800265 formatLayerInfo(layer, weight).c_str(),
266 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100267 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200268 continue;
269 }
270
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100271 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
272 !layer.focused) {
273 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
274 " Current config = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800275 formatLayerInfo(layer, weight).c_str(),
276 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100277 mCurrentRefreshRate->toString().c_str());
278 continue;
279 }
280
281 // Layers with default seamlessness vote for the current config group if
282 // there are layers with seamlessness=SeamedAndSeamless and for the default
283 // config group otherwise. In second case, if the current config group is different
284 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
285 // disappeared.
286 const bool isInPolicyForDefault = seamedLayers > 0
Ady Abraham62a0be22020-12-08 16:54:10 -0800287 ? scores[i].refreshRate->getConfigGroup() ==
288 mCurrentRefreshRate->getConfigGroup()
289 : scores[i].refreshRate->getConfigGroup() == defaultConfig->getConfigGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100290
291 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault &&
292 !layer.focused) {
293 ALOGV("%s ignores %s. Current config = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800294 scores[i].refreshRate->toString().c_str(),
295 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200296 continue;
297 }
298
Ady Abraham62a0be22020-12-08 16:54:10 -0800299 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
300 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700301 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abraham20c029c2020-07-06 12:58:05 -0700302 !(layer.focused && layer.vote == LayerVoteType::ExplicitDefault)) {
303 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700304 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700305 continue;
306 }
307
Ady Abraham62a0be22020-12-08 16:54:10 -0800308 const auto layerScore =
309 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
310 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
311 scores[i].refreshRate->getName().c_str(), layerScore);
312 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800313 }
314 }
315
Ady Abraham34702102020-02-10 14:12:05 -0800316 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
317 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
318 // or the lower otherwise.
319 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
320 ? getBestRefreshRate(scores.rbegin(), scores.rend())
321 : getBestRefreshRate(scores.begin(), scores.end());
322
Alec Mouri11232a22020-05-14 18:06:25 -0700323 if (primaryRangeIsSingleRate) {
324 // If we never scored any layers, then choose the rate from the primary
325 // range instead of picking a random score from the app range.
326 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800327 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700328 ALOGV("layers not scored - choose %s",
329 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700330 return getMaxRefreshRateByPolicyLocked();
331 } else {
332 return *bestRefreshRate;
333 }
334 }
335
Steven Thomasf734df42020-04-13 21:09:28 -0700336 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
337 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
338 // vote we should not change it if we get a touch event. Only apply touch boost if it will
339 // actually increase the refresh rate over the normal selection.
340 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700341
Ady Abrahamdfd62162020-06-10 16:11:56 -0700342 if (globalSignals.touch && explicitDefaultVoteLayers == 0 &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100343 bestRefreshRate->fps.lessThanWithMargin(touchRefreshRate.fps)) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700344 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700345 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700346 return touchRefreshRate;
347 }
348
Ady Abrahamde7156e2020-02-28 17:29:39 -0800349 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800350}
351
Ady Abraham62a0be22020-12-08 16:54:10 -0800352std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
353groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
354 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
355 for (const auto& layer : layers) {
356 auto iter = layersByUid.emplace(layer.ownerUid,
357 std::vector<const RefreshRateConfigs::LayerRequirement*>());
358 auto& layersWithSameUid = iter.first->second;
359 layersWithSameUid.push_back(&layer);
360 }
361
362 // Remove uids that can't have a frame rate override
363 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
364 const auto& layersWithSameUid = iter->second;
365 bool skipUid = false;
366 for (const auto& layer : layersWithSameUid) {
367 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
368 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
369 skipUid = true;
370 break;
371 }
372 }
373 if (skipUid) {
374 iter = layersByUid.erase(iter);
375 } else {
376 ++iter;
377 }
378 }
379
380 return layersByUid;
381}
382
383std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
384 const AllRefreshRatesMapType& refreshRates) {
385 std::vector<RefreshRateScore> scores;
386 scores.reserve(refreshRates.size());
387 for (const auto& [ignored, refreshRate] : refreshRates) {
388 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
389 }
390 std::sort(scores.begin(), scores.end(),
391 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
392 return scores;
393}
394
395RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
396 const std::vector<LayerRequirement>& layers, Fps displayFrameRate) const {
397 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800398 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800399
Ady Abraham64c2fc02020-12-29 12:07:50 -0800400 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800401 std::lock_guard lock(mLock);
402 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
403 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
404 groupLayersByUid(layers);
405 UidToFrameRateOverride frameRateOverrides;
406 for (const auto& [uid, layersWithSameUid] : layersByUid) {
407 for (auto& score : scores) {
408 score.score = 0;
409 }
410
411 for (const auto& layer : layersWithSameUid) {
412 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
413 continue;
414 }
415
416 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
417 layer->vote != LayerVoteType::ExplicitExactOrMultiple);
418 for (RefreshRateScore& score : scores) {
419 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
420 /*isSeamlessSwitch*/ true);
421 score.score += layer->weight * layerScore;
422 }
423 }
424
425 // We just care about the refresh rates which are a divider of the
426 // display refresh rate
427 auto iter =
428 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
429 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
430 });
431 scores.erase(iter, scores.end());
432
433 // If we never scored any layers, we don't have a preferred frame rate
434 if (std::all_of(scores.begin(), scores.end(),
435 [](const RefreshRateScore& score) { return score.score == 0; })) {
436 continue;
437 }
438
439 // Now that we scored all the refresh rates we need to pick the one that got the highest
440 // score.
441 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
442
443 // If the nest refresh rate is the current one, we don't have an override
444 if (!bestRefreshRate->getFps().equalsWithMargin(displayFrameRate)) {
445 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
446 }
447 }
448
449 return frameRateOverrides;
450}
451
Ady Abraham34702102020-02-10 14:12:05 -0800452template <typename Iter>
453const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800454 constexpr auto EPSILON = 0.001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800455 const RefreshRate* bestRefreshRate = begin->refreshRate;
456 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800457 for (auto i = begin; i != end; ++i) {
458 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100459 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800460
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100461 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800462
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800463 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800464 max = score;
465 bestRefreshRate = refreshRate;
466 }
467 }
468
Ady Abraham34702102020-02-10 14:12:05 -0800469 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800470}
471
Ady Abraham2139f732019-11-13 18:56:40 -0800472const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicy() const {
473 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700474 return getMinRefreshRateByPolicyLocked();
475}
476
477const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200478 for (auto refreshRate : mPrimaryRefreshRates) {
479 if (mCurrentRefreshRate->getConfigGroup() == refreshRate->getConfigGroup()) {
480 return *refreshRate;
481 }
482 }
483 ALOGE("Can't find min refresh rate by policy with the same config group"
484 " as the current config %s",
485 mCurrentRefreshRate->toString().c_str());
486 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700487 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800488}
489
490const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
491 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700492 return getMaxRefreshRateByPolicyLocked();
493}
494
495const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200496 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
497 const auto& refreshRate = (**it);
498 if (mCurrentRefreshRate->getConfigGroup() == refreshRate.getConfigGroup()) {
499 return refreshRate;
500 }
501 }
502 ALOGE("Can't find max refresh rate by policy with the same config group"
503 " as the current config %s",
504 mCurrentRefreshRate->toString().c_str());
505 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700506 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800507}
508
509const RefreshRate& RefreshRateConfigs::getCurrentRefreshRate() const {
510 std::lock_guard lock(mLock);
511 return *mCurrentRefreshRate;
512}
513
Ana Krulec5d477912020-02-07 12:02:38 -0800514const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
515 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800516 return getCurrentRefreshRateByPolicyLocked();
517}
518
519const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700520 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
521 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800522 return *mCurrentRefreshRate;
523 }
Steven Thomasd4071902020-03-24 16:02:53 -0700524 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultConfig);
Ana Krulec5d477912020-02-07 12:02:38 -0800525}
526
Ady Abraham2139f732019-11-13 18:56:40 -0800527void RefreshRateConfigs::setCurrentConfigId(HwcConfigIndexType configId) {
528 std::lock_guard lock(mLock);
Ady Abraham2e1dd892020-03-05 13:48:36 -0800529 mCurrentRefreshRate = mRefreshRates.at(configId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800530}
531
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800532RefreshRateConfigs::RefreshRateConfigs(
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800533 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs,
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700534 HwcConfigIndexType currentConfigId)
535 : mKnownFrameRates(constructKnownFrameRates(configs)) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700536 LOG_ALWAYS_FATAL_IF(configs.empty());
Marin Shalamanov6e840172020-12-14 22:13:28 +0100537 LOG_ALWAYS_FATAL_IF(currentConfigId.value() < 0);
Ady Abrahamabc27602020-04-08 17:20:29 -0700538 LOG_ALWAYS_FATAL_IF(currentConfigId.value() >= configs.size());
539
540 for (auto configId = HwcConfigIndexType(0); configId.value() < configs.size(); configId++) {
541 const auto& config = configs.at(static_cast<size_t>(configId.value()));
Ady Abrahamabc27602020-04-08 17:20:29 -0700542 mRefreshRates.emplace(configId,
543 std::make_unique<RefreshRate>(configId, config,
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100544 Fps::fromPeriodNsecs(
545 config->getVsyncPeriod()),
Ady Abrahamabc27602020-04-08 17:20:29 -0700546 RefreshRate::ConstructorTag(0)));
547 if (configId == currentConfigId) {
548 mCurrentRefreshRate = mRefreshRates.at(configId).get();
549 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800550 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700551
552 std::vector<const RefreshRate*> sortedConfigs;
553 getSortedRefreshRateList([](const RefreshRate&) { return true; }, &sortedConfigs);
554 mDisplayManagerPolicy.defaultConfig = currentConfigId;
555 mMinSupportedRefreshRate = sortedConfigs.front();
556 mMaxSupportedRefreshRate = sortedConfigs.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800557
558 mSupportsFrameRateOverride = false;
Ady Abraham4899ff82021-01-06 13:53:29 -0800559 if (android::sysprop::enable_frame_rate_override(true)) {
560 for (const auto& config1 : sortedConfigs) {
561 for (const auto& config2 : sortedConfigs) {
562 if (getFrameRateDivider(config1->getFps(), config2->getFps()) >= 2) {
563 mSupportsFrameRateOverride = true;
564 break;
565 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800566 }
567 }
568 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800569
Ady Abrahamabc27602020-04-08 17:20:29 -0700570 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800571}
572
Steven Thomasd4071902020-03-24 16:02:53 -0700573bool RefreshRateConfigs::isPolicyValid(const Policy& policy) {
574 // defaultConfig must be a valid config, and within the given refresh rate range.
575 auto iter = mRefreshRates.find(policy.defaultConfig);
576 if (iter == mRefreshRates.end()) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100577 ALOGE("Default config is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700578 return false;
579 }
580 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700581 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100582 ALOGE("Default config is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700583 return false;
584 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100585 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
586 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700587}
588
589status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800590 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700591 if (!isPolicyValid(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100592 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100593 return BAD_VALUE;
594 }
Steven Thomasd4071902020-03-24 16:02:53 -0700595 Policy previousPolicy = *getCurrentPolicyLocked();
596 mDisplayManagerPolicy = policy;
597 if (*getCurrentPolicyLocked() == previousPolicy) {
598 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100599 }
Ady Abraham2139f732019-11-13 18:56:40 -0800600 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100601 return NO_ERROR;
602}
603
Steven Thomasd4071902020-03-24 16:02:53 -0700604status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100605 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700606 if (policy && !isPolicyValid(*policy)) {
607 return BAD_VALUE;
608 }
609 Policy previousPolicy = *getCurrentPolicyLocked();
610 mOverridePolicy = policy;
611 if (*getCurrentPolicyLocked() == previousPolicy) {
612 return CURRENT_POLICY_UNCHANGED;
613 }
614 constructAvailableRefreshRates();
615 return NO_ERROR;
616}
617
618const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
619 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
620}
621
622RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
623 std::lock_guard lock(mLock);
624 return *getCurrentPolicyLocked();
625}
626
627RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
628 std::lock_guard lock(mLock);
629 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100630}
631
632bool RefreshRateConfigs::isConfigAllowed(HwcConfigIndexType config) const {
633 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700634 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100635 if (refreshRate->configId == config) {
636 return true;
637 }
638 }
639 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800640}
641
642void RefreshRateConfigs::getSortedRefreshRateList(
643 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
644 std::vector<const RefreshRate*>* outRefreshRates) {
645 outRefreshRates->clear();
646 outRefreshRates->reserve(mRefreshRates.size());
647 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800648 if (shouldAddRefreshRate(*refreshRate)) {
Ady Abraham2139f732019-11-13 18:56:40 -0800649 ALOGV("getSortedRefreshRateList: config %d added to list policy",
Ady Abraham2e1dd892020-03-05 13:48:36 -0800650 refreshRate->configId.value());
651 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800652 }
653 }
654
655 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
656 [](const auto refreshRate1, const auto refreshRate2) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700657 if (refreshRate1->hwcConfig->getVsyncPeriod() !=
658 refreshRate2->hwcConfig->getVsyncPeriod()) {
659 return refreshRate1->hwcConfig->getVsyncPeriod() >
660 refreshRate2->hwcConfig->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700661 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -0700662 return refreshRate1->hwcConfig->getConfigGroup() >
663 refreshRate2->hwcConfig->getConfigGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700664 }
Ady Abraham2139f732019-11-13 18:56:40 -0800665 });
666}
667
668void RefreshRateConfigs::constructAvailableRefreshRates() {
669 // Filter configs based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700670 const Policy* policy = getCurrentPolicyLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700671 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig)->hwcConfig;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100672 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700673
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100674 auto filterRefreshRates = [&](Fps min, Fps max, const char* listName,
Steven Thomasf734df42020-04-13 21:09:28 -0700675 std::vector<const RefreshRate*>* outRefreshRates) {
676 getSortedRefreshRateList(
677 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
678 const auto& hwcConfig = refreshRate.hwcConfig;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800679
Steven Thomasf734df42020-04-13 21:09:28 -0700680 return hwcConfig->getHeight() == defaultConfig->getHeight() &&
681 hwcConfig->getWidth() == defaultConfig->getWidth() &&
682 hwcConfig->getDpiX() == defaultConfig->getDpiX() &&
683 hwcConfig->getDpiY() == defaultConfig->getDpiY() &&
684 (policy->allowGroupSwitching ||
685 hwcConfig->getConfigGroup() == defaultConfig->getConfigGroup()) &&
686 refreshRate.inPolicy(min, max);
687 },
688 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800689
Steven Thomasf734df42020-04-13 21:09:28 -0700690 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100691 "No matching configs for %s range: min=%s max=%s", listName,
692 to_string(min).c_str(), to_string(max).c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700693 auto stringifyRefreshRates = [&]() -> std::string {
694 std::string str;
695 for (auto refreshRate : *outRefreshRates) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100696 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700697 }
698 return str;
699 };
700 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
701 };
702
703 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
704 &mPrimaryRefreshRates);
705 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
706 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800707}
708
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100709std::vector<Fps> RefreshRateConfigs::constructKnownFrameRates(
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700710 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100711 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 -0700712 knownFrameRates.reserve(knownFrameRates.size() + configs.size());
713
714 // Add all supported refresh rates to the set
715 for (const auto& config : configs) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100716 const auto refreshRate = Fps::fromPeriodNsecs(config->getVsyncPeriod());
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700717 knownFrameRates.emplace_back(refreshRate);
718 }
719
720 // Sort and remove duplicates
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100721 std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700722 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100723 Fps::EqualsWithMargin()),
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700724 knownFrameRates.end());
725 return knownFrameRates;
726}
727
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100728Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
729 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700730 return *mKnownFrameRates.begin();
731 }
732
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100733 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700734 return *std::prev(mKnownFrameRates.end());
735 }
736
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100737 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
738 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700739
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100740 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
741 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700742 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
743}
744
Ana Krulecb9afd792020-06-11 13:16:15 -0700745RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
746 std::lock_guard lock(mLock);
747 const auto& deviceMin = getMinRefreshRate();
748 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
749 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
750
751 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
752 // the min allowed refresh rate is higher than the device min, we do not want to enable the
753 // timer.
754 if (deviceMin < minByPolicy) {
755 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
756 }
757 if (minByPolicy == maxByPolicy) {
758 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
759 // max are all the same. This saves us extra unnecessary calls to sysprop.
760 if (deviceMin == minByPolicy) {
761 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
762 }
763 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
764 }
765 // Turn on the timer in all other cases.
766 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
767}
768
Ady Abraham62a0be22020-12-08 16:54:10 -0800769int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700770 // This calculation needs to be in sync with the java code
771 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
772 constexpr float kThreshold = 0.1f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800773 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700774 const auto numPeriodsRounded = std::round(numPeriods);
775 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800776 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700777 }
778
Ady Abraham62f216c2020-10-13 19:07:23 -0700779 return static_cast<int>(numPeriodsRounded);
780}
781
Ady Abraham62a0be22020-12-08 16:54:10 -0800782int RefreshRateConfigs::getRefreshRateDivider(Fps frameRate) const {
Ady Abraham62f216c2020-10-13 19:07:23 -0700783 std::lock_guard lock(mLock);
Ady Abraham62a0be22020-12-08 16:54:10 -0800784 return getFrameRateDivider(mCurrentRefreshRate->getFps(), frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700785}
786
Marin Shalamanovba421a82020-11-10 21:49:26 +0100787void RefreshRateConfigs::dump(std::string& result) const {
788 std::lock_guard lock(mLock);
789 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (DisplayManager): %s\n\n",
790 mDisplayManagerPolicy.toString().c_str());
791 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
792 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
793 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (Override): %s\n\n",
794 currentPolicy.toString().c_str());
795 }
796
797 auto config = mCurrentRefreshRate->hwcConfig;
798 base::StringAppendF(&result, "Current config: %s\n", mCurrentRefreshRate->toString().c_str());
799
800 result.append("Refresh rates:\n");
801 for (const auto& [id, refreshRate] : mRefreshRates) {
802 config = refreshRate->hwcConfig;
803 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
804 }
805
Ady Abraham64c2fc02020-12-29 12:07:50 -0800806 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
807 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100808 result.append("\n");
809}
810
Ady Abraham2139f732019-11-13 18:56:40 -0800811} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100812
813// TODO(b/129481165): remove the #pragma below and fix conversion issues
814#pragma clang diagnostic pop // ignored "-Wextra"