blob: a56827e8f16cbdac7fbced22af8bdc579293bace [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 Abrahamb3512452021-09-16 15:58:52 -0700137float RefreshRateConfigs::calculateNonExactMatchingLayerScoreLocked(
138 const LayerRequirement& layer, const RefreshRate& refreshRate) const {
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200139 constexpr float kScoreForFractionalPairs = .8f;
140
Ady Abraham62a0be22020-12-08 16:54:10 -0800141 const auto displayPeriod = refreshRate.getVsyncPeriod();
142 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
143 if (layer.vote == LayerVoteType::ExplicitDefault) {
144 // Find the actual rate the layer will render, assuming
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200145 // that layerPeriod is the minimal period to render a frame.
146 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
147 // then the actualLayerPeriod will be 32ms, because it is the
148 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800149 auto actualLayerPeriod = displayPeriod;
150 int multiplier = 1;
151 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
152 multiplier++;
153 actualLayerPeriod = displayPeriod * multiplier;
154 }
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200155
156 // Because of the threshold we used above it's possible that score is slightly
157 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800158 return std::min(1.0f,
159 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
160 }
161
162 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
163 layer.vote == LayerVoteType::Heuristic) {
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200164 if (isFractionalPairOrMultiple(refreshRate.getFps(), layer.desiredRefreshRate)) {
Ady Abrahamb3512452021-09-16 15:58:52 -0700165 return kScoreForFractionalPairs;
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200166 }
167
Ady Abraham62a0be22020-12-08 16:54:10 -0800168 // Calculate how many display vsyncs we need to present a single frame for this
169 // layer
170 const auto [displayFramesQuotient, displayFramesRemainder] =
171 getDisplayFrames(layerPeriod, displayPeriod);
172 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
173 if (displayFramesRemainder == 0) {
174 // Layer desired refresh rate matches the display rate.
Ady Abrahamb3512452021-09-16 15:58:52 -0700175 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800176 }
177
178 if (displayFramesQuotient == 0) {
179 // Layer desired refresh rate is higher than the display rate.
180 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
181 (1.0f / (MAX_FRAMES_TO_FIT + 1));
182 }
183
184 // Layer desired refresh rate is lower than the display rate. Check how well it fits
185 // the cadence.
186 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
187 int iter = 2;
188 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
189 diff = diff - (displayPeriod - diff);
190 iter++;
191 }
192
Ady Abrahamb3512452021-09-16 15:58:52 -0700193 return (1.0f / iter);
194 }
195
196 return 0;
197}
198
199float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
200 const RefreshRate& refreshRate,
201 bool isSeamlessSwitch) const {
202 if (!isVoteAllowed(layer, refreshRate)) {
203 return 0;
204 }
205
206 // Slightly prefer seamless switches.
207 constexpr float kSeamedSwitchPenalty = 0.95f;
208 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
209
210 // If the layer wants Max, give higher score to the higher refresh rate
211 if (layer.vote == LayerVoteType::Max) {
212 const auto ratio = refreshRate.getFps().getValue() /
213 mAppRequestRefreshRates.back()->getFps().getValue();
214 // use ratio^2 to get a lower score the more we get further from peak
215 return ratio * ratio;
Ady Abraham62a0be22020-12-08 16:54:10 -0800216 }
217
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800218 if (layer.vote == LayerVoteType::ExplicitExact) {
219 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
220 if (mSupportsFrameRateOverride) {
221 // Since we support frame rate override, allow refresh rates which are
222 // multiples of the layer's request, as those apps would be throttled
223 // down to run at the desired refresh rate.
224 return divider > 0;
225 }
226
227 return divider == 1;
228 }
229
Ady Abrahamb3512452021-09-16 15:58:52 -0700230 // If the layer frame rate is a divider of the refresh rate it should score
231 // the highest score.
232 if (getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate) > 0) {
233 return 1.0f * seamlessness;
234 }
235
236 // The layer frame rate is not a divider of the refresh rate,
237 // there is a small penalty attached to the score to favor the frame rates
238 // the exactly matches the display refresh rate or a multiple.
Ady Abraham3ef084b2022-01-13 21:58:32 -0800239 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abrahamb3512452021-09-16 15:58:52 -0700240 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
241 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800242}
243
244struct RefreshRateScore {
245 const RefreshRate* refreshRate;
246 float score;
247};
248
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100249RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
250 const GlobalSignals& globalSignals,
251 GlobalSignals* outSignalsConsidered) const {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200252 std::lock_guard lock(mLock);
253
254 if (auto cached = getCachedBestRefreshRate(layers, globalSignals, outSignalsConsidered)) {
255 return *cached;
256 }
257
258 GlobalSignals signalsConsidered;
259 RefreshRate result = getBestRefreshRateLocked(layers, globalSignals, &signalsConsidered);
260 lastBestRefreshRateInvocation.emplace(
261 GetBestRefreshRateInvocation{.layerRequirements = layers,
262 .globalSignals = globalSignals,
263 .outSignalsConsidered = signalsConsidered,
264 .resultingBestRefreshRate = result});
265 if (outSignalsConsidered) {
266 *outSignalsConsidered = signalsConsidered;
267 }
268 return result;
269}
270
271std::optional<RefreshRate> RefreshRateConfigs::getCachedBestRefreshRate(
272 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
273 GlobalSignals* outSignalsConsidered) const {
274 const bool sameAsLastCall = lastBestRefreshRateInvocation &&
275 lastBestRefreshRateInvocation->layerRequirements == layers &&
276 lastBestRefreshRateInvocation->globalSignals == globalSignals;
277
278 if (sameAsLastCall) {
279 if (outSignalsConsidered) {
280 *outSignalsConsidered = lastBestRefreshRateInvocation->outSignalsConsidered;
281 }
282 return lastBestRefreshRateInvocation->resultingBestRefreshRate;
283 }
284
285 return {};
286}
287
288RefreshRate RefreshRateConfigs::getBestRefreshRateLocked(
289 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
290 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800291 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200292 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800293
Ady Abrahamdfd62162020-06-10 16:11:56 -0700294 if (outSignalsConsidered) *outSignalsConsidered = {};
295 const auto setTouchConsidered = [&] {
296 if (outSignalsConsidered) {
297 outSignalsConsidered->touch = true;
298 }
299 };
300
301 const auto setIdleConsidered = [&] {
302 if (outSignalsConsidered) {
303 outSignalsConsidered->idle = true;
304 }
305 };
306
Ady Abraham8a82ba62020-01-17 12:43:17 -0800307 int noVoteLayers = 0;
308 int minVoteLayers = 0;
309 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800310 int explicitDefaultVoteLayers = 0;
311 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800312 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800313 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100314 int seamedFocusedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800315 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800316 switch (layer.vote) {
317 case LayerVoteType::NoVote:
318 noVoteLayers++;
319 break;
320 case LayerVoteType::Min:
321 minVoteLayers++;
322 break;
323 case LayerVoteType::Max:
324 maxVoteLayers++;
325 break;
326 case LayerVoteType::ExplicitDefault:
327 explicitDefaultVoteLayers++;
328 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
329 break;
330 case LayerVoteType::ExplicitExactOrMultiple:
331 explicitExactOrMultipleVoteLayers++;
332 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
333 break;
334 case LayerVoteType::ExplicitExact:
335 explicitExact++;
336 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
337 break;
338 case LayerVoteType::Heuristic:
339 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800340 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200341
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100342 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
343 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200344 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800345 }
346
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800347 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
348 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700349
Steven Thomasf734df42020-04-13 21:09:28 -0700350 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
351 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700352 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700353 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700354 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700355 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800356 }
357
Alec Mouri11232a22020-05-14 18:06:25 -0700358 // If the primary range consists of a single refresh rate then we can only
359 // move out the of range if layers explicitly request a different refresh
360 // rate.
361 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100362 const bool primaryRangeIsSingleRate =
363 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700364
Ady Abrahamdfd62162020-06-10 16:11:56 -0700365 if (!globalSignals.touch && globalSignals.idle &&
366 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700367 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700368 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700369 return getMinRefreshRateByPolicyLocked();
370 }
371
Steven Thomasdebafed2020-05-18 17:30:35 -0700372 if (layers.empty() || noVoteLayers == layers.size()) {
373 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700374 }
375
Ady Abraham8a82ba62020-01-17 12:43:17 -0800376 // Only if all layers want Min we should return Min
377 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700378 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700379 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800380 }
381
Ady Abraham8a82ba62020-01-17 12:43:17 -0800382 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800383 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700384 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800385
Steven Thomasf734df42020-04-13 21:09:28 -0700386 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800387 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800388 }
389
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100390 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
Marin Shalamanov46084422020-10-13 12:33:42 +0200391
Ady Abraham8a82ba62020-01-17 12:43:17 -0800392 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700393 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
394 layerVoteTypeString(layer.vote).c_str(), layer.weight,
395 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800396 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800397 continue;
398 }
399
Ady Abraham71c437d2020-01-31 15:56:57 -0800400 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800401
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800402 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100403 const bool isSeamlessSwitch =
404 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200405
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100406 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100407 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800408 formatLayerInfo(layer, weight).c_str(),
409 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100410 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200411 continue;
412 }
413
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100414 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
415 !layer.focused) {
416 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100417 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800418 formatLayerInfo(layer, weight).c_str(),
419 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100420 mCurrentRefreshRate->toString().c_str());
421 continue;
422 }
423
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100424 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100425 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100426 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100427 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
428 // disappeared.
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100429 const bool isInPolicyForDefault = seamedFocusedLayers > 0
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100430 ? scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup()
431 : scores[i].refreshRate->getModeGroup() == defaultMode->getModeGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100432
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100433 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100434 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800435 scores[i].refreshRate->toString().c_str(),
436 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200437 continue;
438 }
439
Ady Abraham62a0be22020-12-08 16:54:10 -0800440 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
441 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700442 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800443 !(layer.focused &&
444 (layer.vote == LayerVoteType::ExplicitDefault ||
445 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700446 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700447 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700448 continue;
449 }
450
Ady Abraham62a0be22020-12-08 16:54:10 -0800451 const auto layerScore =
452 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200453 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800454 scores[i].refreshRate->getName().c_str(), layerScore);
455 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800456 }
457 }
458
Ady Abraham34702102020-02-10 14:12:05 -0800459 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
460 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
461 // or the lower otherwise.
462 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
463 ? getBestRefreshRate(scores.rbegin(), scores.rend())
464 : getBestRefreshRate(scores.begin(), scores.end());
465
Alec Mouri11232a22020-05-14 18:06:25 -0700466 if (primaryRangeIsSingleRate) {
467 // If we never scored any layers, then choose the rate from the primary
468 // range instead of picking a random score from the app range.
469 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800470 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700471 ALOGV("layers not scored - choose %s",
472 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700473 return getMaxRefreshRateByPolicyLocked();
474 } else {
475 return *bestRefreshRate;
476 }
477 }
478
Steven Thomasf734df42020-04-13 21:09:28 -0700479 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
480 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
481 // vote we should not change it if we get a touch event. Only apply touch boost if it will
482 // actually increase the refresh rate over the normal selection.
483 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700484
Ady Abraham5e4e9832021-06-14 13:40:56 -0700485 const bool touchBoostForExplicitExact = [&] {
486 if (mSupportsFrameRateOverride) {
487 // Enable touch boost if there are other layers besides exact
488 return explicitExact + noVoteLayers != layers.size();
489 } else {
490 // Enable touch boost if there are no exact layers
491 return explicitExact == 0;
492 }
493 }();
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800494 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Ady Abraham6b7ad652021-06-23 17:34:57 -0700495 bestRefreshRate->getFps().lessThanWithMargin(touchRefreshRate.getFps())) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700496 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700497 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700498 return touchRefreshRate;
499 }
500
Ady Abrahamde7156e2020-02-28 17:29:39 -0800501 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800502}
503
Ady Abraham62a0be22020-12-08 16:54:10 -0800504std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
505groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
506 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
507 for (const auto& layer : layers) {
508 auto iter = layersByUid.emplace(layer.ownerUid,
509 std::vector<const RefreshRateConfigs::LayerRequirement*>());
510 auto& layersWithSameUid = iter.first->second;
511 layersWithSameUid.push_back(&layer);
512 }
513
514 // Remove uids that can't have a frame rate override
515 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
516 const auto& layersWithSameUid = iter->second;
517 bool skipUid = false;
518 for (const auto& layer : layersWithSameUid) {
519 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
520 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
521 skipUid = true;
522 break;
523 }
524 }
525 if (skipUid) {
526 iter = layersByUid.erase(iter);
527 } else {
528 ++iter;
529 }
530 }
531
532 return layersByUid;
533}
534
535std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
536 const AllRefreshRatesMapType& refreshRates) {
537 std::vector<RefreshRateScore> scores;
538 scores.reserve(refreshRates.size());
539 for (const auto& [ignored, refreshRate] : refreshRates) {
540 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
541 }
542 std::sort(scores.begin(), scores.end(),
543 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
544 return scores;
545}
546
547RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800548 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800549 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800550 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800551
Ady Abraham64c2fc02020-12-29 12:07:50 -0800552 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800553 std::lock_guard lock(mLock);
554 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
555 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
556 groupLayersByUid(layers);
557 UidToFrameRateOverride frameRateOverrides;
558 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800559 // Layers with ExplicitExactOrMultiple expect touch boost
560 const bool hasExplicitExactOrMultiple =
561 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
562 [](const auto& layer) {
563 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
564 });
565
566 if (touch && hasExplicitExactOrMultiple) {
567 continue;
568 }
569
Ady Abraham62a0be22020-12-08 16:54:10 -0800570 for (auto& score : scores) {
571 score.score = 0;
572 }
573
574 for (const auto& layer : layersWithSameUid) {
575 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
576 continue;
577 }
578
579 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800580 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
581 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800582 for (RefreshRateScore& score : scores) {
583 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
584 /*isSeamlessSwitch*/ true);
585 score.score += layer->weight * layerScore;
586 }
587 }
588
589 // We just care about the refresh rates which are a divider of the
590 // display refresh rate
591 auto iter =
592 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
593 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
594 });
595 scores.erase(iter, scores.end());
596
597 // If we never scored any layers, we don't have a preferred frame rate
598 if (std::all_of(scores.begin(), scores.end(),
599 [](const RefreshRateScore& score) { return score.score == 0; })) {
600 continue;
601 }
602
603 // Now that we scored all the refresh rates we need to pick the one that got the highest
604 // score.
605 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700606 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800607 }
608
609 return frameRateOverrides;
610}
611
Ady Abraham34702102020-02-10 14:12:05 -0800612template <typename Iter>
613const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200614 constexpr auto kEpsilon = 0.0001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800615 const RefreshRate* bestRefreshRate = begin->refreshRate;
616 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800617 for (auto i = begin; i != end; ++i) {
618 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100619 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800620
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100621 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800622
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200623 if (score > max * (1 + kEpsilon)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800624 max = score;
625 bestRefreshRate = refreshRate;
626 }
627 }
628
Ady Abraham34702102020-02-10 14:12:05 -0800629 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800630}
631
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100632std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100633 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800634 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100635
636 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
637 : *mCurrentRefreshRate;
638 const auto& min = *mMinSupportedRefreshRate;
639
640 if (current != min) {
641 const auto& refreshRate = timerExpired ? min : current;
642 return refreshRate.getFps();
643 }
644
645 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700646}
647
648const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200649 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100650 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200651 return *refreshRate;
652 }
653 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100654 ALOGE("Can't find min refresh rate by policy with the same mode group"
655 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200656 mCurrentRefreshRate->toString().c_str());
657 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700658 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800659}
660
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100661RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800662 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700663 return getMaxRefreshRateByPolicyLocked();
664}
665
666const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200667 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
668 const auto& refreshRate = (**it);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100669 if (mCurrentRefreshRate->getModeGroup() == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200670 return refreshRate;
671 }
672 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100673 ALOGE("Can't find max refresh rate by policy with the same mode group"
674 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200675 mCurrentRefreshRate->toString().c_str());
676 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700677 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800678}
679
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100680RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800681 std::lock_guard lock(mLock);
682 return *mCurrentRefreshRate;
683}
684
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100685RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800686 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800687 return getCurrentRefreshRateByPolicyLocked();
688}
689
690const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700691 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
692 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800693 return *mCurrentRefreshRate;
694 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100695 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800696}
697
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100698void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800699 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200700
701 // Invalidate the cached invocation to getBestRefreshRate. This forces
702 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
703 lastBestRefreshRateInvocation.reset();
704
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100705 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800706}
707
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100708RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
rnlee3bd610662021-06-23 16:27:57 -0700709 Config config)
710 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700711 initializeIdleTimer();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100712 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100713}
714
Ady Abraham9a2ea342021-09-03 17:32:34 -0700715void RefreshRateConfigs::initializeIdleTimer() {
Ady Abraham6d885932021-09-03 18:05:48 -0700716 if (mConfig.idleTimerTimeoutMs > 0) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700717 const auto getCallback = [this]() -> std::optional<IdleTimerCallbacks::Callbacks> {
718 std::scoped_lock lock(mIdleTimerCallbacksMutex);
719 if (!mIdleTimerCallbacks.has_value()) return {};
Ady Abraham6d885932021-09-03 18:05:48 -0700720 return mConfig.supportKernelIdleTimer ? mIdleTimerCallbacks->kernel
721 : mIdleTimerCallbacks->platform;
Ady Abraham9a2ea342021-09-03 17:32:34 -0700722 };
723
724 mIdleTimer.emplace(
Ady Abraham6d885932021-09-03 18:05:48 -0700725 "IdleTimer", std::chrono::milliseconds(mConfig.idleTimerTimeoutMs),
Ady Abraham9a2ea342021-09-03 17:32:34 -0700726 [getCallback] {
727 if (const auto callback = getCallback()) callback->onReset();
728 },
729 [getCallback] {
730 if (const auto callback = getCallback()) callback->onExpired();
731 });
Ady Abraham9a2ea342021-09-03 17:32:34 -0700732 }
733}
734
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100735void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
736 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100737 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200738
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100739 // The current mode should be supported
740 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
741 return mode->getId() == currentModeId;
742 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700743
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200744 // Invalidate the cached invocation to getBestRefreshRate. This forces
745 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
746 lastBestRefreshRateInvocation.reset();
747
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100748 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100749 for (const auto& mode : modes) {
750 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100751 mRefreshRates.emplace(modeId,
Ady Abraham6b7ad652021-06-23 17:34:57 -0700752 std::make_unique<RefreshRate>(mode, RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100753 if (modeId == currentModeId) {
754 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700755 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800756 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700757
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100758 std::vector<const RefreshRate*> sortedModes;
759 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100760 // Reset the policy because the old one may no longer be valid.
761 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100762 mDisplayManagerPolicy.defaultMode = currentModeId;
763 mMinSupportedRefreshRate = sortedModes.front();
764 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800765
766 mSupportsFrameRateOverride = false;
rnlee3bd610662021-06-23 16:27:57 -0700767 if (mConfig.enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100768 for (const auto& mode1 : sortedModes) {
769 for (const auto& mode2 : sortedModes) {
770 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800771 mSupportsFrameRateOverride = true;
772 break;
773 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800774 }
775 }
776 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800777
Ady Abrahamabc27602020-04-08 17:20:29 -0700778 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800779}
780
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100781bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100782 // defaultMode must be a valid mode, and within the given refresh rate range.
783 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700784 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100785 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700786 return false;
787 }
788 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700789 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100790 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700791 return false;
792 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100793 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
794 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700795}
796
797status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800798 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100799 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100800 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100801 return BAD_VALUE;
802 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200803 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700804 Policy previousPolicy = *getCurrentPolicyLocked();
805 mDisplayManagerPolicy = policy;
806 if (*getCurrentPolicyLocked() == previousPolicy) {
807 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100808 }
Ady Abraham2139f732019-11-13 18:56:40 -0800809 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100810 return NO_ERROR;
811}
812
Steven Thomasd4071902020-03-24 16:02:53 -0700813status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100814 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100815 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700816 return BAD_VALUE;
817 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200818 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700819 Policy previousPolicy = *getCurrentPolicyLocked();
820 mOverridePolicy = policy;
821 if (*getCurrentPolicyLocked() == previousPolicy) {
822 return CURRENT_POLICY_UNCHANGED;
823 }
824 constructAvailableRefreshRates();
825 return NO_ERROR;
826}
827
828const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
829 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
830}
831
832RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
833 std::lock_guard lock(mLock);
834 return *getCurrentPolicyLocked();
835}
836
837RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
838 std::lock_guard lock(mLock);
839 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100840}
841
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100842bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100843 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700844 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700845 if (refreshRate->getModeId() == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100846 return true;
847 }
848 }
849 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800850}
851
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100852void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800853 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
854 std::vector<const RefreshRate*>* outRefreshRates) {
855 outRefreshRates->clear();
856 outRefreshRates->reserve(mRefreshRates.size());
857 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800858 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100859 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Ady Abraham6b7ad652021-06-23 17:34:57 -0700860 refreshRate->getModeId().value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800861 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800862 }
863 }
864
865 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
866 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100867 if (refreshRate1->mode->getVsyncPeriod() !=
868 refreshRate2->mode->getVsyncPeriod()) {
869 return refreshRate1->mode->getVsyncPeriod() >
870 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700871 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100872 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700873 }
Ady Abraham2139f732019-11-13 18:56:40 -0800874 });
875}
876
877void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100878 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700879 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100880 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100881 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700882
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100883 auto filterRefreshRates =
884 [&](Fps min, Fps max, const char* listName,
885 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
886 getSortedRefreshRateListLocked(
887 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
888 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800889
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100890 return mode->getHeight() == defaultMode->getHeight() &&
891 mode->getWidth() == defaultMode->getWidth() &&
892 mode->getDpiX() == defaultMode->getDpiX() &&
893 mode->getDpiY() == defaultMode->getDpiY() &&
894 (policy->allowGroupSwitching ||
895 mode->getGroup() == defaultMode->getGroup()) &&
896 refreshRate.inPolicy(min, max);
897 },
898 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800899
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100900 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
901 "No matching modes for %s range: min=%s max=%s", listName,
902 to_string(min).c_str(), to_string(max).c_str());
903 auto stringifyRefreshRates = [&]() -> std::string {
904 std::string str;
905 for (auto refreshRate : *outRefreshRates) {
906 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
907 }
908 return str;
909 };
910 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
911 };
Steven Thomasf734df42020-04-13 21:09:28 -0700912
913 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
914 &mPrimaryRefreshRates);
915 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
916 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800917}
918
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100919Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
920 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700921 return *mKnownFrameRates.begin();
922 }
923
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100924 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700925 return *std::prev(mKnownFrameRates.end());
926 }
927
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100928 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
929 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700930
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100931 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
932 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700933 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
934}
935
Ana Krulecb9afd792020-06-11 13:16:15 -0700936RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
937 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100938 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700939 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
940 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
TreeHugger Robot758ab612021-06-22 19:17:29 +0000941 const auto& currentPolicy = getCurrentPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700942
943 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
944 // the min allowed refresh rate is higher than the device min, we do not want to enable the
945 // timer.
946 if (deviceMin < minByPolicy) {
947 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
948 }
949 if (minByPolicy == maxByPolicy) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000950 // when min primary range in display manager policy is below device min turn on the timer.
951 if (currentPolicy->primaryRange.min.lessThanWithMargin(deviceMin.getFps())) {
952 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700953 }
954 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
955 }
956 // Turn on the timer in all other cases.
957 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
958}
959
Ady Abraham62a0be22020-12-08 16:54:10 -0800960int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700961 // This calculation needs to be in sync with the java code
962 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Ady Abraham3819b9f2021-08-20 10:11:31 -0700963
964 // The threshold must be smaller than 0.001 in order to differentiate
965 // between the fractional pairs (e.g. 59.94 and 60).
966 constexpr float kThreshold = 0.0009f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800967 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700968 const auto numPeriodsRounded = std::round(numPeriods);
969 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800970 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700971 }
972
Ady Abraham62f216c2020-10-13 19:07:23 -0700973 return static_cast<int>(numPeriodsRounded);
974}
975
Marin Shalamanove3e68ad2021-08-16 18:20:21 +0200976bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
977 if (smaller.getValue() > bigger.getValue()) {
978 return isFractionalPairOrMultiple(bigger, smaller);
979 }
980
981 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
982 constexpr float kCoef = 1000.f / 1001.f;
983 return bigger.equalsWithMargin(Fps(smaller.getValue() * multiplier / kCoef)) ||
984 bigger.equalsWithMargin(Fps(smaller.getValue() * multiplier * kCoef));
985}
986
Marin Shalamanovba421a82020-11-10 21:49:26 +0100987void RefreshRateConfigs::dump(std::string& result) const {
988 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100989 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100990 mDisplayManagerPolicy.toString().c_str());
991 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
992 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100993 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100994 currentPolicy.toString().c_str());
995 }
996
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100997 auto mode = mCurrentRefreshRate->mode;
998 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100999
1000 result.append("Refresh rates:\n");
1001 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001002 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +01001003 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
1004 }
1005
Ady Abraham64c2fc02020-12-29 12:07:50 -08001006 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
1007 mSupportsFrameRateOverride ? "yes" : "no");
Ady Abraham6d885932021-09-03 18:05:48 -07001008 base::StringAppendF(&result, "Idle timer: (%s) %s\n",
1009 mConfig.supportKernelIdleTimer ? "kernel" : "platform",
Ady Abraham9a2ea342021-09-03 17:32:34 -07001010 mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Marin Shalamanovba421a82020-11-10 21:49:26 +01001011 result.append("\n");
1012}
1013
Ady Abraham2139f732019-11-13 18:56:40 -08001014} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001015
1016// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001017#pragma clang diagnostic pop // ignored "-Wextra"