blob: 974607604061d07adfee137ee197a51e2d52b3be [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 {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200193 std::lock_guard lock(mLock);
194
195 if (auto cached = getCachedBestRefreshRate(layers, globalSignals, outSignalsConsidered)) {
196 return *cached;
197 }
198
199 GlobalSignals signalsConsidered;
200 RefreshRate result = getBestRefreshRateLocked(layers, globalSignals, &signalsConsidered);
201 lastBestRefreshRateInvocation.emplace(
202 GetBestRefreshRateInvocation{.layerRequirements = layers,
203 .globalSignals = globalSignals,
204 .outSignalsConsidered = signalsConsidered,
205 .resultingBestRefreshRate = result});
206 if (outSignalsConsidered) {
207 *outSignalsConsidered = signalsConsidered;
208 }
209 return result;
210}
211
212std::optional<RefreshRate> RefreshRateConfigs::getCachedBestRefreshRate(
213 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
214 GlobalSignals* outSignalsConsidered) const {
215 const bool sameAsLastCall = lastBestRefreshRateInvocation &&
216 lastBestRefreshRateInvocation->layerRequirements == layers &&
217 lastBestRefreshRateInvocation->globalSignals == globalSignals;
218
219 if (sameAsLastCall) {
220 if (outSignalsConsidered) {
221 *outSignalsConsidered = lastBestRefreshRateInvocation->outSignalsConsidered;
222 }
223 return lastBestRefreshRateInvocation->resultingBestRefreshRate;
224 }
225
226 return {};
227}
228
229RefreshRate RefreshRateConfigs::getBestRefreshRateLocked(
230 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
231 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800232 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200233 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800234
Ady Abrahamdfd62162020-06-10 16:11:56 -0700235 if (outSignalsConsidered) *outSignalsConsidered = {};
236 const auto setTouchConsidered = [&] {
237 if (outSignalsConsidered) {
238 outSignalsConsidered->touch = true;
239 }
240 };
241
242 const auto setIdleConsidered = [&] {
243 if (outSignalsConsidered) {
244 outSignalsConsidered->idle = true;
245 }
246 };
247
Ady Abraham8a82ba62020-01-17 12:43:17 -0800248 int noVoteLayers = 0;
249 int minVoteLayers = 0;
250 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800251 int explicitDefaultVoteLayers = 0;
252 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800253 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800254 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100255 int seamedFocusedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800256 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800257 switch (layer.vote) {
258 case LayerVoteType::NoVote:
259 noVoteLayers++;
260 break;
261 case LayerVoteType::Min:
262 minVoteLayers++;
263 break;
264 case LayerVoteType::Max:
265 maxVoteLayers++;
266 break;
267 case LayerVoteType::ExplicitDefault:
268 explicitDefaultVoteLayers++;
269 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
270 break;
271 case LayerVoteType::ExplicitExactOrMultiple:
272 explicitExactOrMultipleVoteLayers++;
273 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
274 break;
275 case LayerVoteType::ExplicitExact:
276 explicitExact++;
277 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
278 break;
279 case LayerVoteType::Heuristic:
280 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800281 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200282
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100283 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
284 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200285 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800286 }
287
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800288 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
289 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700290
Steven Thomasf734df42020-04-13 21:09:28 -0700291 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
292 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700293 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700294 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700295 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700296 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800297 }
298
Alec Mouri11232a22020-05-14 18:06:25 -0700299 // If the primary range consists of a single refresh rate then we can only
300 // move out the of range if layers explicitly request a different refresh
301 // rate.
302 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100303 const bool primaryRangeIsSingleRate =
304 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700305
Ady Abrahamdfd62162020-06-10 16:11:56 -0700306 if (!globalSignals.touch && globalSignals.idle &&
307 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700308 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700309 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700310 return getMinRefreshRateByPolicyLocked();
311 }
312
Steven Thomasdebafed2020-05-18 17:30:35 -0700313 if (layers.empty() || noVoteLayers == layers.size()) {
314 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700315 }
316
Ady Abraham8a82ba62020-01-17 12:43:17 -0800317 // Only if all layers want Min we should return Min
318 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700319 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700320 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800321 }
322
Ady Abraham8a82ba62020-01-17 12:43:17 -0800323 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800324 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700325 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800326
Steven Thomasf734df42020-04-13 21:09:28 -0700327 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800328 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800329 }
330
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100331 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
Marin Shalamanov46084422020-10-13 12:33:42 +0200332
Ady Abraham8a82ba62020-01-17 12:43:17 -0800333 for (const auto& layer : layers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700334 ALOGV("Calculating score for %s (%s, weight %.2f)", layer.name.c_str(),
335 layerVoteTypeString(layer.vote).c_str(), layer.weight);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800336 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800337 continue;
338 }
339
Ady Abraham71c437d2020-01-31 15:56:57 -0800340 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800341
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800342 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100343 const bool isSeamlessSwitch =
344 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200345
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100346 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100347 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800348 formatLayerInfo(layer, weight).c_str(),
349 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100350 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200351 continue;
352 }
353
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100354 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
355 !layer.focused) {
356 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100357 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800358 formatLayerInfo(layer, weight).c_str(),
359 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100360 mCurrentRefreshRate->toString().c_str());
361 continue;
362 }
363
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100364 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100365 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100366 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100367 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
368 // disappeared.
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100369 const bool isInPolicyForDefault = seamedFocusedLayers > 0
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100370 ? scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup()
371 : scores[i].refreshRate->getModeGroup() == defaultMode->getModeGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100372
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100373 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100374 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800375 scores[i].refreshRate->toString().c_str(),
376 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200377 continue;
378 }
379
Ady Abraham62a0be22020-12-08 16:54:10 -0800380 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
381 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700382 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800383 !(layer.focused &&
384 (layer.vote == LayerVoteType::ExplicitDefault ||
385 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700386 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700387 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700388 continue;
389 }
390
Ady Abraham62a0be22020-12-08 16:54:10 -0800391 const auto layerScore =
392 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
393 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
394 scores[i].refreshRate->getName().c_str(), layerScore);
395 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800396 }
397 }
398
Ady Abraham34702102020-02-10 14:12:05 -0800399 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
400 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
401 // or the lower otherwise.
402 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
403 ? getBestRefreshRate(scores.rbegin(), scores.rend())
404 : getBestRefreshRate(scores.begin(), scores.end());
405
Alec Mouri11232a22020-05-14 18:06:25 -0700406 if (primaryRangeIsSingleRate) {
407 // If we never scored any layers, then choose the rate from the primary
408 // range instead of picking a random score from the app range.
409 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800410 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700411 ALOGV("layers not scored - choose %s",
412 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700413 return getMaxRefreshRateByPolicyLocked();
414 } else {
415 return *bestRefreshRate;
416 }
417 }
418
Steven Thomasf734df42020-04-13 21:09:28 -0700419 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
420 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
421 // vote we should not change it if we get a touch event. Only apply touch boost if it will
422 // actually increase the refresh rate over the normal selection.
423 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700424
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800425 bool touchBoostForExplicitExact = explicitExact == 0 || mSupportsFrameRateOverride;
426 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100427 bestRefreshRate->fps.lessThanWithMargin(touchRefreshRate.fps)) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700428 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700429 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700430 return touchRefreshRate;
431 }
432
Ady Abrahamde7156e2020-02-28 17:29:39 -0800433 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800434}
435
Ady Abraham62a0be22020-12-08 16:54:10 -0800436std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
437groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
438 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
439 for (const auto& layer : layers) {
440 auto iter = layersByUid.emplace(layer.ownerUid,
441 std::vector<const RefreshRateConfigs::LayerRequirement*>());
442 auto& layersWithSameUid = iter.first->second;
443 layersWithSameUid.push_back(&layer);
444 }
445
446 // Remove uids that can't have a frame rate override
447 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
448 const auto& layersWithSameUid = iter->second;
449 bool skipUid = false;
450 for (const auto& layer : layersWithSameUid) {
451 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
452 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
453 skipUid = true;
454 break;
455 }
456 }
457 if (skipUid) {
458 iter = layersByUid.erase(iter);
459 } else {
460 ++iter;
461 }
462 }
463
464 return layersByUid;
465}
466
467std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
468 const AllRefreshRatesMapType& refreshRates) {
469 std::vector<RefreshRateScore> scores;
470 scores.reserve(refreshRates.size());
471 for (const auto& [ignored, refreshRate] : refreshRates) {
472 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
473 }
474 std::sort(scores.begin(), scores.end(),
475 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
476 return scores;
477}
478
479RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800480 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800481 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800482 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800483
Ady Abraham64c2fc02020-12-29 12:07:50 -0800484 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800485 std::lock_guard lock(mLock);
486 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
487 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
488 groupLayersByUid(layers);
489 UidToFrameRateOverride frameRateOverrides;
490 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800491 // Layers with ExplicitExactOrMultiple expect touch boost
492 const bool hasExplicitExactOrMultiple =
493 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
494 [](const auto& layer) {
495 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
496 });
497
498 if (touch && hasExplicitExactOrMultiple) {
499 continue;
500 }
501
Ady Abraham62a0be22020-12-08 16:54:10 -0800502 for (auto& score : scores) {
503 score.score = 0;
504 }
505
506 for (const auto& layer : layersWithSameUid) {
507 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
508 continue;
509 }
510
511 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800512 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
513 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800514 for (RefreshRateScore& score : scores) {
515 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
516 /*isSeamlessSwitch*/ true);
517 score.score += layer->weight * layerScore;
518 }
519 }
520
521 // We just care about the refresh rates which are a divider of the
522 // display refresh rate
523 auto iter =
524 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
525 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
526 });
527 scores.erase(iter, scores.end());
528
529 // If we never scored any layers, we don't have a preferred frame rate
530 if (std::all_of(scores.begin(), scores.end(),
531 [](const RefreshRateScore& score) { return score.score == 0; })) {
532 continue;
533 }
534
535 // Now that we scored all the refresh rates we need to pick the one that got the highest
536 // score.
537 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700538 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800539 }
540
541 return frameRateOverrides;
542}
543
Ady Abraham34702102020-02-10 14:12:05 -0800544template <typename Iter>
545const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800546 constexpr auto EPSILON = 0.001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800547 const RefreshRate* bestRefreshRate = begin->refreshRate;
548 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800549 for (auto i = begin; i != end; ++i) {
550 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100551 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800552
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100553 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800554
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800555 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800556 max = score;
557 bestRefreshRate = refreshRate;
558 }
559 }
560
Ady Abraham34702102020-02-10 14:12:05 -0800561 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800562}
563
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100564std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100565 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800566 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100567
568 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
569 : *mCurrentRefreshRate;
570 const auto& min = *mMinSupportedRefreshRate;
571
572 if (current != min) {
573 const auto& refreshRate = timerExpired ? min : current;
574 return refreshRate.getFps();
575 }
576
577 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700578}
579
580const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200581 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100582 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200583 return *refreshRate;
584 }
585 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100586 ALOGE("Can't find min refresh rate by policy with the same mode group"
587 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200588 mCurrentRefreshRate->toString().c_str());
589 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700590 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800591}
592
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100593RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800594 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700595 return getMaxRefreshRateByPolicyLocked();
596}
597
598const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200599 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
600 const auto& refreshRate = (**it);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100601 if (mCurrentRefreshRate->getModeGroup() == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200602 return refreshRate;
603 }
604 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100605 ALOGE("Can't find max refresh rate by policy with the same mode group"
606 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200607 mCurrentRefreshRate->toString().c_str());
608 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700609 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800610}
611
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100612RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800613 std::lock_guard lock(mLock);
614 return *mCurrentRefreshRate;
615}
616
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100617RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800618 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800619 return getCurrentRefreshRateByPolicyLocked();
620}
621
622const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700623 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
624 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800625 return *mCurrentRefreshRate;
626 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100627 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800628}
629
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100630void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800631 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200632
633 // Invalidate the cached invocation to getBestRefreshRate. This forces
634 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
635 lastBestRefreshRateInvocation.reset();
636
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100637 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800638}
639
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100640RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800641 bool enableFrameRateOverride)
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100642 : mKnownFrameRates(constructKnownFrameRates(modes)),
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800643 mEnableFrameRateOverride(enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100644 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100645}
646
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100647void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
648 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100649 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200650
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100651 // The current mode should be supported
652 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
653 return mode->getId() == currentModeId;
654 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700655
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200656 // Invalidate the cached invocation to getBestRefreshRate. This forces
657 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
658 lastBestRefreshRateInvocation.reset();
659
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100660 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100661 for (const auto& mode : modes) {
662 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100663 mRefreshRates.emplace(modeId,
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100664 std::make_unique<RefreshRate>(modeId, mode, mode->getFps(),
Ady Abrahamabc27602020-04-08 17:20:29 -0700665 RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100666 if (modeId == currentModeId) {
667 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700668 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800669 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700670
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100671 std::vector<const RefreshRate*> sortedModes;
672 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100673 // Reset the policy because the old one may no longer be valid.
674 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100675 mDisplayManagerPolicy.defaultMode = currentModeId;
676 mMinSupportedRefreshRate = sortedModes.front();
677 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800678
679 mSupportsFrameRateOverride = false;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800680 if (mEnableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100681 for (const auto& mode1 : sortedModes) {
682 for (const auto& mode2 : sortedModes) {
683 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800684 mSupportsFrameRateOverride = true;
685 break;
686 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800687 }
688 }
689 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800690
Ady Abrahamabc27602020-04-08 17:20:29 -0700691 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800692}
693
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100694bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100695 // defaultMode must be a valid mode, and within the given refresh rate range.
696 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700697 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100698 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700699 return false;
700 }
701 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700702 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100703 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700704 return false;
705 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100706 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
707 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700708}
709
710status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800711 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100712 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100713 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100714 return BAD_VALUE;
715 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200716 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700717 Policy previousPolicy = *getCurrentPolicyLocked();
718 mDisplayManagerPolicy = policy;
719 if (*getCurrentPolicyLocked() == previousPolicy) {
720 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100721 }
Ady Abraham2139f732019-11-13 18:56:40 -0800722 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100723 return NO_ERROR;
724}
725
Steven Thomasd4071902020-03-24 16:02:53 -0700726status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100727 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100728 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700729 return BAD_VALUE;
730 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200731 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700732 Policy previousPolicy = *getCurrentPolicyLocked();
733 mOverridePolicy = policy;
734 if (*getCurrentPolicyLocked() == previousPolicy) {
735 return CURRENT_POLICY_UNCHANGED;
736 }
737 constructAvailableRefreshRates();
738 return NO_ERROR;
739}
740
741const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
742 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
743}
744
745RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
746 std::lock_guard lock(mLock);
747 return *getCurrentPolicyLocked();
748}
749
750RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
751 std::lock_guard lock(mLock);
752 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100753}
754
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100755bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100756 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700757 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100758 if (refreshRate->modeId == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100759 return true;
760 }
761 }
762 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800763}
764
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100765void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800766 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
767 std::vector<const RefreshRate*>* outRefreshRates) {
768 outRefreshRates->clear();
769 outRefreshRates->reserve(mRefreshRates.size());
770 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800771 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100772 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100773 refreshRate->modeId.value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800774 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800775 }
776 }
777
778 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
779 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100780 if (refreshRate1->mode->getVsyncPeriod() !=
781 refreshRate2->mode->getVsyncPeriod()) {
782 return refreshRate1->mode->getVsyncPeriod() >
783 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700784 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100785 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700786 }
Ady Abraham2139f732019-11-13 18:56:40 -0800787 });
788}
789
790void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100791 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700792 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100793 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100794 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700795
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100796 auto filterRefreshRates =
797 [&](Fps min, Fps max, const char* listName,
798 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
799 getSortedRefreshRateListLocked(
800 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
801 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800802
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100803 return mode->getHeight() == defaultMode->getHeight() &&
804 mode->getWidth() == defaultMode->getWidth() &&
805 mode->getDpiX() == defaultMode->getDpiX() &&
806 mode->getDpiY() == defaultMode->getDpiY() &&
807 (policy->allowGroupSwitching ||
808 mode->getGroup() == defaultMode->getGroup()) &&
809 refreshRate.inPolicy(min, max);
810 },
811 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800812
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100813 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
814 "No matching modes for %s range: min=%s max=%s", listName,
815 to_string(min).c_str(), to_string(max).c_str());
816 auto stringifyRefreshRates = [&]() -> std::string {
817 std::string str;
818 for (auto refreshRate : *outRefreshRates) {
819 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
820 }
821 return str;
822 };
823 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
824 };
Steven Thomasf734df42020-04-13 21:09:28 -0700825
826 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
827 &mPrimaryRefreshRates);
828 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
829 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800830}
831
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100832Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
833 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700834 return *mKnownFrameRates.begin();
835 }
836
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100837 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700838 return *std::prev(mKnownFrameRates.end());
839 }
840
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100841 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
842 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700843
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100844 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
845 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700846 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
847}
848
Ana Krulecb9afd792020-06-11 13:16:15 -0700849RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
850 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100851 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700852 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
853 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
854
855 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
856 // the min allowed refresh rate is higher than the device min, we do not want to enable the
857 // timer.
858 if (deviceMin < minByPolicy) {
859 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
860 }
861 if (minByPolicy == maxByPolicy) {
862 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
863 // max are all the same. This saves us extra unnecessary calls to sysprop.
864 if (deviceMin == minByPolicy) {
865 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
866 }
867 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
868 }
869 // Turn on the timer in all other cases.
870 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
871}
872
Ady Abraham62a0be22020-12-08 16:54:10 -0800873int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700874 // This calculation needs to be in sync with the java code
875 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
876 constexpr float kThreshold = 0.1f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800877 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700878 const auto numPeriodsRounded = std::round(numPeriods);
879 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800880 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700881 }
882
Ady Abraham62f216c2020-10-13 19:07:23 -0700883 return static_cast<int>(numPeriodsRounded);
884}
885
Marin Shalamanovba421a82020-11-10 21:49:26 +0100886void RefreshRateConfigs::dump(std::string& result) const {
887 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100888 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100889 mDisplayManagerPolicy.toString().c_str());
890 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
891 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100892 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100893 currentPolicy.toString().c_str());
894 }
895
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100896 auto mode = mCurrentRefreshRate->mode;
897 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100898
899 result.append("Refresh rates:\n");
900 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100901 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +0100902 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
903 }
904
Ady Abraham64c2fc02020-12-29 12:07:50 -0800905 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
906 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100907 result.append("\n");
908}
909
Ady Abraham2139f732019-11-13 18:56:40 -0800910} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100911
912// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800913#pragma clang diagnostic pop // ignored "-Wextra"