blob: e922d46a4069468af88de835859e9488c7ee0564 [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
rnlee3bd610662021-06-23 16:27:57 -0700110bool RefreshRateConfigs::isVoteAllowed(const LayerRequirement& layer,
111 const RefreshRate& refreshRate) const {
112 switch (layer.vote) {
113 case LayerVoteType::ExplicitExactOrMultiple:
114 case LayerVoteType::Heuristic:
115 if (mConfig.frameRateMultipleThreshold != 0 &&
Ady Abraham6b7ad652021-06-23 17:34:57 -0700116 refreshRate.getFps().greaterThanOrEqualWithMargin(
rnlee3bd610662021-06-23 16:27:57 -0700117 Fps(mConfig.frameRateMultipleThreshold)) &&
118 layer.desiredRefreshRate.lessThanWithMargin(
119 Fps(mConfig.frameRateMultipleThreshold / 2))) {
120 // Don't vote high refresh rates past the threshold for layers with a low desired
121 // refresh rate. For example, desired 24 fps with 120 Hz threshold means no vote for
122 // 120 Hz, but desired 60 fps should have a vote.
123 return false;
124 }
125 break;
126 case LayerVoteType::ExplicitDefault:
127 case LayerVoteType::ExplicitExact:
128 case LayerVoteType::Max:
129 case LayerVoteType::Min:
130 case LayerVoteType::NoVote:
131 break;
132 }
133 return true;
134}
135
Ady Abraham62a0be22020-12-08 16:54:10 -0800136float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
137 const RefreshRate& refreshRate,
138 bool isSeamlessSwitch) const {
rnlee3bd610662021-06-23 16:27:57 -0700139 if (!isVoteAllowed(layer, refreshRate)) {
140 return 0;
141 }
142
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200143 constexpr float kScoreForFractionalPairs = .8f;
144
Ady Abraham62a0be22020-12-08 16:54:10 -0800145 // Slightly prefer seamless switches.
146 constexpr float kSeamedSwitchPenalty = 0.95f;
147 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
148
149 // If the layer wants Max, give higher score to the higher refresh rate
150 if (layer.vote == LayerVoteType::Max) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700151 const auto ratio = refreshRate.getFps().getValue() /
152 mAppRequestRefreshRates.back()->getFps().getValue();
Ady Abraham62a0be22020-12-08 16:54:10 -0800153 // use ratio^2 to get a lower score the more we get further from peak
154 return ratio * ratio;
155 }
156
157 const auto displayPeriod = refreshRate.getVsyncPeriod();
158 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
159 if (layer.vote == LayerVoteType::ExplicitDefault) {
160 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200161 // that layerPeriod is the minimal period to render a frame.
162 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
163 // then the actualLayerPeriod will be 32ms, because it is the
164 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800165 auto actualLayerPeriod = displayPeriod;
166 int multiplier = 1;
167 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
168 multiplier++;
169 actualLayerPeriod = displayPeriod * multiplier;
170 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200171
172 // Because of the threshold we used above it's possible that score is slightly
173 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800174 return std::min(1.0f,
175 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
176 }
177
178 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
179 layer.vote == LayerVoteType::Heuristic) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200180 if (isFractionalPairOrMultiple(refreshRate.getFps(), layer.desiredRefreshRate)) {
181 return kScoreForFractionalPairs * seamlessness;
182 }
183
Ady Abraham62a0be22020-12-08 16:54:10 -0800184 // Calculate how many display vsyncs we need to present a single frame for this
185 // layer
186 const auto [displayFramesQuotient, displayFramesRemainder] =
187 getDisplayFrames(layerPeriod, displayPeriod);
188 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
189 if (displayFramesRemainder == 0) {
190 // Layer desired refresh rate matches the display rate.
191 return 1.0f * seamlessness;
192 }
193
194 if (displayFramesQuotient == 0) {
195 // Layer desired refresh rate is higher than the display rate.
196 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
197 (1.0f / (MAX_FRAMES_TO_FIT + 1));
198 }
199
200 // Layer desired refresh rate is lower than the display rate. Check how well it fits
201 // the cadence.
202 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
203 int iter = 2;
204 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
205 diff = diff - (displayPeriod - diff);
206 iter++;
207 }
208
209 return (1.0f / iter) * seamlessness;
210 }
211
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800212 if (layer.vote == LayerVoteType::ExplicitExact) {
213 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
214 if (mSupportsFrameRateOverride) {
215 // Since we support frame rate override, allow refresh rates which are
216 // multiples of the layer's request, as those apps would be throttled
217 // down to run at the desired refresh rate.
218 return divider > 0;
219 }
220
221 return divider == 1;
222 }
223
Ady Abraham62a0be22020-12-08 16:54:10 -0800224 return 0;
225}
226
227struct RefreshRateScore {
228 const RefreshRate* refreshRate;
229 float score;
230};
231
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100232RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
233 const GlobalSignals& globalSignals,
234 GlobalSignals* outSignalsConsidered) const {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200235 std::lock_guard lock(mLock);
236
237 if (auto cached = getCachedBestRefreshRate(layers, globalSignals, outSignalsConsidered)) {
238 return *cached;
239 }
240
241 GlobalSignals signalsConsidered;
242 RefreshRate result = getBestRefreshRateLocked(layers, globalSignals, &signalsConsidered);
243 lastBestRefreshRateInvocation.emplace(
244 GetBestRefreshRateInvocation{.layerRequirements = layers,
245 .globalSignals = globalSignals,
246 .outSignalsConsidered = signalsConsidered,
247 .resultingBestRefreshRate = result});
248 if (outSignalsConsidered) {
249 *outSignalsConsidered = signalsConsidered;
250 }
251 return result;
252}
253
254std::optional<RefreshRate> RefreshRateConfigs::getCachedBestRefreshRate(
255 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
256 GlobalSignals* outSignalsConsidered) const {
257 const bool sameAsLastCall = lastBestRefreshRateInvocation &&
258 lastBestRefreshRateInvocation->layerRequirements == layers &&
259 lastBestRefreshRateInvocation->globalSignals == globalSignals;
260
261 if (sameAsLastCall) {
262 if (outSignalsConsidered) {
263 *outSignalsConsidered = lastBestRefreshRateInvocation->outSignalsConsidered;
264 }
265 return lastBestRefreshRateInvocation->resultingBestRefreshRate;
266 }
267
268 return {};
269}
270
271RefreshRate RefreshRateConfigs::getBestRefreshRateLocked(
272 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
273 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800274 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200275 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800276
Ady Abrahamdfd62162020-06-10 16:11:56 -0700277 if (outSignalsConsidered) *outSignalsConsidered = {};
278 const auto setTouchConsidered = [&] {
279 if (outSignalsConsidered) {
280 outSignalsConsidered->touch = true;
281 }
282 };
283
284 const auto setIdleConsidered = [&] {
285 if (outSignalsConsidered) {
286 outSignalsConsidered->idle = true;
287 }
288 };
289
Ady Abraham8a82ba62020-01-17 12:43:17 -0800290 int noVoteLayers = 0;
291 int minVoteLayers = 0;
292 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800293 int explicitDefaultVoteLayers = 0;
294 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800295 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800296 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100297 int seamedFocusedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800298 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800299 switch (layer.vote) {
300 case LayerVoteType::NoVote:
301 noVoteLayers++;
302 break;
303 case LayerVoteType::Min:
304 minVoteLayers++;
305 break;
306 case LayerVoteType::Max:
307 maxVoteLayers++;
308 break;
309 case LayerVoteType::ExplicitDefault:
310 explicitDefaultVoteLayers++;
311 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
312 break;
313 case LayerVoteType::ExplicitExactOrMultiple:
314 explicitExactOrMultipleVoteLayers++;
315 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
316 break;
317 case LayerVoteType::ExplicitExact:
318 explicitExact++;
319 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
320 break;
321 case LayerVoteType::Heuristic:
322 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800323 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200324
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100325 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
326 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200327 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800328 }
329
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800330 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
331 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700332
Steven Thomasf734df42020-04-13 21:09:28 -0700333 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
334 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700335 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700336 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700337 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700338 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800339 }
340
Alec Mouri11232a22020-05-14 18:06:25 -0700341 // If the primary range consists of a single refresh rate then we can only
342 // move out the of range if layers explicitly request a different refresh
343 // rate.
344 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100345 const bool primaryRangeIsSingleRate =
346 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700347
Ady Abrahamdfd62162020-06-10 16:11:56 -0700348 if (!globalSignals.touch && globalSignals.idle &&
349 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700350 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700351 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700352 return getMinRefreshRateByPolicyLocked();
353 }
354
Steven Thomasdebafed2020-05-18 17:30:35 -0700355 if (layers.empty() || noVoteLayers == layers.size()) {
356 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700357 }
358
Ady Abraham8a82ba62020-01-17 12:43:17 -0800359 // Only if all layers want Min we should return Min
360 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700361 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700362 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800363 }
364
Ady Abraham8a82ba62020-01-17 12:43:17 -0800365 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800366 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700367 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800368
Steven Thomasf734df42020-04-13 21:09:28 -0700369 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800370 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800371 }
372
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100373 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
Marin Shalamanov46084422020-10-13 12:33:42 +0200374
Ady Abraham8a82ba62020-01-17 12:43:17 -0800375 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700376 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
377 layerVoteTypeString(layer.vote).c_str(), layer.weight,
378 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800379 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800380 continue;
381 }
382
Ady Abraham71c437d2020-01-31 15:56:57 -0800383 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800384
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800385 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100386 const bool isSeamlessSwitch =
387 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200388
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100389 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100390 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800391 formatLayerInfo(layer, weight).c_str(),
392 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100393 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200394 continue;
395 }
396
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100397 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
398 !layer.focused) {
399 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100400 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800401 formatLayerInfo(layer, weight).c_str(),
402 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100403 mCurrentRefreshRate->toString().c_str());
404 continue;
405 }
406
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100407 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100408 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100409 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100410 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
411 // disappeared.
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100412 const bool isInPolicyForDefault = seamedFocusedLayers > 0
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100413 ? scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup()
414 : scores[i].refreshRate->getModeGroup() == defaultMode->getModeGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100415
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100416 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100417 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800418 scores[i].refreshRate->toString().c_str(),
419 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200420 continue;
421 }
422
Ady Abraham62a0be22020-12-08 16:54:10 -0800423 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
424 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700425 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800426 !(layer.focused &&
427 (layer.vote == LayerVoteType::ExplicitDefault ||
428 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700429 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700430 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700431 continue;
432 }
433
Ady Abraham62a0be22020-12-08 16:54:10 -0800434 const auto layerScore =
435 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200436 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800437 scores[i].refreshRate->getName().c_str(), layerScore);
438 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800439 }
440 }
441
Ady Abraham34702102020-02-10 14:12:05 -0800442 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
443 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
444 // or the lower otherwise.
445 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
446 ? getBestRefreshRate(scores.rbegin(), scores.rend())
447 : getBestRefreshRate(scores.begin(), scores.end());
448
Alec Mouri11232a22020-05-14 18:06:25 -0700449 if (primaryRangeIsSingleRate) {
450 // If we never scored any layers, then choose the rate from the primary
451 // range instead of picking a random score from the app range.
452 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800453 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700454 ALOGV("layers not scored - choose %s",
455 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700456 return getMaxRefreshRateByPolicyLocked();
457 } else {
458 return *bestRefreshRate;
459 }
460 }
461
Steven Thomasf734df42020-04-13 21:09:28 -0700462 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
463 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
464 // vote we should not change it if we get a touch event. Only apply touch boost if it will
465 // actually increase the refresh rate over the normal selection.
466 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700467
Ady Abraham5e4e9832021-06-14 13:40:56 -0700468 const bool touchBoostForExplicitExact = [&] {
469 if (mSupportsFrameRateOverride) {
470 // Enable touch boost if there are other layers besides exact
471 return explicitExact + noVoteLayers != layers.size();
472 } else {
473 // Enable touch boost if there are no exact layers
474 return explicitExact == 0;
475 }
476 }();
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800477 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Ady Abraham6b7ad652021-06-23 17:34:57 -0700478 bestRefreshRate->getFps().lessThanWithMargin(touchRefreshRate.getFps())) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700479 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700480 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700481 return touchRefreshRate;
482 }
483
Ady Abrahamde7156e2020-02-28 17:29:39 -0800484 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800485}
486
Ady Abraham62a0be22020-12-08 16:54:10 -0800487std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
488groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
489 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
490 for (const auto& layer : layers) {
491 auto iter = layersByUid.emplace(layer.ownerUid,
492 std::vector<const RefreshRateConfigs::LayerRequirement*>());
493 auto& layersWithSameUid = iter.first->second;
494 layersWithSameUid.push_back(&layer);
495 }
496
497 // Remove uids that can't have a frame rate override
498 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
499 const auto& layersWithSameUid = iter->second;
500 bool skipUid = false;
501 for (const auto& layer : layersWithSameUid) {
502 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
503 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
504 skipUid = true;
505 break;
506 }
507 }
508 if (skipUid) {
509 iter = layersByUid.erase(iter);
510 } else {
511 ++iter;
512 }
513 }
514
515 return layersByUid;
516}
517
518std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
519 const AllRefreshRatesMapType& refreshRates) {
520 std::vector<RefreshRateScore> scores;
521 scores.reserve(refreshRates.size());
522 for (const auto& [ignored, refreshRate] : refreshRates) {
523 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
524 }
525 std::sort(scores.begin(), scores.end(),
526 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
527 return scores;
528}
529
530RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800531 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800532 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800533 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800534
Ady Abraham64c2fc02020-12-29 12:07:50 -0800535 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800536 std::lock_guard lock(mLock);
537 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
538 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
539 groupLayersByUid(layers);
540 UidToFrameRateOverride frameRateOverrides;
541 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800542 // Layers with ExplicitExactOrMultiple expect touch boost
543 const bool hasExplicitExactOrMultiple =
544 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
545 [](const auto& layer) {
546 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
547 });
548
549 if (touch && hasExplicitExactOrMultiple) {
550 continue;
551 }
552
Ady Abraham62a0be22020-12-08 16:54:10 -0800553 for (auto& score : scores) {
554 score.score = 0;
555 }
556
557 for (const auto& layer : layersWithSameUid) {
558 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
559 continue;
560 }
561
562 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800563 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
564 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800565 for (RefreshRateScore& score : scores) {
566 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
567 /*isSeamlessSwitch*/ true);
568 score.score += layer->weight * layerScore;
569 }
570 }
571
572 // We just care about the refresh rates which are a divider of the
573 // display refresh rate
574 auto iter =
575 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
576 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
577 });
578 scores.erase(iter, scores.end());
579
580 // If we never scored any layers, we don't have a preferred frame rate
581 if (std::all_of(scores.begin(), scores.end(),
582 [](const RefreshRateScore& score) { return score.score == 0; })) {
583 continue;
584 }
585
586 // Now that we scored all the refresh rates we need to pick the one that got the highest
587 // score.
588 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700589 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800590 }
591
592 return frameRateOverrides;
593}
594
Ady Abraham34702102020-02-10 14:12:05 -0800595template <typename Iter>
596const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200597 constexpr auto kEpsilon = 0.0001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800598 const RefreshRate* bestRefreshRate = begin->refreshRate;
599 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800600 for (auto i = begin; i != end; ++i) {
601 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100602 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800603
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100604 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800605
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200606 if (score > max * (1 + kEpsilon)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800607 max = score;
608 bestRefreshRate = refreshRate;
609 }
610 }
611
Ady Abraham34702102020-02-10 14:12:05 -0800612 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800613}
614
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100615std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100616 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800617 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100618
619 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
620 : *mCurrentRefreshRate;
621 const auto& min = *mMinSupportedRefreshRate;
622
623 if (current != min) {
624 const auto& refreshRate = timerExpired ? min : current;
625 return refreshRate.getFps();
626 }
627
628 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700629}
630
631const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200632 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100633 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200634 return *refreshRate;
635 }
636 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100637 ALOGE("Can't find min refresh rate by policy with the same mode group"
638 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200639 mCurrentRefreshRate->toString().c_str());
640 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700641 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800642}
643
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100644RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800645 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700646 return getMaxRefreshRateByPolicyLocked();
647}
648
649const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200650 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
651 const auto& refreshRate = (**it);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100652 if (mCurrentRefreshRate->getModeGroup() == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200653 return refreshRate;
654 }
655 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100656 ALOGE("Can't find max refresh rate by policy with the same mode group"
657 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200658 mCurrentRefreshRate->toString().c_str());
659 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700660 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800661}
662
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100663RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800664 std::lock_guard lock(mLock);
665 return *mCurrentRefreshRate;
666}
667
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100668RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800669 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800670 return getCurrentRefreshRateByPolicyLocked();
671}
672
673const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700674 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
675 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800676 return *mCurrentRefreshRate;
677 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100678 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800679}
680
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100681void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800682 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200683
684 // Invalidate the cached invocation to getBestRefreshRate. This forces
685 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
686 lastBestRefreshRateInvocation.reset();
687
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100688 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800689}
690
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100691RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
rnlee3bd610662021-06-23 16:27:57 -0700692 Config config)
693 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100694 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100695}
696
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100697void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
698 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100699 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200700
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100701 // The current mode should be supported
702 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
703 return mode->getId() == currentModeId;
704 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700705
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200706 // Invalidate the cached invocation to getBestRefreshRate. This forces
707 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
708 lastBestRefreshRateInvocation.reset();
709
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100710 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100711 for (const auto& mode : modes) {
712 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100713 mRefreshRates.emplace(modeId,
Ady Abraham6b7ad652021-06-23 17:34:57 -0700714 std::make_unique<RefreshRate>(mode, RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100715 if (modeId == currentModeId) {
716 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700717 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800718 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700719
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100720 std::vector<const RefreshRate*> sortedModes;
721 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100722 // Reset the policy because the old one may no longer be valid.
723 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100724 mDisplayManagerPolicy.defaultMode = currentModeId;
725 mMinSupportedRefreshRate = sortedModes.front();
726 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800727
728 mSupportsFrameRateOverride = false;
rnlee3bd610662021-06-23 16:27:57 -0700729 if (mConfig.enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100730 for (const auto& mode1 : sortedModes) {
731 for (const auto& mode2 : sortedModes) {
732 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800733 mSupportsFrameRateOverride = true;
734 break;
735 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800736 }
737 }
738 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800739
Ady Abrahamabc27602020-04-08 17:20:29 -0700740 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800741}
742
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100743bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100744 // defaultMode must be a valid mode, and within the given refresh rate range.
745 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700746 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100747 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700748 return false;
749 }
750 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700751 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100752 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700753 return false;
754 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100755 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
756 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700757}
758
759status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800760 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100761 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100762 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100763 return BAD_VALUE;
764 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200765 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700766 Policy previousPolicy = *getCurrentPolicyLocked();
767 mDisplayManagerPolicy = policy;
768 if (*getCurrentPolicyLocked() == previousPolicy) {
769 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100770 }
Ady Abraham2139f732019-11-13 18:56:40 -0800771 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100772 return NO_ERROR;
773}
774
Steven Thomasd4071902020-03-24 16:02:53 -0700775status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100776 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100777 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700778 return BAD_VALUE;
779 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200780 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700781 Policy previousPolicy = *getCurrentPolicyLocked();
782 mOverridePolicy = policy;
783 if (*getCurrentPolicyLocked() == previousPolicy) {
784 return CURRENT_POLICY_UNCHANGED;
785 }
786 constructAvailableRefreshRates();
787 return NO_ERROR;
788}
789
790const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
791 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
792}
793
794RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
795 std::lock_guard lock(mLock);
796 return *getCurrentPolicyLocked();
797}
798
799RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
800 std::lock_guard lock(mLock);
801 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100802}
803
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100804bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100805 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700806 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700807 if (refreshRate->getModeId() == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100808 return true;
809 }
810 }
811 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800812}
813
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100814void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800815 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
816 std::vector<const RefreshRate*>* outRefreshRates) {
817 outRefreshRates->clear();
818 outRefreshRates->reserve(mRefreshRates.size());
819 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800820 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100821 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Ady Abraham6b7ad652021-06-23 17:34:57 -0700822 refreshRate->getModeId().value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800823 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800824 }
825 }
826
827 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
828 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100829 if (refreshRate1->mode->getVsyncPeriod() !=
830 refreshRate2->mode->getVsyncPeriod()) {
831 return refreshRate1->mode->getVsyncPeriod() >
832 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700833 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100834 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700835 }
Ady Abraham2139f732019-11-13 18:56:40 -0800836 });
837}
838
839void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100840 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700841 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100842 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100843 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700844
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100845 auto filterRefreshRates =
846 [&](Fps min, Fps max, const char* listName,
847 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
848 getSortedRefreshRateListLocked(
849 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
850 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800851
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100852 return mode->getHeight() == defaultMode->getHeight() &&
853 mode->getWidth() == defaultMode->getWidth() &&
854 mode->getDpiX() == defaultMode->getDpiX() &&
855 mode->getDpiY() == defaultMode->getDpiY() &&
856 (policy->allowGroupSwitching ||
857 mode->getGroup() == defaultMode->getGroup()) &&
858 refreshRate.inPolicy(min, max);
859 },
860 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800861
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100862 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
863 "No matching modes for %s range: min=%s max=%s", listName,
864 to_string(min).c_str(), to_string(max).c_str());
865 auto stringifyRefreshRates = [&]() -> std::string {
866 std::string str;
867 for (auto refreshRate : *outRefreshRates) {
868 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
869 }
870 return str;
871 };
872 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
873 };
Steven Thomasf734df42020-04-13 21:09:28 -0700874
875 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
876 &mPrimaryRefreshRates);
877 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
878 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800879}
880
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100881Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
882 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700883 return *mKnownFrameRates.begin();
884 }
885
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100886 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700887 return *std::prev(mKnownFrameRates.end());
888 }
889
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100890 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
891 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700892
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100893 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
894 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700895 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
896}
897
Ana Krulecb9afd792020-06-11 13:16:15 -0700898RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
899 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100900 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700901 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
902 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
TreeHugger Robot758ab612021-06-22 19:17:29 +0000903 const auto& currentPolicy = getCurrentPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700904
905 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
906 // the min allowed refresh rate is higher than the device min, we do not want to enable the
907 // timer.
908 if (deviceMin < minByPolicy) {
909 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
910 }
911 if (minByPolicy == maxByPolicy) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000912 // when min primary range in display manager policy is below device min turn on the timer.
913 if (currentPolicy->primaryRange.min.lessThanWithMargin(deviceMin.getFps())) {
914 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700915 }
916 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
917 }
918 // Turn on the timer in all other cases.
919 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
920}
921
Ady Abraham62a0be22020-12-08 16:54:10 -0800922int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700923 // This calculation needs to be in sync with the java code
924 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200925
926 // The threshold must be smaller than 0.001 in order to differentiate
927 // between the fractional pairs (e.g. 59.94 and 60).
928 constexpr float kThreshold = 0.0009f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800929 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700930 const auto numPeriodsRounded = std::round(numPeriods);
931 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800932 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700933 }
934
Ady Abraham62f216c2020-10-13 19:07:23 -0700935 return static_cast<int>(numPeriodsRounded);
936}
937
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200938bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
939 if (smaller.getValue() > bigger.getValue()) {
940 return isFractionalPairOrMultiple(bigger, smaller);
941 }
942
943 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
944 constexpr float kCoef = 1000.f / 1001.f;
945 return bigger.equalsWithMargin(Fps(smaller.getValue() * multiplier / kCoef)) ||
946 bigger.equalsWithMargin(Fps(smaller.getValue() * multiplier * kCoef));
947}
948
Marin Shalamanovba421a82020-11-10 21:49:26 +0100949void RefreshRateConfigs::dump(std::string& result) const {
950 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100951 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100952 mDisplayManagerPolicy.toString().c_str());
953 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
954 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100955 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100956 currentPolicy.toString().c_str());
957 }
958
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100959 auto mode = mCurrentRefreshRate->mode;
960 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100961
962 result.append("Refresh rates:\n");
963 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100964 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +0100965 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
966 }
967
Ady Abraham64c2fc02020-12-29 12:07:50 -0800968 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
969 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100970 result.append("\n");
971}
972
Ady Abraham2139f732019-11-13 18:56:40 -0800973} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100974
975// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800976#pragma clang diagnostic pop // ignored "-Wextra"