blob: a03f79384e3a34752737037e87367abda257aca6 [file] [log] [blame]
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001/*
2 * Copyright 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Ady Abraham2139f732019-11-13 18:56:40 -080016
Ady Abraham8a82ba62020-01-17 12:43:17 -080017// #define LOG_NDEBUG 0
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020// TODO(b/129481165): remove the #pragma below and fix conversion issues
21#pragma clang diagnostic push
22#pragma clang diagnostic ignored "-Wextra"
23
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080024#include "RefreshRateConfigs.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080025#include <android-base/stringprintf.h>
26#include <utils/Trace.h>
27#include <chrono>
28#include <cmath>
Ady Abraham4899ff82021-01-06 13:53:29 -080029#include "../SurfaceFlingerProperties.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080030
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080031#undef LOG_TAG
32#define LOG_TAG "RefreshRateConfigs"
33
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080034namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010035namespace {
36std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010037 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010038 RefreshRateConfigs::layerVoteTypeString(layer.vote).c_str(), weight,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010039 toString(layer.seamlessness).c_str(),
40 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010041}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010042
Marin Shalamanova7fe3042021-01-29 21:02:08 +010043std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010044 std::vector<Fps> knownFrameRates = {Fps(24.0f), Fps(30.0f), Fps(45.0f), Fps(60.0f), Fps(72.0f)};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010045 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010046
47 // Add all supported refresh rates to the set
Marin Shalamanova7fe3042021-01-29 21:02:08 +010048 for (const auto& mode : modes) {
49 const auto refreshRate = Fps::fromPeriodNsecs(mode->getVsyncPeriod());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010050 knownFrameRates.emplace_back(refreshRate);
51 }
52
53 // Sort and remove duplicates
54 std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
55 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
56 Fps::EqualsWithMargin()),
57 knownFrameRates.end());
58 return knownFrameRates;
59}
60
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010061} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080062
63using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080064using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080065
Marin Shalamanov46084422020-10-13 12:33:42 +020066std::string RefreshRate::toString() const {
Marin Shalamanov3ea1d602020-12-16 19:59:39 +010067 return base::StringPrintf("{id=%zu, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010068 getModeId().value(), mode->getHwcId(), getFps().getValue(),
69 mode->getWidth(), mode->getHeight(), getModeGroup());
Marin Shalamanov46084422020-10-13 12:33:42 +020070}
71
Ady Abrahama6b676e2020-05-27 14:29:09 -070072std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
73 switch (vote) {
74 case LayerVoteType::NoVote:
75 return "NoVote";
76 case LayerVoteType::Min:
77 return "Min";
78 case LayerVoteType::Max:
79 return "Max";
80 case LayerVoteType::Heuristic:
81 return "Heuristic";
82 case LayerVoteType::ExplicitDefault:
83 return "ExplicitDefault";
84 case LayerVoteType::ExplicitExactOrMultiple:
85 return "ExplicitExactOrMultiple";
Ady Abrahamdd5bfa92021-01-07 17:56:08 -080086 case LayerVoteType::ExplicitExact:
87 return "ExplicitExact";
Ady Abrahama6b676e2020-05-27 14:29:09 -070088 }
89}
90
Marin Shalamanovb6674e72020-11-06 13:05:57 +010091std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +010092 return base::StringPrintf("default mode ID: %zu, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010093 ", primary range: %s, app request range: %s",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010094 defaultMode.value(), allowGroupSwitching,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010095 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020096}
97
Ady Abraham4ccdcb42020-02-11 17:34:34 -080098std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
99 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800100 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
101 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
102 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
103 quotient++;
104 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800105 }
106
Ady Abraham62a0be22020-12-08 16:54:10 -0800107 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800108}
109
Ady Abraham62a0be22020-12-08 16:54:10 -0800110float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
111 const RefreshRate& refreshRate,
112 bool isSeamlessSwitch) const {
113 // Slightly prefer seamless switches.
114 constexpr float kSeamedSwitchPenalty = 0.95f;
115 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
116
117 // If the layer wants Max, give higher score to the higher refresh rate
118 if (layer.vote == LayerVoteType::Max) {
119 const auto ratio =
120 refreshRate.fps.getValue() / mAppRequestRefreshRates.back()->fps.getValue();
121 // use ratio^2 to get a lower score the more we get further from peak
122 return ratio * ratio;
123 }
124
125 const auto displayPeriod = refreshRate.getVsyncPeriod();
126 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
127 if (layer.vote == LayerVoteType::ExplicitDefault) {
128 // Find the actual rate the layer will render, assuming
129 // that layerPeriod is the minimal time to render a frame
130 auto actualLayerPeriod = displayPeriod;
131 int multiplier = 1;
132 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
133 multiplier++;
134 actualLayerPeriod = displayPeriod * multiplier;
135 }
136 return std::min(1.0f,
137 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
138 }
139
140 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
141 layer.vote == LayerVoteType::Heuristic) {
142 // Calculate how many display vsyncs we need to present a single frame for this
143 // layer
144 const auto [displayFramesQuotient, displayFramesRemainder] =
145 getDisplayFrames(layerPeriod, displayPeriod);
146 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
147 if (displayFramesRemainder == 0) {
148 // Layer desired refresh rate matches the display rate.
149 return 1.0f * seamlessness;
150 }
151
152 if (displayFramesQuotient == 0) {
153 // Layer desired refresh rate is higher than the display rate.
154 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
155 (1.0f / (MAX_FRAMES_TO_FIT + 1));
156 }
157
158 // Layer desired refresh rate is lower than the display rate. Check how well it fits
159 // the cadence.
160 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
161 int iter = 2;
162 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
163 diff = diff - (displayPeriod - diff);
164 iter++;
165 }
166
167 return (1.0f / iter) * seamlessness;
168 }
169
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800170 if (layer.vote == LayerVoteType::ExplicitExact) {
171 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
172 if (mSupportsFrameRateOverride) {
173 // Since we support frame rate override, allow refresh rates which are
174 // multiples of the layer's request, as those apps would be throttled
175 // down to run at the desired refresh rate.
176 return divider > 0;
177 }
178
179 return divider == 1;
180 }
181
Ady Abraham62a0be22020-12-08 16:54:10 -0800182 return 0;
183}
184
185struct RefreshRateScore {
186 const RefreshRate* refreshRate;
187 float score;
188};
189
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100190RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
191 const GlobalSignals& globalSignals,
192 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800193 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200194 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800195
Ady Abrahamdfd62162020-06-10 16:11:56 -0700196 if (outSignalsConsidered) *outSignalsConsidered = {};
197 const auto setTouchConsidered = [&] {
198 if (outSignalsConsidered) {
199 outSignalsConsidered->touch = true;
200 }
201 };
202
203 const auto setIdleConsidered = [&] {
204 if (outSignalsConsidered) {
205 outSignalsConsidered->idle = true;
206 }
207 };
208
Ady Abraham8a82ba62020-01-17 12:43:17 -0800209 std::lock_guard lock(mLock);
210
211 int noVoteLayers = 0;
212 int minVoteLayers = 0;
213 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800214 int explicitDefaultVoteLayers = 0;
215 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800216 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800217 float maxExplicitWeight = 0;
Marin Shalamanov46084422020-10-13 12:33:42 +0200218 int seamedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800219 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800220 switch (layer.vote) {
221 case LayerVoteType::NoVote:
222 noVoteLayers++;
223 break;
224 case LayerVoteType::Min:
225 minVoteLayers++;
226 break;
227 case LayerVoteType::Max:
228 maxVoteLayers++;
229 break;
230 case LayerVoteType::ExplicitDefault:
231 explicitDefaultVoteLayers++;
232 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
233 break;
234 case LayerVoteType::ExplicitExactOrMultiple:
235 explicitExactOrMultipleVoteLayers++;
236 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
237 break;
238 case LayerVoteType::ExplicitExact:
239 explicitExact++;
240 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
241 break;
242 case LayerVoteType::Heuristic:
243 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800244 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200245
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100246 if (layer.seamlessness == Seamlessness::SeamedAndSeamless) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200247 seamedLayers++;
248 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800249 }
250
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800251 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
252 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700253
Steven Thomasf734df42020-04-13 21:09:28 -0700254 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
255 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700256 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700257 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700258 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700259 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800260 }
261
Alec Mouri11232a22020-05-14 18:06:25 -0700262 // If the primary range consists of a single refresh rate then we can only
263 // move out the of range if layers explicitly request a different refresh
264 // rate.
265 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100266 const bool primaryRangeIsSingleRate =
267 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700268
Ady Abrahamdfd62162020-06-10 16:11:56 -0700269 if (!globalSignals.touch && globalSignals.idle &&
270 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700271 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700272 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700273 return getMinRefreshRateByPolicyLocked();
274 }
275
Steven Thomasdebafed2020-05-18 17:30:35 -0700276 if (layers.empty() || noVoteLayers == layers.size()) {
277 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700278 }
279
Ady Abraham8a82ba62020-01-17 12:43:17 -0800280 // Only if all layers want Min we should return Min
281 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700282 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700283 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800284 }
285
Ady Abraham8a82ba62020-01-17 12:43:17 -0800286 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800287 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700288 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800289
Steven Thomasf734df42020-04-13 21:09:28 -0700290 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800291 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800292 }
293
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100294 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
Marin Shalamanov46084422020-10-13 12:33:42 +0200295
Ady Abraham8a82ba62020-01-17 12:43:17 -0800296 for (const auto& layer : layers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700297 ALOGV("Calculating score for %s (%s, weight %.2f)", layer.name.c_str(),
298 layerVoteTypeString(layer.vote).c_str(), layer.weight);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800299 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800300 continue;
301 }
302
Ady Abraham71c437d2020-01-31 15:56:57 -0800303 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800304
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800305 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100306 const bool isSeamlessSwitch =
307 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200308
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100309 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100310 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800311 formatLayerInfo(layer, weight).c_str(),
312 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100313 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200314 continue;
315 }
316
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100317 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
318 !layer.focused) {
319 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100320 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800321 formatLayerInfo(layer, weight).c_str(),
322 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100323 mCurrentRefreshRate->toString().c_str());
324 continue;
325 }
326
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100327 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100328 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100329 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100330 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
331 // disappeared.
332 const bool isInPolicyForDefault = seamedLayers > 0
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100333 ? scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup()
334 : scores[i].refreshRate->getModeGroup() == defaultMode->getModeGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100335
336 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault &&
337 !layer.focused) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100338 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800339 scores[i].refreshRate->toString().c_str(),
340 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200341 continue;
342 }
343
Ady Abraham62a0be22020-12-08 16:54:10 -0800344 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
345 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700346 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800347 !(layer.focused &&
348 (layer.vote == LayerVoteType::ExplicitDefault ||
349 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700350 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700351 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700352 continue;
353 }
354
Ady Abraham62a0be22020-12-08 16:54:10 -0800355 const auto layerScore =
356 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
357 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
358 scores[i].refreshRate->getName().c_str(), layerScore);
359 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800360 }
361 }
362
Ady Abraham34702102020-02-10 14:12:05 -0800363 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
364 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
365 // or the lower otherwise.
366 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
367 ? getBestRefreshRate(scores.rbegin(), scores.rend())
368 : getBestRefreshRate(scores.begin(), scores.end());
369
Alec Mouri11232a22020-05-14 18:06:25 -0700370 if (primaryRangeIsSingleRate) {
371 // If we never scored any layers, then choose the rate from the primary
372 // range instead of picking a random score from the app range.
373 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800374 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700375 ALOGV("layers not scored - choose %s",
376 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700377 return getMaxRefreshRateByPolicyLocked();
378 } else {
379 return *bestRefreshRate;
380 }
381 }
382
Steven Thomasf734df42020-04-13 21:09:28 -0700383 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
384 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
385 // vote we should not change it if we get a touch event. Only apply touch boost if it will
386 // actually increase the refresh rate over the normal selection.
387 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700388
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800389 bool touchBoostForExplicitExact = explicitExact == 0 || mSupportsFrameRateOverride;
390 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100391 bestRefreshRate->fps.lessThanWithMargin(touchRefreshRate.fps)) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700392 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700393 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700394 return touchRefreshRate;
395 }
396
Ady Abrahamde7156e2020-02-28 17:29:39 -0800397 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800398}
399
Ady Abraham62a0be22020-12-08 16:54:10 -0800400std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
401groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
402 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
403 for (const auto& layer : layers) {
404 auto iter = layersByUid.emplace(layer.ownerUid,
405 std::vector<const RefreshRateConfigs::LayerRequirement*>());
406 auto& layersWithSameUid = iter.first->second;
407 layersWithSameUid.push_back(&layer);
408 }
409
410 // Remove uids that can't have a frame rate override
411 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
412 const auto& layersWithSameUid = iter->second;
413 bool skipUid = false;
414 for (const auto& layer : layersWithSameUid) {
415 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
416 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
417 skipUid = true;
418 break;
419 }
420 }
421 if (skipUid) {
422 iter = layersByUid.erase(iter);
423 } else {
424 ++iter;
425 }
426 }
427
428 return layersByUid;
429}
430
431std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
432 const AllRefreshRatesMapType& refreshRates) {
433 std::vector<RefreshRateScore> scores;
434 scores.reserve(refreshRates.size());
435 for (const auto& [ignored, refreshRate] : refreshRates) {
436 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
437 }
438 std::sort(scores.begin(), scores.end(),
439 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
440 return scores;
441}
442
443RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800444 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800445 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800446 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800447
Ady Abraham64c2fc02020-12-29 12:07:50 -0800448 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800449 std::lock_guard lock(mLock);
450 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
451 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
452 groupLayersByUid(layers);
453 UidToFrameRateOverride frameRateOverrides;
454 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800455 // Layers with ExplicitExactOrMultiple expect touch boost
456 const bool hasExplicitExactOrMultiple =
457 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
458 [](const auto& layer) {
459 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
460 });
461
462 if (touch && hasExplicitExactOrMultiple) {
463 continue;
464 }
465
Ady Abraham62a0be22020-12-08 16:54:10 -0800466 for (auto& score : scores) {
467 score.score = 0;
468 }
469
470 for (const auto& layer : layersWithSameUid) {
471 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
472 continue;
473 }
474
475 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800476 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
477 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800478 for (RefreshRateScore& score : scores) {
479 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
480 /*isSeamlessSwitch*/ true);
481 score.score += layer->weight * layerScore;
482 }
483 }
484
485 // We just care about the refresh rates which are a divider of the
486 // display refresh rate
487 auto iter =
488 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
489 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
490 });
491 scores.erase(iter, scores.end());
492
493 // If we never scored any layers, we don't have a preferred frame rate
494 if (std::all_of(scores.begin(), scores.end(),
495 [](const RefreshRateScore& score) { return score.score == 0; })) {
496 continue;
497 }
498
499 // Now that we scored all the refresh rates we need to pick the one that got the highest
500 // score.
501 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
502
503 // If the nest refresh rate is the current one, we don't have an override
504 if (!bestRefreshRate->getFps().equalsWithMargin(displayFrameRate)) {
505 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
506 }
507 }
508
509 return frameRateOverrides;
510}
511
Ady Abraham34702102020-02-10 14:12:05 -0800512template <typename Iter>
513const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800514 constexpr auto EPSILON = 0.001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800515 const RefreshRate* bestRefreshRate = begin->refreshRate;
516 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800517 for (auto i = begin; i != end; ++i) {
518 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100519 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800520
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100521 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800522
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800523 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800524 max = score;
525 bestRefreshRate = refreshRate;
526 }
527 }
528
Ady Abraham34702102020-02-10 14:12:05 -0800529 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800530}
531
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100532std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100533 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800534 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100535
536 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
537 : *mCurrentRefreshRate;
538 const auto& min = *mMinSupportedRefreshRate;
539
540 if (current != min) {
541 const auto& refreshRate = timerExpired ? min : current;
542 return refreshRate.getFps();
543 }
544
545 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700546}
547
548const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200549 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100550 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200551 return *refreshRate;
552 }
553 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100554 ALOGE("Can't find min refresh rate by policy with the same mode group"
555 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200556 mCurrentRefreshRate->toString().c_str());
557 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700558 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800559}
560
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100561RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800562 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700563 return getMaxRefreshRateByPolicyLocked();
564}
565
566const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200567 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
568 const auto& refreshRate = (**it);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100569 if (mCurrentRefreshRate->getModeGroup() == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200570 return refreshRate;
571 }
572 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100573 ALOGE("Can't find max refresh rate by policy with the same mode group"
574 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200575 mCurrentRefreshRate->toString().c_str());
576 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700577 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800578}
579
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100580RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800581 std::lock_guard lock(mLock);
582 return *mCurrentRefreshRate;
583}
584
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100585RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800586 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800587 return getCurrentRefreshRateByPolicyLocked();
588}
589
590const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700591 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
592 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800593 return *mCurrentRefreshRate;
594 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100595 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800596}
597
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100598void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800599 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100600 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800601}
602
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100603RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800604 bool enableFrameRateOverride)
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100605 : mKnownFrameRates(constructKnownFrameRates(modes)),
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800606 mEnableFrameRateOverride(enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100607 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100608}
609
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100610void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
611 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100612 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100613 LOG_ALWAYS_FATAL_IF(modes.empty());
614 LOG_ALWAYS_FATAL_IF(currentModeId.value() >= modes.size());
Ady Abrahamabc27602020-04-08 17:20:29 -0700615
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100616 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100617 for (const auto& mode : modes) {
618 const auto modeId = mode->getId();
619 const auto fps = Fps::fromPeriodNsecs(mode->getVsyncPeriod());
620 mRefreshRates.emplace(modeId,
621 std::make_unique<RefreshRate>(modeId, mode, fps,
Ady Abrahamabc27602020-04-08 17:20:29 -0700622 RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100623 if (modeId == currentModeId) {
624 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700625 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800626 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700627
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100628 std::vector<const RefreshRate*> sortedModes;
629 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100630 // Reset the policy because the old one may no longer be valid.
631 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100632 mDisplayManagerPolicy.defaultMode = currentModeId;
633 mMinSupportedRefreshRate = sortedModes.front();
634 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800635
636 mSupportsFrameRateOverride = false;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800637 if (mEnableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100638 for (const auto& mode1 : sortedModes) {
639 for (const auto& mode2 : sortedModes) {
640 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800641 mSupportsFrameRateOverride = true;
642 break;
643 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800644 }
645 }
646 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800647
Ady Abrahamabc27602020-04-08 17:20:29 -0700648 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800649}
650
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100651bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100652 // defaultMode must be a valid mode, and within the given refresh rate range.
653 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700654 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100655 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700656 return false;
657 }
658 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700659 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100660 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700661 return false;
662 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100663 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
664 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700665}
666
667status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800668 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100669 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100670 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100671 return BAD_VALUE;
672 }
Steven Thomasd4071902020-03-24 16:02:53 -0700673 Policy previousPolicy = *getCurrentPolicyLocked();
674 mDisplayManagerPolicy = policy;
675 if (*getCurrentPolicyLocked() == previousPolicy) {
676 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100677 }
Ady Abraham2139f732019-11-13 18:56:40 -0800678 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100679 return NO_ERROR;
680}
681
Steven Thomasd4071902020-03-24 16:02:53 -0700682status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100683 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100684 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700685 return BAD_VALUE;
686 }
687 Policy previousPolicy = *getCurrentPolicyLocked();
688 mOverridePolicy = policy;
689 if (*getCurrentPolicyLocked() == previousPolicy) {
690 return CURRENT_POLICY_UNCHANGED;
691 }
692 constructAvailableRefreshRates();
693 return NO_ERROR;
694}
695
696const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
697 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
698}
699
700RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
701 std::lock_guard lock(mLock);
702 return *getCurrentPolicyLocked();
703}
704
705RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
706 std::lock_guard lock(mLock);
707 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100708}
709
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100710bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100711 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700712 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100713 if (refreshRate->modeId == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100714 return true;
715 }
716 }
717 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800718}
719
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100720void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800721 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
722 std::vector<const RefreshRate*>* outRefreshRates) {
723 outRefreshRates->clear();
724 outRefreshRates->reserve(mRefreshRates.size());
725 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800726 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100727 ALOGV("getSortedRefreshRateListLocked: mode %zu added to list policy",
728 refreshRate->modeId.value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800729 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800730 }
731 }
732
733 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
734 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100735 if (refreshRate1->mode->getVsyncPeriod() !=
736 refreshRate2->mode->getVsyncPeriod()) {
737 return refreshRate1->mode->getVsyncPeriod() >
738 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700739 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100740 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700741 }
Ady Abraham2139f732019-11-13 18:56:40 -0800742 });
743}
744
745void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100746 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700747 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100748 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100749 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700750
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100751 auto filterRefreshRates =
752 [&](Fps min, Fps max, const char* listName,
753 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
754 getSortedRefreshRateListLocked(
755 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
756 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800757
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100758 return mode->getHeight() == defaultMode->getHeight() &&
759 mode->getWidth() == defaultMode->getWidth() &&
760 mode->getDpiX() == defaultMode->getDpiX() &&
761 mode->getDpiY() == defaultMode->getDpiY() &&
762 (policy->allowGroupSwitching ||
763 mode->getGroup() == defaultMode->getGroup()) &&
764 refreshRate.inPolicy(min, max);
765 },
766 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800767
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100768 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
769 "No matching modes for %s range: min=%s max=%s", listName,
770 to_string(min).c_str(), to_string(max).c_str());
771 auto stringifyRefreshRates = [&]() -> std::string {
772 std::string str;
773 for (auto refreshRate : *outRefreshRates) {
774 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
775 }
776 return str;
777 };
778 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
779 };
Steven Thomasf734df42020-04-13 21:09:28 -0700780
781 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
782 &mPrimaryRefreshRates);
783 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
784 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800785}
786
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100787Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
788 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700789 return *mKnownFrameRates.begin();
790 }
791
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100792 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700793 return *std::prev(mKnownFrameRates.end());
794 }
795
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100796 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
797 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700798
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100799 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
800 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700801 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
802}
803
Ana Krulecb9afd792020-06-11 13:16:15 -0700804RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
805 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100806 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700807 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
808 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
809
810 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
811 // the min allowed refresh rate is higher than the device min, we do not want to enable the
812 // timer.
813 if (deviceMin < minByPolicy) {
814 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
815 }
816 if (minByPolicy == maxByPolicy) {
817 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
818 // max are all the same. This saves us extra unnecessary calls to sysprop.
819 if (deviceMin == minByPolicy) {
820 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
821 }
822 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
823 }
824 // Turn on the timer in all other cases.
825 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
826}
827
Ady Abraham62a0be22020-12-08 16:54:10 -0800828int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700829 // This calculation needs to be in sync with the java code
830 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
831 constexpr float kThreshold = 0.1f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800832 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700833 const auto numPeriodsRounded = std::round(numPeriods);
834 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800835 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700836 }
837
Ady Abraham62f216c2020-10-13 19:07:23 -0700838 return static_cast<int>(numPeriodsRounded);
839}
840
Ady Abraham62a0be22020-12-08 16:54:10 -0800841int RefreshRateConfigs::getRefreshRateDivider(Fps frameRate) const {
Ady Abraham62f216c2020-10-13 19:07:23 -0700842 std::lock_guard lock(mLock);
Ady Abraham62a0be22020-12-08 16:54:10 -0800843 return getFrameRateDivider(mCurrentRefreshRate->getFps(), frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700844}
845
Marin Shalamanovba421a82020-11-10 21:49:26 +0100846void RefreshRateConfigs::dump(std::string& result) const {
847 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100848 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100849 mDisplayManagerPolicy.toString().c_str());
850 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
851 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100852 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100853 currentPolicy.toString().c_str());
854 }
855
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100856 auto mode = mCurrentRefreshRate->mode;
857 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100858
859 result.append("Refresh rates:\n");
860 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100861 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +0100862 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
863 }
864
Ady Abraham64c2fc02020-12-29 12:07:50 -0800865 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
866 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100867 result.append("\n");
868}
869
Ady Abraham2139f732019-11-13 18:56:40 -0800870} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100871
872// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800873#pragma clang diagnostic pop // ignored "-Wextra"