blob: 0e4256b3961358dcc91462e4071ac2906a9d14e3 [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 Shalamanov228f46b2021-01-28 21:11:45 +010067 return base::StringPrintf("{id=%d, 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 Shalamanov228f46b2021-01-28 21:11:45 +010092 return base::StringPrintf("default mode ID: %d, 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 Shalamanovae0b5352021-03-24 12:56:08 +0100218 int seamedFocusedLayers = 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 Shalamanovae0b5352021-03-24 12:56:08 +0100246 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
247 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200248 }
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.
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100332 const bool isInPolicyForDefault = seamedFocusedLayers > 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
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100336 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100337 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800338 scores[i].refreshRate->toString().c_str(),
339 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200340 continue;
341 }
342
Ady Abraham62a0be22020-12-08 16:54:10 -0800343 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
344 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700345 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800346 !(layer.focused &&
347 (layer.vote == LayerVoteType::ExplicitDefault ||
348 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700349 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700350 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700351 continue;
352 }
353
Ady Abraham62a0be22020-12-08 16:54:10 -0800354 const auto layerScore =
355 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
356 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
357 scores[i].refreshRate->getName().c_str(), layerScore);
358 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800359 }
360 }
361
Ady Abraham34702102020-02-10 14:12:05 -0800362 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
363 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
364 // or the lower otherwise.
365 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
366 ? getBestRefreshRate(scores.rbegin(), scores.rend())
367 : getBestRefreshRate(scores.begin(), scores.end());
368
Alec Mouri11232a22020-05-14 18:06:25 -0700369 if (primaryRangeIsSingleRate) {
370 // If we never scored any layers, then choose the rate from the primary
371 // range instead of picking a random score from the app range.
372 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800373 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700374 ALOGV("layers not scored - choose %s",
375 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700376 return getMaxRefreshRateByPolicyLocked();
377 } else {
378 return *bestRefreshRate;
379 }
380 }
381
Steven Thomasf734df42020-04-13 21:09:28 -0700382 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
383 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
384 // vote we should not change it if we get a touch event. Only apply touch boost if it will
385 // actually increase the refresh rate over the normal selection.
386 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700387
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800388 bool touchBoostForExplicitExact = explicitExact == 0 || mSupportsFrameRateOverride;
389 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100390 bestRefreshRate->fps.lessThanWithMargin(touchRefreshRate.fps)) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700391 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700392 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700393 return touchRefreshRate;
394 }
395
Ady Abrahamde7156e2020-02-28 17:29:39 -0800396 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800397}
398
Ady Abraham62a0be22020-12-08 16:54:10 -0800399std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
400groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
401 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
402 for (const auto& layer : layers) {
403 auto iter = layersByUid.emplace(layer.ownerUid,
404 std::vector<const RefreshRateConfigs::LayerRequirement*>());
405 auto& layersWithSameUid = iter.first->second;
406 layersWithSameUid.push_back(&layer);
407 }
408
409 // Remove uids that can't have a frame rate override
410 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
411 const auto& layersWithSameUid = iter->second;
412 bool skipUid = false;
413 for (const auto& layer : layersWithSameUid) {
414 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
415 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
416 skipUid = true;
417 break;
418 }
419 }
420 if (skipUid) {
421 iter = layersByUid.erase(iter);
422 } else {
423 ++iter;
424 }
425 }
426
427 return layersByUid;
428}
429
430std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
431 const AllRefreshRatesMapType& refreshRates) {
432 std::vector<RefreshRateScore> scores;
433 scores.reserve(refreshRates.size());
434 for (const auto& [ignored, refreshRate] : refreshRates) {
435 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
436 }
437 std::sort(scores.begin(), scores.end(),
438 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
439 return scores;
440}
441
442RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800443 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800444 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800445 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800446
Ady Abraham64c2fc02020-12-29 12:07:50 -0800447 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800448 std::lock_guard lock(mLock);
449 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
450 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
451 groupLayersByUid(layers);
452 UidToFrameRateOverride frameRateOverrides;
453 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800454 // Layers with ExplicitExactOrMultiple expect touch boost
455 const bool hasExplicitExactOrMultiple =
456 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
457 [](const auto& layer) {
458 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
459 });
460
461 if (touch && hasExplicitExactOrMultiple) {
462 continue;
463 }
464
Ady Abraham62a0be22020-12-08 16:54:10 -0800465 for (auto& score : scores) {
466 score.score = 0;
467 }
468
469 for (const auto& layer : layersWithSameUid) {
470 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
471 continue;
472 }
473
474 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800475 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
476 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800477 for (RefreshRateScore& score : scores) {
478 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
479 /*isSeamlessSwitch*/ true);
480 score.score += layer->weight * layerScore;
481 }
482 }
483
484 // We just care about the refresh rates which are a divider of the
485 // display refresh rate
486 auto iter =
487 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
488 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
489 });
490 scores.erase(iter, scores.end());
491
492 // If we never scored any layers, we don't have a preferred frame rate
493 if (std::all_of(scores.begin(), scores.end(),
494 [](const RefreshRateScore& score) { return score.score == 0; })) {
495 continue;
496 }
497
498 // Now that we scored all the refresh rates we need to pick the one that got the highest
499 // score.
500 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
501
502 // If the nest refresh rate is the current one, we don't have an override
503 if (!bestRefreshRate->getFps().equalsWithMargin(displayFrameRate)) {
504 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
505 }
506 }
507
508 return frameRateOverrides;
509}
510
Ady Abraham34702102020-02-10 14:12:05 -0800511template <typename Iter>
512const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800513 constexpr auto EPSILON = 0.001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800514 const RefreshRate* bestRefreshRate = begin->refreshRate;
515 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800516 for (auto i = begin; i != end; ++i) {
517 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100518 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800519
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100520 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800521
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800522 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800523 max = score;
524 bestRefreshRate = refreshRate;
525 }
526 }
527
Ady Abraham34702102020-02-10 14:12:05 -0800528 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800529}
530
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100531std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100532 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800533 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100534
535 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
536 : *mCurrentRefreshRate;
537 const auto& min = *mMinSupportedRefreshRate;
538
539 if (current != min) {
540 const auto& refreshRate = timerExpired ? min : current;
541 return refreshRate.getFps();
542 }
543
544 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700545}
546
547const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200548 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100549 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200550 return *refreshRate;
551 }
552 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100553 ALOGE("Can't find min refresh rate by policy with the same mode group"
554 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200555 mCurrentRefreshRate->toString().c_str());
556 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700557 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800558}
559
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100560RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800561 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700562 return getMaxRefreshRateByPolicyLocked();
563}
564
565const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200566 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
567 const auto& refreshRate = (**it);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100568 if (mCurrentRefreshRate->getModeGroup() == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200569 return refreshRate;
570 }
571 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100572 ALOGE("Can't find max refresh rate by policy with the same mode group"
573 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200574 mCurrentRefreshRate->toString().c_str());
575 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700576 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800577}
578
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100579RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800580 std::lock_guard lock(mLock);
581 return *mCurrentRefreshRate;
582}
583
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100584RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800585 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800586 return getCurrentRefreshRateByPolicyLocked();
587}
588
589const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700590 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
591 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800592 return *mCurrentRefreshRate;
593 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100594 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800595}
596
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100597void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800598 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100599 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800600}
601
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100602RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800603 bool enableFrameRateOverride)
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100604 : mKnownFrameRates(constructKnownFrameRates(modes)),
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800605 mEnableFrameRateOverride(enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100606 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100607}
608
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100609void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
610 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100611 std::lock_guard lock(mLock);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100612 // The current mode should be supported
613 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
614 return mode->getId() == currentModeId;
615 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700616
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100617 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100618 for (const auto& mode : modes) {
619 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100620 mRefreshRates.emplace(modeId,
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100621 std::make_unique<RefreshRate>(modeId, mode, mode->getFps(),
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 Shalamanov228f46b2021-01-28 21:11:45 +0100727 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100728 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"