blob: 975754b0643234bfd499c3468000e1b35831ebc1 [file] [log] [blame]
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001/*
2 * Copyright 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Ady Abraham2139f732019-11-13 18:56:40 -080016
Ady Abraham8a82ba62020-01-17 12:43:17 -080017// #define LOG_NDEBUG 0
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020// TODO(b/129481165): remove the #pragma below and fix conversion issues
21#pragma clang diagnostic push
22#pragma clang diagnostic ignored "-Wextra"
23
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080024#include "RefreshRateConfigs.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080025#include <android-base/stringprintf.h>
26#include <utils/Trace.h>
27#include <chrono>
28#include <cmath>
Ady Abraham4899ff82021-01-06 13:53:29 -080029#include "../SurfaceFlingerProperties.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080030
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080031#undef LOG_TAG
32#define LOG_TAG "RefreshRateConfigs"
33
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080034namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010035namespace {
36std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010037 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010038 RefreshRateConfigs::layerVoteTypeString(layer.vote).c_str(), weight,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010039 toString(layer.seamlessness).c_str(),
40 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010041}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010042
43std::vector<Fps> constructKnownFrameRates(
44 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs) {
45 std::vector<Fps> knownFrameRates = {Fps(24.0f), Fps(30.0f), Fps(45.0f), Fps(60.0f), Fps(72.0f)};
46 knownFrameRates.reserve(knownFrameRates.size() + configs.size());
47
48 // Add all supported refresh rates to the set
49 for (const auto& config : configs) {
50 const auto refreshRate = Fps::fromPeriodNsecs(config->getVsyncPeriod());
51 knownFrameRates.emplace_back(refreshRate);
52 }
53
54 // Sort and remove duplicates
55 std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
56 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
57 Fps::EqualsWithMargin()),
58 knownFrameRates.end());
59 return knownFrameRates;
60}
61
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010062} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080063
64using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080065using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080066
Marin Shalamanov46084422020-10-13 12:33:42 +020067std::string RefreshRate::toString() const {
68 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanove8a663d2020-11-24 17:48:00 +010069 getConfigId().value(), hwcConfig->getId(), getFps().getValue(),
Marin Shalamanov46084422020-10-13 12:33:42 +020070 hwcConfig->getWidth(), hwcConfig->getHeight(), getConfigGroup());
71}
72
Ady Abrahama6b676e2020-05-27 14:29:09 -070073std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
74 switch (vote) {
75 case LayerVoteType::NoVote:
76 return "NoVote";
77 case LayerVoteType::Min:
78 return "Min";
79 case LayerVoteType::Max:
80 return "Max";
81 case LayerVoteType::Heuristic:
82 return "Heuristic";
83 case LayerVoteType::ExplicitDefault:
84 return "ExplicitDefault";
85 case LayerVoteType::ExplicitExactOrMultiple:
86 return "ExplicitExactOrMultiple";
87 }
88}
89
Marin Shalamanovb6674e72020-11-06 13:05:57 +010090std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020091 return base::StringPrintf("default config ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010092 ", primary range: %s, app request range: %s",
93 defaultConfig.value(), allowGroupSwitching,
94 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020095}
96
Ady Abraham4ccdcb42020-02-11 17:34:34 -080097std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
98 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -080099 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
100 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
101 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
102 quotient++;
103 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800104 }
105
Ady Abraham62a0be22020-12-08 16:54:10 -0800106 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800107}
108
Ady Abraham62a0be22020-12-08 16:54:10 -0800109float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
110 const RefreshRate& refreshRate,
111 bool isSeamlessSwitch) const {
112 // Slightly prefer seamless switches.
113 constexpr float kSeamedSwitchPenalty = 0.95f;
114 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
115
116 // If the layer wants Max, give higher score to the higher refresh rate
117 if (layer.vote == LayerVoteType::Max) {
118 const auto ratio =
119 refreshRate.fps.getValue() / mAppRequestRefreshRates.back()->fps.getValue();
120 // use ratio^2 to get a lower score the more we get further from peak
121 return ratio * ratio;
122 }
123
124 const auto displayPeriod = refreshRate.getVsyncPeriod();
125 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
126 if (layer.vote == LayerVoteType::ExplicitDefault) {
127 // Find the actual rate the layer will render, assuming
128 // that layerPeriod is the minimal time to render a frame
129 auto actualLayerPeriod = displayPeriod;
130 int multiplier = 1;
131 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
132 multiplier++;
133 actualLayerPeriod = displayPeriod * multiplier;
134 }
135 return std::min(1.0f,
136 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
137 }
138
139 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
140 layer.vote == LayerVoteType::Heuristic) {
141 // Calculate how many display vsyncs we need to present a single frame for this
142 // layer
143 const auto [displayFramesQuotient, displayFramesRemainder] =
144 getDisplayFrames(layerPeriod, displayPeriod);
145 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
146 if (displayFramesRemainder == 0) {
147 // Layer desired refresh rate matches the display rate.
148 return 1.0f * seamlessness;
149 }
150
151 if (displayFramesQuotient == 0) {
152 // Layer desired refresh rate is higher than the display rate.
153 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
154 (1.0f / (MAX_FRAMES_TO_FIT + 1));
155 }
156
157 // Layer desired refresh rate is lower than the display rate. Check how well it fits
158 // the cadence.
159 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
160 int iter = 2;
161 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
162 diff = diff - (displayPeriod - diff);
163 iter++;
164 }
165
166 return (1.0f / iter) * seamlessness;
167 }
168
169 return 0;
170}
171
172struct RefreshRateScore {
173 const RefreshRate* refreshRate;
174 float score;
175};
176
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100177RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
178 const GlobalSignals& globalSignals,
179 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800180 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200181 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800182
Ady Abrahamdfd62162020-06-10 16:11:56 -0700183 if (outSignalsConsidered) *outSignalsConsidered = {};
184 const auto setTouchConsidered = [&] {
185 if (outSignalsConsidered) {
186 outSignalsConsidered->touch = true;
187 }
188 };
189
190 const auto setIdleConsidered = [&] {
191 if (outSignalsConsidered) {
192 outSignalsConsidered->idle = true;
193 }
194 };
195
Ady Abraham8a82ba62020-01-17 12:43:17 -0800196 std::lock_guard lock(mLock);
197
198 int noVoteLayers = 0;
199 int minVoteLayers = 0;
200 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800201 int explicitDefaultVoteLayers = 0;
202 int explicitExactOrMultipleVoteLayers = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800203 float maxExplicitWeight = 0;
Marin Shalamanov46084422020-10-13 12:33:42 +0200204 int seamedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800205 for (const auto& layer : layers) {
Ady Abraham6fb599b2020-03-05 13:48:22 -0800206 if (layer.vote == LayerVoteType::NoVote) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800207 noVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800208 } else if (layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800209 minVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800210 } else if (layer.vote == LayerVoteType::Max) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800211 maxVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800212 } else if (layer.vote == LayerVoteType::ExplicitDefault) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800213 explicitDefaultVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800214 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
215 } else if (layer.vote == LayerVoteType::ExplicitExactOrMultiple) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800216 explicitExactOrMultipleVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800217 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
218 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200219
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100220 if (layer.seamlessness == Seamlessness::SeamedAndSeamless) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200221 seamedLayers++;
222 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800223 }
224
Alec Mouri11232a22020-05-14 18:06:25 -0700225 const bool hasExplicitVoteLayers =
226 explicitDefaultVoteLayers > 0 || explicitExactOrMultipleVoteLayers > 0;
227
Steven Thomasf734df42020-04-13 21:09:28 -0700228 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
229 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700230 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700231 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700232 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700233 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800234 }
235
Alec Mouri11232a22020-05-14 18:06:25 -0700236 // If the primary range consists of a single refresh rate then we can only
237 // move out the of range if layers explicitly request a different refresh
238 // rate.
239 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100240 const bool primaryRangeIsSingleRate =
241 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700242
Ady Abrahamdfd62162020-06-10 16:11:56 -0700243 if (!globalSignals.touch && globalSignals.idle &&
244 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700245 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700246 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700247 return getMinRefreshRateByPolicyLocked();
248 }
249
Steven Thomasdebafed2020-05-18 17:30:35 -0700250 if (layers.empty() || noVoteLayers == layers.size()) {
251 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700252 }
253
Ady Abraham8a82ba62020-01-17 12:43:17 -0800254 // Only if all layers want Min we should return Min
255 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700256 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700257 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800258 }
259
Ady Abraham8a82ba62020-01-17 12:43:17 -0800260 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800261 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700262 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800263
Steven Thomasf734df42020-04-13 21:09:28 -0700264 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800265 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800266 }
267
Marin Shalamanov46084422020-10-13 12:33:42 +0200268 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig);
269
Ady Abraham8a82ba62020-01-17 12:43:17 -0800270 for (const auto& layer : layers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700271 ALOGV("Calculating score for %s (%s, weight %.2f)", layer.name.c_str(),
272 layerVoteTypeString(layer.vote).c_str(), layer.weight);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800273 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800274 continue;
275 }
276
Ady Abraham71c437d2020-01-31 15:56:57 -0800277 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800278
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800279 for (auto i = 0u; i < scores.size(); i++) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800280 const bool isSeamlessSwitch = scores[i].refreshRate->getConfigGroup() ==
281 mCurrentRefreshRate->getConfigGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200282
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100283 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
284 ALOGV("%s ignores %s to avoid non-seamless switch. Current config = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800285 formatLayerInfo(layer, weight).c_str(),
286 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100287 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200288 continue;
289 }
290
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100291 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
292 !layer.focused) {
293 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
294 " Current config = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800295 formatLayerInfo(layer, weight).c_str(),
296 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100297 mCurrentRefreshRate->toString().c_str());
298 continue;
299 }
300
301 // Layers with default seamlessness vote for the current config group if
302 // there are layers with seamlessness=SeamedAndSeamless and for the default
303 // config group otherwise. In second case, if the current config group is different
304 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
305 // disappeared.
306 const bool isInPolicyForDefault = seamedLayers > 0
Ady Abraham62a0be22020-12-08 16:54:10 -0800307 ? scores[i].refreshRate->getConfigGroup() ==
308 mCurrentRefreshRate->getConfigGroup()
309 : scores[i].refreshRate->getConfigGroup() == defaultConfig->getConfigGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100310
311 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault &&
312 !layer.focused) {
313 ALOGV("%s ignores %s. Current config = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800314 scores[i].refreshRate->toString().c_str(),
315 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200316 continue;
317 }
318
Ady Abraham62a0be22020-12-08 16:54:10 -0800319 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
320 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700321 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abraham20c029c2020-07-06 12:58:05 -0700322 !(layer.focused && layer.vote == LayerVoteType::ExplicitDefault)) {
323 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700324 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700325 continue;
326 }
327
Ady Abraham62a0be22020-12-08 16:54:10 -0800328 const auto layerScore =
329 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
330 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
331 scores[i].refreshRate->getName().c_str(), layerScore);
332 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800333 }
334 }
335
Ady Abraham34702102020-02-10 14:12:05 -0800336 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
337 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
338 // or the lower otherwise.
339 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
340 ? getBestRefreshRate(scores.rbegin(), scores.rend())
341 : getBestRefreshRate(scores.begin(), scores.end());
342
Alec Mouri11232a22020-05-14 18:06:25 -0700343 if (primaryRangeIsSingleRate) {
344 // If we never scored any layers, then choose the rate from the primary
345 // range instead of picking a random score from the app range.
346 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800347 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700348 ALOGV("layers not scored - choose %s",
349 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700350 return getMaxRefreshRateByPolicyLocked();
351 } else {
352 return *bestRefreshRate;
353 }
354 }
355
Steven Thomasf734df42020-04-13 21:09:28 -0700356 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
357 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
358 // vote we should not change it if we get a touch event. Only apply touch boost if it will
359 // actually increase the refresh rate over the normal selection.
360 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700361
Ady Abrahamdfd62162020-06-10 16:11:56 -0700362 if (globalSignals.touch && explicitDefaultVoteLayers == 0 &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100363 bestRefreshRate->fps.lessThanWithMargin(touchRefreshRate.fps)) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700364 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700365 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700366 return touchRefreshRate;
367 }
368
Ady Abrahamde7156e2020-02-28 17:29:39 -0800369 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800370}
371
Ady Abraham62a0be22020-12-08 16:54:10 -0800372std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
373groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
374 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
375 for (const auto& layer : layers) {
376 auto iter = layersByUid.emplace(layer.ownerUid,
377 std::vector<const RefreshRateConfigs::LayerRequirement*>());
378 auto& layersWithSameUid = iter.first->second;
379 layersWithSameUid.push_back(&layer);
380 }
381
382 // Remove uids that can't have a frame rate override
383 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
384 const auto& layersWithSameUid = iter->second;
385 bool skipUid = false;
386 for (const auto& layer : layersWithSameUid) {
387 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
388 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
389 skipUid = true;
390 break;
391 }
392 }
393 if (skipUid) {
394 iter = layersByUid.erase(iter);
395 } else {
396 ++iter;
397 }
398 }
399
400 return layersByUid;
401}
402
403std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
404 const AllRefreshRatesMapType& refreshRates) {
405 std::vector<RefreshRateScore> scores;
406 scores.reserve(refreshRates.size());
407 for (const auto& [ignored, refreshRate] : refreshRates) {
408 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
409 }
410 std::sort(scores.begin(), scores.end(),
411 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
412 return scores;
413}
414
415RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
416 const std::vector<LayerRequirement>& layers, Fps displayFrameRate) const {
417 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800418 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800419
Ady Abraham64c2fc02020-12-29 12:07:50 -0800420 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800421 std::lock_guard lock(mLock);
422 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
423 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
424 groupLayersByUid(layers);
425 UidToFrameRateOverride frameRateOverrides;
426 for (const auto& [uid, layersWithSameUid] : layersByUid) {
427 for (auto& score : scores) {
428 score.score = 0;
429 }
430
431 for (const auto& layer : layersWithSameUid) {
432 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
433 continue;
434 }
435
436 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
437 layer->vote != LayerVoteType::ExplicitExactOrMultiple);
438 for (RefreshRateScore& score : scores) {
439 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
440 /*isSeamlessSwitch*/ true);
441 score.score += layer->weight * layerScore;
442 }
443 }
444
445 // We just care about the refresh rates which are a divider of the
446 // display refresh rate
447 auto iter =
448 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
449 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
450 });
451 scores.erase(iter, scores.end());
452
453 // If we never scored any layers, we don't have a preferred frame rate
454 if (std::all_of(scores.begin(), scores.end(),
455 [](const RefreshRateScore& score) { return score.score == 0; })) {
456 continue;
457 }
458
459 // Now that we scored all the refresh rates we need to pick the one that got the highest
460 // score.
461 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
462
463 // If the nest refresh rate is the current one, we don't have an override
464 if (!bestRefreshRate->getFps().equalsWithMargin(displayFrameRate)) {
465 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
466 }
467 }
468
469 return frameRateOverrides;
470}
471
Ady Abraham34702102020-02-10 14:12:05 -0800472template <typename Iter>
473const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800474 constexpr auto EPSILON = 0.001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800475 const RefreshRate* bestRefreshRate = begin->refreshRate;
476 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800477 for (auto i = begin; i != end; ++i) {
478 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100479 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800480
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100481 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800482
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800483 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800484 max = score;
485 bestRefreshRate = refreshRate;
486 }
487 }
488
Ady Abraham34702102020-02-10 14:12:05 -0800489 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800490}
491
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100492std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
493 std::optional<HwcConfigIndexType> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800494 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100495
496 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
497 : *mCurrentRefreshRate;
498 const auto& min = *mMinSupportedRefreshRate;
499
500 if (current != min) {
501 const auto& refreshRate = timerExpired ? min : current;
502 return refreshRate.getFps();
503 }
504
505 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700506}
507
508const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200509 for (auto refreshRate : mPrimaryRefreshRates) {
510 if (mCurrentRefreshRate->getConfigGroup() == refreshRate->getConfigGroup()) {
511 return *refreshRate;
512 }
513 }
514 ALOGE("Can't find min refresh rate by policy with the same config group"
515 " as the current config %s",
516 mCurrentRefreshRate->toString().c_str());
517 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700518 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800519}
520
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100521RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800522 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700523 return getMaxRefreshRateByPolicyLocked();
524}
525
526const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200527 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
528 const auto& refreshRate = (**it);
529 if (mCurrentRefreshRate->getConfigGroup() == refreshRate.getConfigGroup()) {
530 return refreshRate;
531 }
532 }
533 ALOGE("Can't find max refresh rate by policy with the same config group"
534 " as the current config %s",
535 mCurrentRefreshRate->toString().c_str());
536 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700537 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800538}
539
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100540RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800541 std::lock_guard lock(mLock);
542 return *mCurrentRefreshRate;
543}
544
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100545RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800546 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800547 return getCurrentRefreshRateByPolicyLocked();
548}
549
550const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700551 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
552 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800553 return *mCurrentRefreshRate;
554 }
Steven Thomasd4071902020-03-24 16:02:53 -0700555 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultConfig);
Ana Krulec5d477912020-02-07 12:02:38 -0800556}
557
Ady Abraham2139f732019-11-13 18:56:40 -0800558void RefreshRateConfigs::setCurrentConfigId(HwcConfigIndexType configId) {
559 std::lock_guard lock(mLock);
Ady Abraham2e1dd892020-03-05 13:48:36 -0800560 mCurrentRefreshRate = mRefreshRates.at(configId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800561}
562
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800563RefreshRateConfigs::RefreshRateConfigs(
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800564 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs,
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700565 HwcConfigIndexType currentConfigId)
566 : mKnownFrameRates(constructKnownFrameRates(configs)) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100567 updateDisplayConfigs(configs, currentConfigId);
568}
569
570void RefreshRateConfigs::updateDisplayConfigs(
571 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs,
572 HwcConfigIndexType currentConfigId) {
573 std::lock_guard lock(mLock);
Ady Abrahamabc27602020-04-08 17:20:29 -0700574 LOG_ALWAYS_FATAL_IF(configs.empty());
Marin Shalamanov6e840172020-12-14 22:13:28 +0100575 LOG_ALWAYS_FATAL_IF(currentConfigId.value() < 0);
Ady Abrahamabc27602020-04-08 17:20:29 -0700576 LOG_ALWAYS_FATAL_IF(currentConfigId.value() >= configs.size());
577
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100578 mRefreshRates.clear();
Ady Abrahamabc27602020-04-08 17:20:29 -0700579 for (auto configId = HwcConfigIndexType(0); configId.value() < configs.size(); configId++) {
580 const auto& config = configs.at(static_cast<size_t>(configId.value()));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100581 const auto fps = Fps::fromPeriodNsecs(config->getVsyncPeriod());
Ady Abrahamabc27602020-04-08 17:20:29 -0700582 mRefreshRates.emplace(configId,
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100583 std::make_unique<RefreshRate>(configId, config, fps,
Ady Abrahamabc27602020-04-08 17:20:29 -0700584 RefreshRate::ConstructorTag(0)));
585 if (configId == currentConfigId) {
586 mCurrentRefreshRate = mRefreshRates.at(configId).get();
587 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800588 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700589
590 std::vector<const RefreshRate*> sortedConfigs;
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100591 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedConfigs);
Ady Abrahamabc27602020-04-08 17:20:29 -0700592 mDisplayManagerPolicy.defaultConfig = currentConfigId;
593 mMinSupportedRefreshRate = sortedConfigs.front();
594 mMaxSupportedRefreshRate = sortedConfigs.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800595
596 mSupportsFrameRateOverride = false;
Ady Abraham4899ff82021-01-06 13:53:29 -0800597 if (android::sysprop::enable_frame_rate_override(true)) {
598 for (const auto& config1 : sortedConfigs) {
599 for (const auto& config2 : sortedConfigs) {
600 if (getFrameRateDivider(config1->getFps(), config2->getFps()) >= 2) {
601 mSupportsFrameRateOverride = true;
602 break;
603 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800604 }
605 }
606 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800607
Ady Abrahamabc27602020-04-08 17:20:29 -0700608 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800609}
610
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100611bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Steven Thomasd4071902020-03-24 16:02:53 -0700612 // defaultConfig must be a valid config, and within the given refresh rate range.
613 auto iter = mRefreshRates.find(policy.defaultConfig);
614 if (iter == mRefreshRates.end()) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100615 ALOGE("Default config is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700616 return false;
617 }
618 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700619 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100620 ALOGE("Default config is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700621 return false;
622 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100623 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
624 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700625}
626
627status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800628 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100629 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100630 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100631 return BAD_VALUE;
632 }
Steven Thomasd4071902020-03-24 16:02:53 -0700633 Policy previousPolicy = *getCurrentPolicyLocked();
634 mDisplayManagerPolicy = policy;
635 if (*getCurrentPolicyLocked() == previousPolicy) {
636 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100637 }
Ady Abraham2139f732019-11-13 18:56:40 -0800638 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100639 return NO_ERROR;
640}
641
Steven Thomasd4071902020-03-24 16:02:53 -0700642status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100643 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100644 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700645 return BAD_VALUE;
646 }
647 Policy previousPolicy = *getCurrentPolicyLocked();
648 mOverridePolicy = policy;
649 if (*getCurrentPolicyLocked() == previousPolicy) {
650 return CURRENT_POLICY_UNCHANGED;
651 }
652 constructAvailableRefreshRates();
653 return NO_ERROR;
654}
655
656const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
657 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
658}
659
660RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
661 std::lock_guard lock(mLock);
662 return *getCurrentPolicyLocked();
663}
664
665RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
666 std::lock_guard lock(mLock);
667 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100668}
669
670bool RefreshRateConfigs::isConfigAllowed(HwcConfigIndexType config) const {
671 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700672 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100673 if (refreshRate->configId == config) {
674 return true;
675 }
676 }
677 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800678}
679
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100680void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800681 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
682 std::vector<const RefreshRate*>* outRefreshRates) {
683 outRefreshRates->clear();
684 outRefreshRates->reserve(mRefreshRates.size());
685 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800686 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100687 ALOGV("getSortedRefreshRateListLocked: config %d added to list policy",
Ady Abraham2e1dd892020-03-05 13:48:36 -0800688 refreshRate->configId.value());
689 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800690 }
691 }
692
693 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
694 [](const auto refreshRate1, const auto refreshRate2) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700695 if (refreshRate1->hwcConfig->getVsyncPeriod() !=
696 refreshRate2->hwcConfig->getVsyncPeriod()) {
697 return refreshRate1->hwcConfig->getVsyncPeriod() >
698 refreshRate2->hwcConfig->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700699 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -0700700 return refreshRate1->hwcConfig->getConfigGroup() >
701 refreshRate2->hwcConfig->getConfigGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700702 }
Ady Abraham2139f732019-11-13 18:56:40 -0800703 });
704}
705
706void RefreshRateConfigs::constructAvailableRefreshRates() {
707 // Filter configs based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700708 const Policy* policy = getCurrentPolicyLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700709 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig)->hwcConfig;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100710 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700711
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100712 auto filterRefreshRates = [&](Fps min, Fps max, const char* listName,
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100713 std::vector<const RefreshRate*>*
714 outRefreshRates) REQUIRES(mLock) {
715 getSortedRefreshRateListLocked(
Steven Thomasf734df42020-04-13 21:09:28 -0700716 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
717 const auto& hwcConfig = refreshRate.hwcConfig;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800718
Steven Thomasf734df42020-04-13 21:09:28 -0700719 return hwcConfig->getHeight() == defaultConfig->getHeight() &&
720 hwcConfig->getWidth() == defaultConfig->getWidth() &&
721 hwcConfig->getDpiX() == defaultConfig->getDpiX() &&
722 hwcConfig->getDpiY() == defaultConfig->getDpiY() &&
723 (policy->allowGroupSwitching ||
724 hwcConfig->getConfigGroup() == defaultConfig->getConfigGroup()) &&
725 refreshRate.inPolicy(min, max);
726 },
727 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800728
Steven Thomasf734df42020-04-13 21:09:28 -0700729 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100730 "No matching configs for %s range: min=%s max=%s", listName,
731 to_string(min).c_str(), to_string(max).c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700732 auto stringifyRefreshRates = [&]() -> std::string {
733 std::string str;
734 for (auto refreshRate : *outRefreshRates) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100735 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700736 }
737 return str;
738 };
739 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
740 };
741
742 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
743 &mPrimaryRefreshRates);
744 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
745 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800746}
747
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100748Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
749 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700750 return *mKnownFrameRates.begin();
751 }
752
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100753 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700754 return *std::prev(mKnownFrameRates.end());
755 }
756
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100757 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
758 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700759
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100760 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
761 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700762 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
763}
764
Ana Krulecb9afd792020-06-11 13:16:15 -0700765RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
766 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100767 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700768 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
769 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
770
771 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
772 // the min allowed refresh rate is higher than the device min, we do not want to enable the
773 // timer.
774 if (deviceMin < minByPolicy) {
775 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
776 }
777 if (minByPolicy == maxByPolicy) {
778 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
779 // max are all the same. This saves us extra unnecessary calls to sysprop.
780 if (deviceMin == minByPolicy) {
781 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
782 }
783 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
784 }
785 // Turn on the timer in all other cases.
786 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
787}
788
Ady Abraham62a0be22020-12-08 16:54:10 -0800789int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700790 // This calculation needs to be in sync with the java code
791 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
792 constexpr float kThreshold = 0.1f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800793 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700794 const auto numPeriodsRounded = std::round(numPeriods);
795 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800796 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700797 }
798
Ady Abraham62f216c2020-10-13 19:07:23 -0700799 return static_cast<int>(numPeriodsRounded);
800}
801
Ady Abraham62a0be22020-12-08 16:54:10 -0800802int RefreshRateConfigs::getRefreshRateDivider(Fps frameRate) const {
Ady Abraham62f216c2020-10-13 19:07:23 -0700803 std::lock_guard lock(mLock);
Ady Abraham62a0be22020-12-08 16:54:10 -0800804 return getFrameRateDivider(mCurrentRefreshRate->getFps(), frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700805}
806
Marin Shalamanovba421a82020-11-10 21:49:26 +0100807void RefreshRateConfigs::dump(std::string& result) const {
808 std::lock_guard lock(mLock);
809 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (DisplayManager): %s\n\n",
810 mDisplayManagerPolicy.toString().c_str());
811 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
812 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
813 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (Override): %s\n\n",
814 currentPolicy.toString().c_str());
815 }
816
817 auto config = mCurrentRefreshRate->hwcConfig;
818 base::StringAppendF(&result, "Current config: %s\n", mCurrentRefreshRate->toString().c_str());
819
820 result.append("Refresh rates:\n");
821 for (const auto& [id, refreshRate] : mRefreshRates) {
822 config = refreshRate->hwcConfig;
823 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
824 }
825
Ady Abraham64c2fc02020-12-29 12:07:50 -0800826 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
827 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100828 result.append("\n");
829}
830
Ady Abraham2139f732019-11-13 18:56:40 -0800831} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100832
833// TODO(b/129481165): remove the #pragma below and fix conversion issues
834#pragma clang diagnostic pop // ignored "-Wextra"