blob: e7a44a70d5467ad02c9ae149e11105fefe752726 [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);
630 mDisplayManagerPolicy.defaultMode = currentModeId;
631 mMinSupportedRefreshRate = sortedModes.front();
632 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800633
634 mSupportsFrameRateOverride = false;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800635 if (mEnableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100636 for (const auto& mode1 : sortedModes) {
637 for (const auto& mode2 : sortedModes) {
638 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800639 mSupportsFrameRateOverride = true;
640 break;
641 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800642 }
643 }
644 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800645
Ady Abrahamabc27602020-04-08 17:20:29 -0700646 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800647}
648
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100649bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100650 // defaultMode must be a valid mode, and within the given refresh rate range.
651 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700652 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100653 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700654 return false;
655 }
656 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700657 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100658 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700659 return false;
660 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100661 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
662 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700663}
664
665status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800666 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100667 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100668 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100669 return BAD_VALUE;
670 }
Steven Thomasd4071902020-03-24 16:02:53 -0700671 Policy previousPolicy = *getCurrentPolicyLocked();
672 mDisplayManagerPolicy = policy;
673 if (*getCurrentPolicyLocked() == previousPolicy) {
674 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100675 }
Ady Abraham2139f732019-11-13 18:56:40 -0800676 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100677 return NO_ERROR;
678}
679
Steven Thomasd4071902020-03-24 16:02:53 -0700680status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100681 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100682 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700683 return BAD_VALUE;
684 }
685 Policy previousPolicy = *getCurrentPolicyLocked();
686 mOverridePolicy = policy;
687 if (*getCurrentPolicyLocked() == previousPolicy) {
688 return CURRENT_POLICY_UNCHANGED;
689 }
690 constructAvailableRefreshRates();
691 return NO_ERROR;
692}
693
694const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
695 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
696}
697
698RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
699 std::lock_guard lock(mLock);
700 return *getCurrentPolicyLocked();
701}
702
703RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
704 std::lock_guard lock(mLock);
705 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100706}
707
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100708bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100709 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700710 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100711 if (refreshRate->modeId == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100712 return true;
713 }
714 }
715 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800716}
717
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100718void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800719 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
720 std::vector<const RefreshRate*>* outRefreshRates) {
721 outRefreshRates->clear();
722 outRefreshRates->reserve(mRefreshRates.size());
723 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800724 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100725 ALOGV("getSortedRefreshRateListLocked: mode %zu added to list policy",
726 refreshRate->modeId.value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800727 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800728 }
729 }
730
731 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
732 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100733 if (refreshRate1->mode->getVsyncPeriod() !=
734 refreshRate2->mode->getVsyncPeriod()) {
735 return refreshRate1->mode->getVsyncPeriod() >
736 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700737 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100738 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700739 }
Ady Abraham2139f732019-11-13 18:56:40 -0800740 });
741}
742
743void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100744 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700745 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100746 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100747 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700748
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100749 auto filterRefreshRates =
750 [&](Fps min, Fps max, const char* listName,
751 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
752 getSortedRefreshRateListLocked(
753 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
754 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800755
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100756 return mode->getHeight() == defaultMode->getHeight() &&
757 mode->getWidth() == defaultMode->getWidth() &&
758 mode->getDpiX() == defaultMode->getDpiX() &&
759 mode->getDpiY() == defaultMode->getDpiY() &&
760 (policy->allowGroupSwitching ||
761 mode->getGroup() == defaultMode->getGroup()) &&
762 refreshRate.inPolicy(min, max);
763 },
764 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800765
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100766 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
767 "No matching modes for %s range: min=%s max=%s", listName,
768 to_string(min).c_str(), to_string(max).c_str());
769 auto stringifyRefreshRates = [&]() -> std::string {
770 std::string str;
771 for (auto refreshRate : *outRefreshRates) {
772 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
773 }
774 return str;
775 };
776 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
777 };
Steven Thomasf734df42020-04-13 21:09:28 -0700778
779 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
780 &mPrimaryRefreshRates);
781 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
782 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800783}
784
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100785Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
786 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700787 return *mKnownFrameRates.begin();
788 }
789
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100790 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700791 return *std::prev(mKnownFrameRates.end());
792 }
793
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100794 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
795 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700796
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100797 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
798 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700799 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
800}
801
Ana Krulecb9afd792020-06-11 13:16:15 -0700802RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
803 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100804 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700805 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
806 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
807
808 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
809 // the min allowed refresh rate is higher than the device min, we do not want to enable the
810 // timer.
811 if (deviceMin < minByPolicy) {
812 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
813 }
814 if (minByPolicy == maxByPolicy) {
815 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
816 // max are all the same. This saves us extra unnecessary calls to sysprop.
817 if (deviceMin == minByPolicy) {
818 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
819 }
820 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
821 }
822 // Turn on the timer in all other cases.
823 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
824}
825
Ady Abraham62a0be22020-12-08 16:54:10 -0800826int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700827 // This calculation needs to be in sync with the java code
828 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
829 constexpr float kThreshold = 0.1f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800830 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700831 const auto numPeriodsRounded = std::round(numPeriods);
832 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800833 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700834 }
835
Ady Abraham62f216c2020-10-13 19:07:23 -0700836 return static_cast<int>(numPeriodsRounded);
837}
838
Ady Abraham62a0be22020-12-08 16:54:10 -0800839int RefreshRateConfigs::getRefreshRateDivider(Fps frameRate) const {
Ady Abraham62f216c2020-10-13 19:07:23 -0700840 std::lock_guard lock(mLock);
Ady Abraham62a0be22020-12-08 16:54:10 -0800841 return getFrameRateDivider(mCurrentRefreshRate->getFps(), frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700842}
843
Marin Shalamanovba421a82020-11-10 21:49:26 +0100844void RefreshRateConfigs::dump(std::string& result) const {
845 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100846 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100847 mDisplayManagerPolicy.toString().c_str());
848 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
849 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100850 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100851 currentPolicy.toString().c_str());
852 }
853
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100854 auto mode = mCurrentRefreshRate->mode;
855 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100856
857 result.append("Refresh rates:\n");
858 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100859 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +0100860 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
861 }
862
Ady Abraham64c2fc02020-12-29 12:07:50 -0800863 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
864 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100865 result.append("\n");
866}
867
Ady Abraham2139f732019-11-13 18:56:40 -0800868} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100869
870// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800871#pragma clang diagnostic pop // ignored "-Wextra"