blob: 0eb16e2384c9af963fa88658b2cfd0de6556efc8 [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 Abraham5e4e9832021-06-14 13:40:56 -0700425 const bool touchBoostForExplicitExact = [&] {
426 if (mSupportsFrameRateOverride) {
427 // Enable touch boost if there are other layers besides exact
428 return explicitExact + noVoteLayers != layers.size();
429 } else {
430 // Enable touch boost if there are no exact layers
431 return explicitExact == 0;
432 }
433 }();
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800434 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100435 bestRefreshRate->fps.lessThanWithMargin(touchRefreshRate.fps)) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700436 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700437 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700438 return touchRefreshRate;
439 }
440
Ady Abrahamde7156e2020-02-28 17:29:39 -0800441 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800442}
443
Ady Abraham62a0be22020-12-08 16:54:10 -0800444std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
445groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
446 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
447 for (const auto& layer : layers) {
448 auto iter = layersByUid.emplace(layer.ownerUid,
449 std::vector<const RefreshRateConfigs::LayerRequirement*>());
450 auto& layersWithSameUid = iter.first->second;
451 layersWithSameUid.push_back(&layer);
452 }
453
454 // Remove uids that can't have a frame rate override
455 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
456 const auto& layersWithSameUid = iter->second;
457 bool skipUid = false;
458 for (const auto& layer : layersWithSameUid) {
459 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
460 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
461 skipUid = true;
462 break;
463 }
464 }
465 if (skipUid) {
466 iter = layersByUid.erase(iter);
467 } else {
468 ++iter;
469 }
470 }
471
472 return layersByUid;
473}
474
475std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
476 const AllRefreshRatesMapType& refreshRates) {
477 std::vector<RefreshRateScore> scores;
478 scores.reserve(refreshRates.size());
479 for (const auto& [ignored, refreshRate] : refreshRates) {
480 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
481 }
482 std::sort(scores.begin(), scores.end(),
483 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
484 return scores;
485}
486
487RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800488 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800489 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800490 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800491
Ady Abraham64c2fc02020-12-29 12:07:50 -0800492 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800493 std::lock_guard lock(mLock);
494 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
495 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
496 groupLayersByUid(layers);
497 UidToFrameRateOverride frameRateOverrides;
498 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800499 // Layers with ExplicitExactOrMultiple expect touch boost
500 const bool hasExplicitExactOrMultiple =
501 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
502 [](const auto& layer) {
503 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
504 });
505
506 if (touch && hasExplicitExactOrMultiple) {
507 continue;
508 }
509
Ady Abraham62a0be22020-12-08 16:54:10 -0800510 for (auto& score : scores) {
511 score.score = 0;
512 }
513
514 for (const auto& layer : layersWithSameUid) {
515 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
516 continue;
517 }
518
519 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800520 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
521 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800522 for (RefreshRateScore& score : scores) {
523 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
524 /*isSeamlessSwitch*/ true);
525 score.score += layer->weight * layerScore;
526 }
527 }
528
529 // We just care about the refresh rates which are a divider of the
530 // display refresh rate
531 auto iter =
532 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
533 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
534 });
535 scores.erase(iter, scores.end());
536
537 // If we never scored any layers, we don't have a preferred frame rate
538 if (std::all_of(scores.begin(), scores.end(),
539 [](const RefreshRateScore& score) { return score.score == 0; })) {
540 continue;
541 }
542
543 // Now that we scored all the refresh rates we need to pick the one that got the highest
544 // score.
545 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700546 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800547 }
548
549 return frameRateOverrides;
550}
551
Ady Abraham34702102020-02-10 14:12:05 -0800552template <typename Iter>
553const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800554 constexpr auto EPSILON = 0.001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800555 const RefreshRate* bestRefreshRate = begin->refreshRate;
556 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800557 for (auto i = begin; i != end; ++i) {
558 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100559 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800560
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100561 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800562
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800563 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800564 max = score;
565 bestRefreshRate = refreshRate;
566 }
567 }
568
Ady Abraham34702102020-02-10 14:12:05 -0800569 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800570}
571
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100572std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100573 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800574 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100575
576 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
577 : *mCurrentRefreshRate;
578 const auto& min = *mMinSupportedRefreshRate;
579
580 if (current != min) {
581 const auto& refreshRate = timerExpired ? min : current;
582 return refreshRate.getFps();
583 }
584
585 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700586}
587
588const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200589 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100590 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200591 return *refreshRate;
592 }
593 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100594 ALOGE("Can't find min refresh rate by policy with the same mode group"
595 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200596 mCurrentRefreshRate->toString().c_str());
597 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700598 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800599}
600
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100601RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800602 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700603 return getMaxRefreshRateByPolicyLocked();
604}
605
606const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200607 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
608 const auto& refreshRate = (**it);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100609 if (mCurrentRefreshRate->getModeGroup() == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200610 return refreshRate;
611 }
612 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100613 ALOGE("Can't find max refresh rate by policy with the same mode group"
614 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200615 mCurrentRefreshRate->toString().c_str());
616 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700617 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800618}
619
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100620RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800621 std::lock_guard lock(mLock);
622 return *mCurrentRefreshRate;
623}
624
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100625RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800626 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800627 return getCurrentRefreshRateByPolicyLocked();
628}
629
630const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700631 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
632 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800633 return *mCurrentRefreshRate;
634 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100635 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800636}
637
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100638void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800639 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200640
641 // Invalidate the cached invocation to getBestRefreshRate. This forces
642 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
643 lastBestRefreshRateInvocation.reset();
644
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100645 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800646}
647
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100648RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800649 bool enableFrameRateOverride)
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100650 : mKnownFrameRates(constructKnownFrameRates(modes)),
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800651 mEnableFrameRateOverride(enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100652 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100653}
654
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100655void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
656 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100657 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200658
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100659 // The current mode should be supported
660 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
661 return mode->getId() == currentModeId;
662 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700663
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200664 // Invalidate the cached invocation to getBestRefreshRate. This forces
665 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
666 lastBestRefreshRateInvocation.reset();
667
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100668 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100669 for (const auto& mode : modes) {
670 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100671 mRefreshRates.emplace(modeId,
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100672 std::make_unique<RefreshRate>(modeId, mode, mode->getFps(),
Ady Abrahamabc27602020-04-08 17:20:29 -0700673 RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100674 if (modeId == currentModeId) {
675 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700676 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800677 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700678
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100679 std::vector<const RefreshRate*> sortedModes;
680 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100681 // Reset the policy because the old one may no longer be valid.
682 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100683 mDisplayManagerPolicy.defaultMode = currentModeId;
684 mMinSupportedRefreshRate = sortedModes.front();
685 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800686
687 mSupportsFrameRateOverride = false;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800688 if (mEnableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100689 for (const auto& mode1 : sortedModes) {
690 for (const auto& mode2 : sortedModes) {
691 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800692 mSupportsFrameRateOverride = true;
693 break;
694 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800695 }
696 }
697 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800698
Ady Abrahamabc27602020-04-08 17:20:29 -0700699 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800700}
701
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100702bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100703 // defaultMode must be a valid mode, and within the given refresh rate range.
704 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700705 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100706 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700707 return false;
708 }
709 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700710 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100711 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700712 return false;
713 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100714 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
715 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700716}
717
718status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800719 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100720 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100721 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100722 return BAD_VALUE;
723 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200724 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700725 Policy previousPolicy = *getCurrentPolicyLocked();
726 mDisplayManagerPolicy = policy;
727 if (*getCurrentPolicyLocked() == previousPolicy) {
728 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100729 }
Ady Abraham2139f732019-11-13 18:56:40 -0800730 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100731 return NO_ERROR;
732}
733
Steven Thomasd4071902020-03-24 16:02:53 -0700734status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100735 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100736 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700737 return BAD_VALUE;
738 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200739 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700740 Policy previousPolicy = *getCurrentPolicyLocked();
741 mOverridePolicy = policy;
742 if (*getCurrentPolicyLocked() == previousPolicy) {
743 return CURRENT_POLICY_UNCHANGED;
744 }
745 constructAvailableRefreshRates();
746 return NO_ERROR;
747}
748
749const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
750 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
751}
752
753RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
754 std::lock_guard lock(mLock);
755 return *getCurrentPolicyLocked();
756}
757
758RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
759 std::lock_guard lock(mLock);
760 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100761}
762
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100763bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100764 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700765 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100766 if (refreshRate->modeId == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100767 return true;
768 }
769 }
770 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800771}
772
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100773void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800774 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
775 std::vector<const RefreshRate*>* outRefreshRates) {
776 outRefreshRates->clear();
777 outRefreshRates->reserve(mRefreshRates.size());
778 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800779 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100780 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100781 refreshRate->modeId.value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800782 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800783 }
784 }
785
786 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
787 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100788 if (refreshRate1->mode->getVsyncPeriod() !=
789 refreshRate2->mode->getVsyncPeriod()) {
790 return refreshRate1->mode->getVsyncPeriod() >
791 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700792 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100793 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700794 }
Ady Abraham2139f732019-11-13 18:56:40 -0800795 });
796}
797
798void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100799 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700800 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100801 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100802 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700803
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100804 auto filterRefreshRates =
805 [&](Fps min, Fps max, const char* listName,
806 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
807 getSortedRefreshRateListLocked(
808 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
809 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800810
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100811 return mode->getHeight() == defaultMode->getHeight() &&
812 mode->getWidth() == defaultMode->getWidth() &&
813 mode->getDpiX() == defaultMode->getDpiX() &&
814 mode->getDpiY() == defaultMode->getDpiY() &&
815 (policy->allowGroupSwitching ||
816 mode->getGroup() == defaultMode->getGroup()) &&
817 refreshRate.inPolicy(min, max);
818 },
819 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800820
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100821 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
822 "No matching modes for %s range: min=%s max=%s", listName,
823 to_string(min).c_str(), to_string(max).c_str());
824 auto stringifyRefreshRates = [&]() -> std::string {
825 std::string str;
826 for (auto refreshRate : *outRefreshRates) {
827 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
828 }
829 return str;
830 };
831 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
832 };
Steven Thomasf734df42020-04-13 21:09:28 -0700833
834 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
835 &mPrimaryRefreshRates);
836 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
837 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800838}
839
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100840Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
841 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700842 return *mKnownFrameRates.begin();
843 }
844
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100845 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700846 return *std::prev(mKnownFrameRates.end());
847 }
848
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100849 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
850 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700851
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100852 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
853 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700854 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
855}
856
Ana Krulecb9afd792020-06-11 13:16:15 -0700857RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
858 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100859 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700860 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
861 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
862
863 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
864 // the min allowed refresh rate is higher than the device min, we do not want to enable the
865 // timer.
866 if (deviceMin < minByPolicy) {
867 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
868 }
869 if (minByPolicy == maxByPolicy) {
Ana Krulecb9afd792020-06-11 13:16:15 -0700870 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
871 }
872 // Turn on the timer in all other cases.
873 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
874}
875
Ady Abraham62a0be22020-12-08 16:54:10 -0800876int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700877 // This calculation needs to be in sync with the java code
878 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
879 constexpr float kThreshold = 0.1f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800880 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700881 const auto numPeriodsRounded = std::round(numPeriods);
882 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800883 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700884 }
885
Ady Abraham62f216c2020-10-13 19:07:23 -0700886 return static_cast<int>(numPeriodsRounded);
887}
888
Marin Shalamanovba421a82020-11-10 21:49:26 +0100889void RefreshRateConfigs::dump(std::string& result) const {
890 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100891 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100892 mDisplayManagerPolicy.toString().c_str());
893 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
894 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100895 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100896 currentPolicy.toString().c_str());
897 }
898
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100899 auto mode = mCurrentRefreshRate->mode;
900 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100901
902 result.append("Refresh rates:\n");
903 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100904 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +0100905 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
906 }
907
Ady Abraham64c2fc02020-12-29 12:07:50 -0800908 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
909 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100910 result.append("\n");
911}
912
Ady Abraham2139f732019-11-13 18:56:40 -0800913} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100914
915// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800916#pragma clang diagnostic pop // ignored "-Wextra"