blob: 74ffc8fb9cbe9e27eaf8e981b46170f509a2164f [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 Abraham9a2ea342021-09-03 17:32:34 -070025#include <android-base/properties.h>
Ady Abraham8a82ba62020-01-17 12:43:17 -080026#include <android-base/stringprintf.h>
27#include <utils/Trace.h>
28#include <chrono>
29#include <cmath>
Ady Abraham4899ff82021-01-06 13:53:29 -080030#include "../SurfaceFlingerProperties.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080031
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080032#undef LOG_TAG
33#define LOG_TAG "RefreshRateConfigs"
34
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080035namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010036namespace {
37std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010038 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010039 RefreshRateConfigs::layerVoteTypeString(layer.vote).c_str(), weight,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010040 toString(layer.seamlessness).c_str(),
41 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010042}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010043
Marin Shalamanova7fe3042021-01-29 21:02:08 +010044std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010045 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 +010046 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010047
48 // Add all supported refresh rates to the set
Marin Shalamanova7fe3042021-01-29 21:02:08 +010049 for (const auto& mode : modes) {
50 const auto refreshRate = Fps::fromPeriodNsecs(mode->getVsyncPeriod());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010051 knownFrameRates.emplace_back(refreshRate);
52 }
53
54 // Sort and remove duplicates
55 std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
56 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
57 Fps::EqualsWithMargin()),
58 knownFrameRates.end());
59 return knownFrameRates;
60}
61
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010062} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080063
64using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080065using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080066
Marin Shalamanov46084422020-10-13 12:33:42 +020067std::string RefreshRate::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010068 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010069 getModeId().value(), mode->getHwcId(), getFps().getValue(),
70 mode->getWidth(), mode->getHeight(), getModeGroup());
Marin Shalamanov46084422020-10-13 12:33:42 +020071}
72
Ady Abrahama6b676e2020-05-27 14:29:09 -070073std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
74 switch (vote) {
75 case LayerVoteType::NoVote:
76 return "NoVote";
77 case LayerVoteType::Min:
78 return "Min";
79 case LayerVoteType::Max:
80 return "Max";
81 case LayerVoteType::Heuristic:
82 return "Heuristic";
83 case LayerVoteType::ExplicitDefault:
84 return "ExplicitDefault";
85 case LayerVoteType::ExplicitExactOrMultiple:
86 return "ExplicitExactOrMultiple";
Ady Abrahamdd5bfa92021-01-07 17:56:08 -080087 case LayerVoteType::ExplicitExact:
88 return "ExplicitExact";
Ady Abrahama6b676e2020-05-27 14:29:09 -070089 }
90}
91
Marin Shalamanovb6674e72020-11-06 13:05:57 +010092std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010093 return base::StringPrintf("default mode ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010094 ", primary range: %s, app request range: %s",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010095 defaultMode.value(), allowGroupSwitching,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010096 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020097}
98
Ady Abraham4ccdcb42020-02-11 17:34:34 -080099std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
100 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800101 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
102 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
103 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
104 quotient++;
105 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800106 }
107
Ady Abraham62a0be22020-12-08 16:54:10 -0800108 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800109}
110
rnlee3bd610662021-06-23 16:27:57 -0700111bool RefreshRateConfigs::isVoteAllowed(const LayerRequirement& layer,
112 const RefreshRate& refreshRate) const {
113 switch (layer.vote) {
114 case LayerVoteType::ExplicitExactOrMultiple:
115 case LayerVoteType::Heuristic:
116 if (mConfig.frameRateMultipleThreshold != 0 &&
Ady Abraham6b7ad652021-06-23 17:34:57 -0700117 refreshRate.getFps().greaterThanOrEqualWithMargin(
rnlee3bd610662021-06-23 16:27:57 -0700118 Fps(mConfig.frameRateMultipleThreshold)) &&
119 layer.desiredRefreshRate.lessThanWithMargin(
120 Fps(mConfig.frameRateMultipleThreshold / 2))) {
121 // Don't vote high refresh rates past the threshold for layers with a low desired
122 // refresh rate. For example, desired 24 fps with 120 Hz threshold means no vote for
123 // 120 Hz, but desired 60 fps should have a vote.
124 return false;
125 }
126 break;
127 case LayerVoteType::ExplicitDefault:
128 case LayerVoteType::ExplicitExact:
129 case LayerVoteType::Max:
130 case LayerVoteType::Min:
131 case LayerVoteType::NoVote:
132 break;
133 }
134 return true;
135}
136
Ady Abraham62a0be22020-12-08 16:54:10 -0800137float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
138 const RefreshRate& refreshRate,
139 bool isSeamlessSwitch) const {
rnlee3bd610662021-06-23 16:27:57 -0700140 if (!isVoteAllowed(layer, refreshRate)) {
141 return 0;
142 }
143
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200144 constexpr float kScoreForFractionalPairs = .8f;
145
Ady Abraham62a0be22020-12-08 16:54:10 -0800146 // Slightly prefer seamless switches.
147 constexpr float kSeamedSwitchPenalty = 0.95f;
148 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
149
150 // If the layer wants Max, give higher score to the higher refresh rate
151 if (layer.vote == LayerVoteType::Max) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700152 const auto ratio = refreshRate.getFps().getValue() /
153 mAppRequestRefreshRates.back()->getFps().getValue();
Ady Abraham62a0be22020-12-08 16:54:10 -0800154 // use ratio^2 to get a lower score the more we get further from peak
155 return ratio * ratio;
156 }
157
158 const auto displayPeriod = refreshRate.getVsyncPeriod();
159 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
160 if (layer.vote == LayerVoteType::ExplicitDefault) {
161 // Find the actual rate the layer will render, assuming
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200162 // that layerPeriod is the minimal period to render a frame.
163 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
164 // then the actualLayerPeriod will be 32ms, because it is the
165 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800166 auto actualLayerPeriod = displayPeriod;
167 int multiplier = 1;
168 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
169 multiplier++;
170 actualLayerPeriod = displayPeriod * multiplier;
171 }
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200172
173 // Because of the threshold we used above it's possible that score is slightly
174 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800175 return std::min(1.0f,
176 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
177 }
178
179 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
180 layer.vote == LayerVoteType::Heuristic) {
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200181 if (isFractionalPairOrMultiple(refreshRate.getFps(), layer.desiredRefreshRate)) {
182 return kScoreForFractionalPairs * seamlessness;
183 }
184
Ady Abraham62a0be22020-12-08 16:54:10 -0800185 // Calculate how many display vsyncs we need to present a single frame for this
186 // layer
187 const auto [displayFramesQuotient, displayFramesRemainder] =
188 getDisplayFrames(layerPeriod, displayPeriod);
189 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
190 if (displayFramesRemainder == 0) {
191 // Layer desired refresh rate matches the display rate.
192 return 1.0f * seamlessness;
193 }
194
195 if (displayFramesQuotient == 0) {
196 // Layer desired refresh rate is higher than the display rate.
197 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
198 (1.0f / (MAX_FRAMES_TO_FIT + 1));
199 }
200
201 // Layer desired refresh rate is lower than the display rate. Check how well it fits
202 // the cadence.
203 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
204 int iter = 2;
205 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
206 diff = diff - (displayPeriod - diff);
207 iter++;
208 }
209
210 return (1.0f / iter) * seamlessness;
211 }
212
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800213 if (layer.vote == LayerVoteType::ExplicitExact) {
214 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
215 if (mSupportsFrameRateOverride) {
216 // Since we support frame rate override, allow refresh rates which are
217 // multiples of the layer's request, as those apps would be throttled
218 // down to run at the desired refresh rate.
219 return divider > 0;
220 }
221
222 return divider == 1;
223 }
224
Ady Abraham62a0be22020-12-08 16:54:10 -0800225 return 0;
226}
227
228struct RefreshRateScore {
229 const RefreshRate* refreshRate;
230 float score;
231};
232
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100233RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
234 const GlobalSignals& globalSignals,
235 GlobalSignals* outSignalsConsidered) const {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200236 std::lock_guard lock(mLock);
237
238 if (auto cached = getCachedBestRefreshRate(layers, globalSignals, outSignalsConsidered)) {
239 return *cached;
240 }
241
242 GlobalSignals signalsConsidered;
243 RefreshRate result = getBestRefreshRateLocked(layers, globalSignals, &signalsConsidered);
244 lastBestRefreshRateInvocation.emplace(
245 GetBestRefreshRateInvocation{.layerRequirements = layers,
246 .globalSignals = globalSignals,
247 .outSignalsConsidered = signalsConsidered,
248 .resultingBestRefreshRate = result});
249 if (outSignalsConsidered) {
250 *outSignalsConsidered = signalsConsidered;
251 }
252 return result;
253}
254
255std::optional<RefreshRate> RefreshRateConfigs::getCachedBestRefreshRate(
256 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
257 GlobalSignals* outSignalsConsidered) const {
258 const bool sameAsLastCall = lastBestRefreshRateInvocation &&
259 lastBestRefreshRateInvocation->layerRequirements == layers &&
260 lastBestRefreshRateInvocation->globalSignals == globalSignals;
261
262 if (sameAsLastCall) {
263 if (outSignalsConsidered) {
264 *outSignalsConsidered = lastBestRefreshRateInvocation->outSignalsConsidered;
265 }
266 return lastBestRefreshRateInvocation->resultingBestRefreshRate;
267 }
268
269 return {};
270}
271
272RefreshRate RefreshRateConfigs::getBestRefreshRateLocked(
273 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
274 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800275 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200276 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800277
Ady Abrahamdfd62162020-06-10 16:11:56 -0700278 if (outSignalsConsidered) *outSignalsConsidered = {};
279 const auto setTouchConsidered = [&] {
280 if (outSignalsConsidered) {
281 outSignalsConsidered->touch = true;
282 }
283 };
284
285 const auto setIdleConsidered = [&] {
286 if (outSignalsConsidered) {
287 outSignalsConsidered->idle = true;
288 }
289 };
290
Ady Abraham8a82ba62020-01-17 12:43:17 -0800291 int noVoteLayers = 0;
292 int minVoteLayers = 0;
293 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800294 int explicitDefaultVoteLayers = 0;
295 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800296 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800297 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100298 int seamedFocusedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800299 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800300 switch (layer.vote) {
301 case LayerVoteType::NoVote:
302 noVoteLayers++;
303 break;
304 case LayerVoteType::Min:
305 minVoteLayers++;
306 break;
307 case LayerVoteType::Max:
308 maxVoteLayers++;
309 break;
310 case LayerVoteType::ExplicitDefault:
311 explicitDefaultVoteLayers++;
312 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
313 break;
314 case LayerVoteType::ExplicitExactOrMultiple:
315 explicitExactOrMultipleVoteLayers++;
316 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
317 break;
318 case LayerVoteType::ExplicitExact:
319 explicitExact++;
320 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
321 break;
322 case LayerVoteType::Heuristic:
323 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800324 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200325
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100326 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
327 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200328 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800329 }
330
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800331 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
332 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700333
Steven Thomasf734df42020-04-13 21:09:28 -0700334 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
335 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700336 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700337 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700338 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700339 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800340 }
341
Alec Mouri11232a22020-05-14 18:06:25 -0700342 // If the primary range consists of a single refresh rate then we can only
343 // move out the of range if layers explicitly request a different refresh
344 // rate.
345 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100346 const bool primaryRangeIsSingleRate =
347 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700348
Ady Abrahamdfd62162020-06-10 16:11:56 -0700349 if (!globalSignals.touch && globalSignals.idle &&
350 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700351 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700352 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700353 return getMinRefreshRateByPolicyLocked();
354 }
355
Steven Thomasdebafed2020-05-18 17:30:35 -0700356 if (layers.empty() || noVoteLayers == layers.size()) {
357 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700358 }
359
Ady Abraham8a82ba62020-01-17 12:43:17 -0800360 // Only if all layers want Min we should return Min
361 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700362 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700363 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800364 }
365
Ady Abraham8a82ba62020-01-17 12:43:17 -0800366 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800367 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700368 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800369
Steven Thomasf734df42020-04-13 21:09:28 -0700370 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800371 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800372 }
373
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100374 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
Marin Shalamanov46084422020-10-13 12:33:42 +0200375
Ady Abraham8a82ba62020-01-17 12:43:17 -0800376 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700377 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
378 layerVoteTypeString(layer.vote).c_str(), layer.weight,
379 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800380 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800381 continue;
382 }
383
Ady Abraham71c437d2020-01-31 15:56:57 -0800384 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800385
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800386 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100387 const bool isSeamlessSwitch =
388 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200389
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100390 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100391 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800392 formatLayerInfo(layer, weight).c_str(),
393 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100394 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200395 continue;
396 }
397
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100398 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
399 !layer.focused) {
400 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100401 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800402 formatLayerInfo(layer, weight).c_str(),
403 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100404 mCurrentRefreshRate->toString().c_str());
405 continue;
406 }
407
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100408 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100409 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100410 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100411 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
412 // disappeared.
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100413 const bool isInPolicyForDefault = seamedFocusedLayers > 0
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100414 ? scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup()
415 : scores[i].refreshRate->getModeGroup() == defaultMode->getModeGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100416
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100417 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100418 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800419 scores[i].refreshRate->toString().c_str(),
420 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200421 continue;
422 }
423
Ady Abraham62a0be22020-12-08 16:54:10 -0800424 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
425 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700426 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800427 !(layer.focused &&
428 (layer.vote == LayerVoteType::ExplicitDefault ||
429 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700430 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700431 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700432 continue;
433 }
434
Ady Abraham62a0be22020-12-08 16:54:10 -0800435 const auto layerScore =
436 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200437 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800438 scores[i].refreshRate->getName().c_str(), layerScore);
439 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800440 }
441 }
442
Ady Abraham34702102020-02-10 14:12:05 -0800443 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
444 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
445 // or the lower otherwise.
446 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
447 ? getBestRefreshRate(scores.rbegin(), scores.rend())
448 : getBestRefreshRate(scores.begin(), scores.end());
449
Alec Mouri11232a22020-05-14 18:06:25 -0700450 if (primaryRangeIsSingleRate) {
451 // If we never scored any layers, then choose the rate from the primary
452 // range instead of picking a random score from the app range.
453 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800454 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700455 ALOGV("layers not scored - choose %s",
456 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700457 return getMaxRefreshRateByPolicyLocked();
458 } else {
459 return *bestRefreshRate;
460 }
461 }
462
Steven Thomasf734df42020-04-13 21:09:28 -0700463 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
464 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
465 // vote we should not change it if we get a touch event. Only apply touch boost if it will
466 // actually increase the refresh rate over the normal selection.
467 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700468
Ady Abraham5e4e9832021-06-14 13:40:56 -0700469 const bool touchBoostForExplicitExact = [&] {
470 if (mSupportsFrameRateOverride) {
471 // Enable touch boost if there are other layers besides exact
472 return explicitExact + noVoteLayers != layers.size();
473 } else {
474 // Enable touch boost if there are no exact layers
475 return explicitExact == 0;
476 }
477 }();
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800478 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Ady Abraham6b7ad652021-06-23 17:34:57 -0700479 bestRefreshRate->getFps().lessThanWithMargin(touchRefreshRate.getFps())) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700480 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700481 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700482 return touchRefreshRate;
483 }
484
Ady Abrahamde7156e2020-02-28 17:29:39 -0800485 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800486}
487
Ady Abraham62a0be22020-12-08 16:54:10 -0800488std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
489groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
490 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
491 for (const auto& layer : layers) {
492 auto iter = layersByUid.emplace(layer.ownerUid,
493 std::vector<const RefreshRateConfigs::LayerRequirement*>());
494 auto& layersWithSameUid = iter.first->second;
495 layersWithSameUid.push_back(&layer);
496 }
497
498 // Remove uids that can't have a frame rate override
499 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
500 const auto& layersWithSameUid = iter->second;
501 bool skipUid = false;
502 for (const auto& layer : layersWithSameUid) {
503 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
504 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
505 skipUid = true;
506 break;
507 }
508 }
509 if (skipUid) {
510 iter = layersByUid.erase(iter);
511 } else {
512 ++iter;
513 }
514 }
515
516 return layersByUid;
517}
518
519std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
520 const AllRefreshRatesMapType& refreshRates) {
521 std::vector<RefreshRateScore> scores;
522 scores.reserve(refreshRates.size());
523 for (const auto& [ignored, refreshRate] : refreshRates) {
524 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
525 }
526 std::sort(scores.begin(), scores.end(),
527 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
528 return scores;
529}
530
531RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800532 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800533 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800534 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800535
Ady Abraham64c2fc02020-12-29 12:07:50 -0800536 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800537 std::lock_guard lock(mLock);
538 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
539 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
540 groupLayersByUid(layers);
541 UidToFrameRateOverride frameRateOverrides;
542 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800543 // Layers with ExplicitExactOrMultiple expect touch boost
544 const bool hasExplicitExactOrMultiple =
545 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
546 [](const auto& layer) {
547 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
548 });
549
550 if (touch && hasExplicitExactOrMultiple) {
551 continue;
552 }
553
Ady Abraham62a0be22020-12-08 16:54:10 -0800554 for (auto& score : scores) {
555 score.score = 0;
556 }
557
558 for (const auto& layer : layersWithSameUid) {
559 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
560 continue;
561 }
562
563 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800564 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
565 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800566 for (RefreshRateScore& score : scores) {
567 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
568 /*isSeamlessSwitch*/ true);
569 score.score += layer->weight * layerScore;
570 }
571 }
572
573 // We just care about the refresh rates which are a divider of the
574 // display refresh rate
575 auto iter =
576 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
577 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
578 });
579 scores.erase(iter, scores.end());
580
581 // If we never scored any layers, we don't have a preferred frame rate
582 if (std::all_of(scores.begin(), scores.end(),
583 [](const RefreshRateScore& score) { return score.score == 0; })) {
584 continue;
585 }
586
587 // Now that we scored all the refresh rates we need to pick the one that got the highest
588 // score.
589 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700590 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800591 }
592
593 return frameRateOverrides;
594}
595
Ady Abraham34702102020-02-10 14:12:05 -0800596template <typename Iter>
597const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200598 constexpr auto kEpsilon = 0.0001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800599 const RefreshRate* bestRefreshRate = begin->refreshRate;
600 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800601 for (auto i = begin; i != end; ++i) {
602 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100603 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800604
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100605 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800606
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200607 if (score > max * (1 + kEpsilon)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800608 max = score;
609 bestRefreshRate = refreshRate;
610 }
611 }
612
Ady Abraham34702102020-02-10 14:12:05 -0800613 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800614}
615
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100616std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100617 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800618 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100619
620 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
621 : *mCurrentRefreshRate;
622 const auto& min = *mMinSupportedRefreshRate;
623
624 if (current != min) {
625 const auto& refreshRate = timerExpired ? min : current;
626 return refreshRate.getFps();
627 }
628
629 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700630}
631
632const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200633 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100634 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200635 return *refreshRate;
636 }
637 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100638 ALOGE("Can't find min refresh rate by policy with the same mode group"
639 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200640 mCurrentRefreshRate->toString().c_str());
641 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700642 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800643}
644
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100645RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800646 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700647 return getMaxRefreshRateByPolicyLocked();
648}
649
650const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200651 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
652 const auto& refreshRate = (**it);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100653 if (mCurrentRefreshRate->getModeGroup() == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200654 return refreshRate;
655 }
656 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100657 ALOGE("Can't find max refresh rate by policy with the same mode group"
658 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200659 mCurrentRefreshRate->toString().c_str());
660 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700661 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800662}
663
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100664RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800665 std::lock_guard lock(mLock);
666 return *mCurrentRefreshRate;
667}
668
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100669RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800670 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800671 return getCurrentRefreshRateByPolicyLocked();
672}
673
674const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700675 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
676 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800677 return *mCurrentRefreshRate;
678 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100679 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800680}
681
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100682void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800683 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200684
685 // Invalidate the cached invocation to getBestRefreshRate. This forces
686 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
687 lastBestRefreshRateInvocation.reset();
688
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100689 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800690}
691
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100692RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
rnlee3bd610662021-06-23 16:27:57 -0700693 Config config)
694 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700695 initializeIdleTimer();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100696 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100697}
698
Ady Abraham9a2ea342021-09-03 17:32:34 -0700699void RefreshRateConfigs::initializeIdleTimer() {
Ady Abraham6d885932021-09-03 18:05:48 -0700700 if (mConfig.idleTimerTimeoutMs > 0) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700701 const auto getCallback = [this]() -> std::optional<IdleTimerCallbacks::Callbacks> {
702 std::scoped_lock lock(mIdleTimerCallbacksMutex);
703 if (!mIdleTimerCallbacks.has_value()) return {};
Ady Abraham6d885932021-09-03 18:05:48 -0700704 return mConfig.supportKernelIdleTimer ? mIdleTimerCallbacks->kernel
705 : mIdleTimerCallbacks->platform;
Ady Abraham9a2ea342021-09-03 17:32:34 -0700706 };
707
708 mIdleTimer.emplace(
Ady Abraham6d885932021-09-03 18:05:48 -0700709 "IdleTimer", std::chrono::milliseconds(mConfig.idleTimerTimeoutMs),
Ady Abraham9a2ea342021-09-03 17:32:34 -0700710 [getCallback] {
711 if (const auto callback = getCallback()) callback->onReset();
712 },
713 [getCallback] {
714 if (const auto callback = getCallback()) callback->onExpired();
715 });
Ady Abraham9a2ea342021-09-03 17:32:34 -0700716 }
717}
718
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100719void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
720 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100721 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200722
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100723 // The current mode should be supported
724 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
725 return mode->getId() == currentModeId;
726 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700727
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200728 // Invalidate the cached invocation to getBestRefreshRate. This forces
729 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
730 lastBestRefreshRateInvocation.reset();
731
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100732 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100733 for (const auto& mode : modes) {
734 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100735 mRefreshRates.emplace(modeId,
Ady Abraham6b7ad652021-06-23 17:34:57 -0700736 std::make_unique<RefreshRate>(mode, RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100737 if (modeId == currentModeId) {
738 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700739 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800740 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700741
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100742 std::vector<const RefreshRate*> sortedModes;
743 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100744 // Reset the policy because the old one may no longer be valid.
745 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100746 mDisplayManagerPolicy.defaultMode = currentModeId;
747 mMinSupportedRefreshRate = sortedModes.front();
748 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800749
750 mSupportsFrameRateOverride = false;
rnlee3bd610662021-06-23 16:27:57 -0700751 if (mConfig.enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100752 for (const auto& mode1 : sortedModes) {
753 for (const auto& mode2 : sortedModes) {
754 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800755 mSupportsFrameRateOverride = true;
756 break;
757 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800758 }
759 }
760 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800761
Ady Abrahamabc27602020-04-08 17:20:29 -0700762 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800763}
764
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100765bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100766 // defaultMode must be a valid mode, and within the given refresh rate range.
767 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700768 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100769 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700770 return false;
771 }
772 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700773 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100774 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700775 return false;
776 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100777 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
778 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700779}
780
781status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800782 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100783 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100784 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100785 return BAD_VALUE;
786 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200787 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700788 Policy previousPolicy = *getCurrentPolicyLocked();
789 mDisplayManagerPolicy = policy;
790 if (*getCurrentPolicyLocked() == previousPolicy) {
791 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100792 }
Ady Abraham2139f732019-11-13 18:56:40 -0800793 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100794 return NO_ERROR;
795}
796
Steven Thomasd4071902020-03-24 16:02:53 -0700797status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100798 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100799 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700800 return BAD_VALUE;
801 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200802 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700803 Policy previousPolicy = *getCurrentPolicyLocked();
804 mOverridePolicy = policy;
805 if (*getCurrentPolicyLocked() == previousPolicy) {
806 return CURRENT_POLICY_UNCHANGED;
807 }
808 constructAvailableRefreshRates();
809 return NO_ERROR;
810}
811
812const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
813 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
814}
815
816RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
817 std::lock_guard lock(mLock);
818 return *getCurrentPolicyLocked();
819}
820
821RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
822 std::lock_guard lock(mLock);
823 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100824}
825
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100826bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100827 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700828 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700829 if (refreshRate->getModeId() == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100830 return true;
831 }
832 }
833 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800834}
835
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100836void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800837 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
838 std::vector<const RefreshRate*>* outRefreshRates) {
839 outRefreshRates->clear();
840 outRefreshRates->reserve(mRefreshRates.size());
841 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800842 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100843 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Ady Abraham6b7ad652021-06-23 17:34:57 -0700844 refreshRate->getModeId().value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800845 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800846 }
847 }
848
849 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
850 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100851 if (refreshRate1->mode->getVsyncPeriod() !=
852 refreshRate2->mode->getVsyncPeriod()) {
853 return refreshRate1->mode->getVsyncPeriod() >
854 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700855 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100856 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700857 }
Ady Abraham2139f732019-11-13 18:56:40 -0800858 });
859}
860
861void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100862 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700863 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100864 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100865 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700866
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100867 auto filterRefreshRates =
868 [&](Fps min, Fps max, const char* listName,
869 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
870 getSortedRefreshRateListLocked(
871 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
872 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800873
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100874 return mode->getHeight() == defaultMode->getHeight() &&
875 mode->getWidth() == defaultMode->getWidth() &&
876 mode->getDpiX() == defaultMode->getDpiX() &&
877 mode->getDpiY() == defaultMode->getDpiY() &&
878 (policy->allowGroupSwitching ||
879 mode->getGroup() == defaultMode->getGroup()) &&
880 refreshRate.inPolicy(min, max);
881 },
882 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800883
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100884 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
885 "No matching modes for %s range: min=%s max=%s", listName,
886 to_string(min).c_str(), to_string(max).c_str());
887 auto stringifyRefreshRates = [&]() -> std::string {
888 std::string str;
889 for (auto refreshRate : *outRefreshRates) {
890 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
891 }
892 return str;
893 };
894 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
895 };
Steven Thomasf734df42020-04-13 21:09:28 -0700896
897 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
898 &mPrimaryRefreshRates);
899 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
900 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800901}
902
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100903Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
904 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700905 return *mKnownFrameRates.begin();
906 }
907
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100908 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700909 return *std::prev(mKnownFrameRates.end());
910 }
911
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100912 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
913 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700914
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100915 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
916 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700917 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
918}
919
Ana Krulecb9afd792020-06-11 13:16:15 -0700920RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
921 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100922 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700923 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
924 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
TreeHugger Robot758ab612021-06-22 19:17:29 +0000925 const auto& currentPolicy = getCurrentPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700926
927 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
928 // the min allowed refresh rate is higher than the device min, we do not want to enable the
929 // timer.
930 if (deviceMin < minByPolicy) {
931 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
932 }
933 if (minByPolicy == maxByPolicy) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000934 // when min primary range in display manager policy is below device min turn on the timer.
935 if (currentPolicy->primaryRange.min.lessThanWithMargin(deviceMin.getFps())) {
936 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700937 }
938 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
939 }
940 // Turn on the timer in all other cases.
941 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
942}
943
Ady Abraham62a0be22020-12-08 16:54:10 -0800944int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700945 // This calculation needs to be in sync with the java code
946 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Ady Abraham3819b9f2021-08-20 10:11:31 -0700947
948 // The threshold must be smaller than 0.001 in order to differentiate
949 // between the fractional pairs (e.g. 59.94 and 60).
950 constexpr float kThreshold = 0.0009f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800951 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700952 const auto numPeriodsRounded = std::round(numPeriods);
953 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800954 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700955 }
956
Ady Abraham62f216c2020-10-13 19:07:23 -0700957 return static_cast<int>(numPeriodsRounded);
958}
959
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200960bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
961 if (smaller.getValue() > bigger.getValue()) {
962 return isFractionalPairOrMultiple(bigger, smaller);
963 }
964
965 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
966 constexpr float kCoef = 1000.f / 1001.f;
967 return bigger.equalsWithMargin(Fps(smaller.getValue() * multiplier / kCoef)) ||
968 bigger.equalsWithMargin(Fps(smaller.getValue() * multiplier * kCoef));
969}
970
Marin Shalamanovba421a82020-11-10 21:49:26 +0100971void RefreshRateConfigs::dump(std::string& result) const {
972 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100973 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100974 mDisplayManagerPolicy.toString().c_str());
975 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
976 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100977 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100978 currentPolicy.toString().c_str());
979 }
980
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100981 auto mode = mCurrentRefreshRate->mode;
982 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100983
984 result.append("Refresh rates:\n");
985 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100986 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +0100987 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
988 }
989
Ady Abraham64c2fc02020-12-29 12:07:50 -0800990 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
991 mSupportsFrameRateOverride ? "yes" : "no");
Ady Abraham6d885932021-09-03 18:05:48 -0700992 base::StringAppendF(&result, "Idle timer: (%s) %s\n",
993 mConfig.supportKernelIdleTimer ? "kernel" : "platform",
Ady Abraham9a2ea342021-09-03 17:32:34 -0700994 mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100995 result.append("\n");
996}
997
Ady Abraham2139f732019-11-13 18:56:40 -0800998} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100999
1000// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001001#pragma clang diagnostic pop // ignored "-Wextra"