blob: c9f00a0376b45b89dad790073b32103c3c201ca7 [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 Abraham05243be2021-09-16 15:58:52 -0700137float RefreshRateConfigs::calculateNonExactMatchingLayerScoreLocked(
138 const LayerRequirement& layer, const RefreshRate& refreshRate) const {
Marin Shalamanov15a0fc62021-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 Shalamanov15a0fc62021-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 Shalamanov15a0fc62021-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 Shalamanov15a0fc62021-08-16 18:20:21 +0200164 if (isFractionalPairOrMultiple(refreshRate.getFps(), layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700165 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-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 Abraham05243be2021-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 Abraham05243be2021-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 Abraham05243be2021-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.
239 constexpr float kNonExactMatchingPenalty = 0.99f;
240 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
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200350 const Policy* policy = getCurrentPolicyLocked();
351 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
352 // If the default mode group is different from the group of current mode,
353 // this means a layer requesting a seamed mode switch just disappeared and
354 // we should switch back to the default group.
355 // However if a seamed layer is still present we anchor around the group
356 // of the current mode, in order to prevent unnecessary seamed mode switches
357 // (e.g. when pausing a video playback).
358 const auto anchorGroup = seamedFocusedLayers > 0 ? mCurrentRefreshRate->getModeGroup()
359 : defaultMode->getModeGroup();
360
Steven Thomasf734df42020-04-13 21:09:28 -0700361 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
362 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700363 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700364 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700365 setTouchConsidered();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200366 return getMaxRefreshRateByPolicyLocked(anchorGroup);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800367 }
368
Alec Mouri11232a22020-05-14 18:06:25 -0700369 // If the primary range consists of a single refresh rate then we can only
370 // move out the of range if layers explicitly request a different refresh
371 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100372 const bool primaryRangeIsSingleRate =
373 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700374
Ady Abrahamdfd62162020-06-10 16:11:56 -0700375 if (!globalSignals.touch && globalSignals.idle &&
376 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700377 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700378 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700379 return getMinRefreshRateByPolicyLocked();
380 }
381
Steven Thomasdebafed2020-05-18 17:30:35 -0700382 if (layers.empty() || noVoteLayers == layers.size()) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200383 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
384 ALOGV("no layers with votes - choose %s", refreshRate.getName().c_str());
385 return refreshRate;
Steven Thomasbb374322020-04-28 22:47:16 -0700386 }
387
Ady Abraham8a82ba62020-01-17 12:43:17 -0800388 // Only if all layers want Min we should return Min
389 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700390 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700391 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800392 }
393
Ady Abraham8a82ba62020-01-17 12:43:17 -0800394 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800395 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700396 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800397
Steven Thomasf734df42020-04-13 21:09:28 -0700398 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800399 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800400 }
401
402 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700403 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
404 layerVoteTypeString(layer.vote).c_str(), layer.weight,
405 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800406 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800407 continue;
408 }
409
Ady Abraham71c437d2020-01-31 15:56:57 -0800410 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800411
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800412 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100413 const bool isSeamlessSwitch =
414 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200415
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100416 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100417 ALOGV("%s ignores %s to avoid non-seamless switch. 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());
Marin Shalamanov46084422020-10-13 12:33:42 +0200421 continue;
422 }
423
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100424 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
425 !layer.focused) {
426 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100427 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800428 formatLayerInfo(layer, weight).c_str(),
429 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100430 mCurrentRefreshRate->toString().c_str());
431 continue;
432 }
433
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100434 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100435 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100436 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100437 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
438 // disappeared.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200439 const bool isInPolicyForDefault = scores[i].refreshRate->getModeGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100440 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100441 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800442 scores[i].refreshRate->toString().c_str(),
443 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200444 continue;
445 }
446
Ady Abraham62a0be22020-12-08 16:54:10 -0800447 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
448 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700449 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800450 !(layer.focused &&
451 (layer.vote == LayerVoteType::ExplicitDefault ||
452 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700453 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700454 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700455 continue;
456 }
457
Ady Abraham62a0be22020-12-08 16:54:10 -0800458 const auto layerScore =
459 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200460 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800461 scores[i].refreshRate->getName().c_str(), layerScore);
462 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800463 }
464 }
465
Ady Abraham34702102020-02-10 14:12:05 -0800466 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
467 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
468 // or the lower otherwise.
469 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
470 ? getBestRefreshRate(scores.rbegin(), scores.rend())
471 : getBestRefreshRate(scores.begin(), scores.end());
472
Alec Mouri11232a22020-05-14 18:06:25 -0700473 if (primaryRangeIsSingleRate) {
474 // If we never scored any layers, then choose the rate from the primary
475 // range instead of picking a random score from the app range.
476 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800477 [](RefreshRateScore score) { return score.score == 0; })) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200478 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
479 ALOGV("layers not scored - choose %s", refreshRate.getName().c_str());
480 return refreshRate;
Alec Mouri11232a22020-05-14 18:06:25 -0700481 } else {
482 return *bestRefreshRate;
483 }
484 }
485
Steven Thomasf734df42020-04-13 21:09:28 -0700486 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
487 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
488 // vote we should not change it if we get a touch event. Only apply touch boost if it will
489 // actually increase the refresh rate over the normal selection.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200490 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
Alec Mouri11232a22020-05-14 18:06:25 -0700491
Ady Abraham5e4e9832021-06-14 13:40:56 -0700492 const bool touchBoostForExplicitExact = [&] {
493 if (mSupportsFrameRateOverride) {
494 // Enable touch boost if there are other layers besides exact
495 return explicitExact + noVoteLayers != layers.size();
496 } else {
497 // Enable touch boost if there are no exact layers
498 return explicitExact == 0;
499 }
500 }();
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800501 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Ady Abraham6b7ad652021-06-23 17:34:57 -0700502 bestRefreshRate->getFps().lessThanWithMargin(touchRefreshRate.getFps())) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700503 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700504 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700505 return touchRefreshRate;
506 }
507
Ady Abrahamde7156e2020-02-28 17:29:39 -0800508 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800509}
510
Ady Abraham62a0be22020-12-08 16:54:10 -0800511std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
512groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
513 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
514 for (const auto& layer : layers) {
515 auto iter = layersByUid.emplace(layer.ownerUid,
516 std::vector<const RefreshRateConfigs::LayerRequirement*>());
517 auto& layersWithSameUid = iter.first->second;
518 layersWithSameUid.push_back(&layer);
519 }
520
521 // Remove uids that can't have a frame rate override
522 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
523 const auto& layersWithSameUid = iter->second;
524 bool skipUid = false;
525 for (const auto& layer : layersWithSameUid) {
526 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
527 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
528 skipUid = true;
529 break;
530 }
531 }
532 if (skipUid) {
533 iter = layersByUid.erase(iter);
534 } else {
535 ++iter;
536 }
537 }
538
539 return layersByUid;
540}
541
542std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
543 const AllRefreshRatesMapType& refreshRates) {
544 std::vector<RefreshRateScore> scores;
545 scores.reserve(refreshRates.size());
546 for (const auto& [ignored, refreshRate] : refreshRates) {
547 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
548 }
549 std::sort(scores.begin(), scores.end(),
550 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
551 return scores;
552}
553
554RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800555 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800556 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800557 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800558
Ady Abraham64c2fc02020-12-29 12:07:50 -0800559 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800560 std::lock_guard lock(mLock);
561 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
562 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
563 groupLayersByUid(layers);
564 UidToFrameRateOverride frameRateOverrides;
565 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800566 // Layers with ExplicitExactOrMultiple expect touch boost
567 const bool hasExplicitExactOrMultiple =
568 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
569 [](const auto& layer) {
570 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
571 });
572
573 if (touch && hasExplicitExactOrMultiple) {
574 continue;
575 }
576
Ady Abraham62a0be22020-12-08 16:54:10 -0800577 for (auto& score : scores) {
578 score.score = 0;
579 }
580
581 for (const auto& layer : layersWithSameUid) {
582 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
583 continue;
584 }
585
586 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800587 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
588 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800589 for (RefreshRateScore& score : scores) {
590 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
591 /*isSeamlessSwitch*/ true);
592 score.score += layer->weight * layerScore;
593 }
594 }
595
596 // We just care about the refresh rates which are a divider of the
597 // display refresh rate
598 auto iter =
599 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
600 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
601 });
602 scores.erase(iter, scores.end());
603
604 // If we never scored any layers, we don't have a preferred frame rate
605 if (std::all_of(scores.begin(), scores.end(),
606 [](const RefreshRateScore& score) { return score.score == 0; })) {
607 continue;
608 }
609
610 // Now that we scored all the refresh rates we need to pick the one that got the highest
611 // score.
612 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700613 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800614 }
615
616 return frameRateOverrides;
617}
618
Ady Abraham34702102020-02-10 14:12:05 -0800619template <typename Iter>
620const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200621 constexpr auto kEpsilon = 0.0001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800622 const RefreshRate* bestRefreshRate = begin->refreshRate;
623 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800624 for (auto i = begin; i != end; ++i) {
625 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100626 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800627
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100628 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800629
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200630 if (score > max * (1 + kEpsilon)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800631 max = score;
632 bestRefreshRate = refreshRate;
633 }
634 }
635
Ady Abraham34702102020-02-10 14:12:05 -0800636 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800637}
638
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100639std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100640 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800641 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100642
643 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
644 : *mCurrentRefreshRate;
645 const auto& min = *mMinSupportedRefreshRate;
646
647 if (current != min) {
648 const auto& refreshRate = timerExpired ? min : current;
649 return refreshRate.getFps();
650 }
651
652 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700653}
654
655const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200656 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100657 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200658 return *refreshRate;
659 }
660 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100661 ALOGE("Can't find min refresh rate by policy with the same mode group"
662 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200663 mCurrentRefreshRate->toString().c_str());
664 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700665 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800666}
667
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100668RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800669 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700670 return getMaxRefreshRateByPolicyLocked();
671}
672
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200673const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200674 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
675 const auto& refreshRate = (**it);
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200676 if (anchorGroup == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200677 return refreshRate;
678 }
679 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100680 ALOGE("Can't find max refresh rate by policy with the same mode group"
681 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200682 mCurrentRefreshRate->toString().c_str());
683 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700684 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800685}
686
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100687RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800688 std::lock_guard lock(mLock);
689 return *mCurrentRefreshRate;
690}
691
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100692RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800693 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800694 return getCurrentRefreshRateByPolicyLocked();
695}
696
697const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700698 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
699 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800700 return *mCurrentRefreshRate;
701 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100702 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800703}
704
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100705void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800706 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200707
708 // Invalidate the cached invocation to getBestRefreshRate. This forces
709 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
710 lastBestRefreshRateInvocation.reset();
711
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100712 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800713}
714
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100715RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
rnlee3bd610662021-06-23 16:27:57 -0700716 Config config)
717 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700718 initializeIdleTimer();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100719 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100720}
721
Ady Abraham9a2ea342021-09-03 17:32:34 -0700722void RefreshRateConfigs::initializeIdleTimer() {
Ady Abraham6d885932021-09-03 18:05:48 -0700723 if (mConfig.idleTimerTimeoutMs > 0) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700724 const auto getCallback = [this]() -> std::optional<IdleTimerCallbacks::Callbacks> {
725 std::scoped_lock lock(mIdleTimerCallbacksMutex);
726 if (!mIdleTimerCallbacks.has_value()) return {};
Ady Abraham6d885932021-09-03 18:05:48 -0700727 return mConfig.supportKernelIdleTimer ? mIdleTimerCallbacks->kernel
728 : mIdleTimerCallbacks->platform;
Ady Abraham9a2ea342021-09-03 17:32:34 -0700729 };
730
731 mIdleTimer.emplace(
Ady Abraham6d885932021-09-03 18:05:48 -0700732 "IdleTimer", std::chrono::milliseconds(mConfig.idleTimerTimeoutMs),
Ady Abraham9a2ea342021-09-03 17:32:34 -0700733 [getCallback] {
734 if (const auto callback = getCallback()) callback->onReset();
735 },
736 [getCallback] {
737 if (const auto callback = getCallback()) callback->onExpired();
738 });
739 mIdleTimer->start();
740 }
741}
742
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100743void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
744 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100745 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200746
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100747 // The current mode should be supported
748 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
749 return mode->getId() == currentModeId;
750 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700751
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200752 // Invalidate the cached invocation to getBestRefreshRate. This forces
753 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
754 lastBestRefreshRateInvocation.reset();
755
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100756 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100757 for (const auto& mode : modes) {
758 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100759 mRefreshRates.emplace(modeId,
Ady Abraham6b7ad652021-06-23 17:34:57 -0700760 std::make_unique<RefreshRate>(mode, RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100761 if (modeId == currentModeId) {
762 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700763 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800764 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700765
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100766 std::vector<const RefreshRate*> sortedModes;
767 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100768 // Reset the policy because the old one may no longer be valid.
769 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100770 mDisplayManagerPolicy.defaultMode = currentModeId;
771 mMinSupportedRefreshRate = sortedModes.front();
772 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800773
774 mSupportsFrameRateOverride = false;
rnlee3bd610662021-06-23 16:27:57 -0700775 if (mConfig.enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100776 for (const auto& mode1 : sortedModes) {
777 for (const auto& mode2 : sortedModes) {
778 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800779 mSupportsFrameRateOverride = true;
780 break;
781 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800782 }
783 }
784 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800785
Ady Abrahamabc27602020-04-08 17:20:29 -0700786 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800787}
788
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100789bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100790 // defaultMode must be a valid mode, and within the given refresh rate range.
791 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700792 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100793 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700794 return false;
795 }
796 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700797 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100798 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700799 return false;
800 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100801 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
802 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700803}
804
805status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800806 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100807 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100808 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100809 return BAD_VALUE;
810 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200811 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700812 Policy previousPolicy = *getCurrentPolicyLocked();
813 mDisplayManagerPolicy = policy;
814 if (*getCurrentPolicyLocked() == previousPolicy) {
815 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100816 }
Ady Abraham2139f732019-11-13 18:56:40 -0800817 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100818 return NO_ERROR;
819}
820
Steven Thomasd4071902020-03-24 16:02:53 -0700821status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100822 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100823 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700824 return BAD_VALUE;
825 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200826 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700827 Policy previousPolicy = *getCurrentPolicyLocked();
828 mOverridePolicy = policy;
829 if (*getCurrentPolicyLocked() == previousPolicy) {
830 return CURRENT_POLICY_UNCHANGED;
831 }
832 constructAvailableRefreshRates();
833 return NO_ERROR;
834}
835
836const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
837 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
838}
839
840RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
841 std::lock_guard lock(mLock);
842 return *getCurrentPolicyLocked();
843}
844
845RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
846 std::lock_guard lock(mLock);
847 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100848}
849
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100850bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100851 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700852 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700853 if (refreshRate->getModeId() == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100854 return true;
855 }
856 }
857 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800858}
859
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100860void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800861 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
862 std::vector<const RefreshRate*>* outRefreshRates) {
863 outRefreshRates->clear();
864 outRefreshRates->reserve(mRefreshRates.size());
865 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800866 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100867 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Ady Abraham6b7ad652021-06-23 17:34:57 -0700868 refreshRate->getModeId().value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800869 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800870 }
871 }
872
873 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
874 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100875 if (refreshRate1->mode->getVsyncPeriod() !=
876 refreshRate2->mode->getVsyncPeriod()) {
877 return refreshRate1->mode->getVsyncPeriod() >
878 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700879 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100880 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700881 }
Ady Abraham2139f732019-11-13 18:56:40 -0800882 });
883}
884
885void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100886 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700887 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100888 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100889 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700890
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100891 auto filterRefreshRates =
892 [&](Fps min, Fps max, const char* listName,
893 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
894 getSortedRefreshRateListLocked(
895 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
896 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800897
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100898 return mode->getHeight() == defaultMode->getHeight() &&
899 mode->getWidth() == defaultMode->getWidth() &&
900 mode->getDpiX() == defaultMode->getDpiX() &&
901 mode->getDpiY() == defaultMode->getDpiY() &&
902 (policy->allowGroupSwitching ||
903 mode->getGroup() == defaultMode->getGroup()) &&
904 refreshRate.inPolicy(min, max);
905 },
906 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800907
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100908 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
909 "No matching modes for %s range: min=%s max=%s", listName,
910 to_string(min).c_str(), to_string(max).c_str());
911 auto stringifyRefreshRates = [&]() -> std::string {
912 std::string str;
913 for (auto refreshRate : *outRefreshRates) {
914 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
915 }
916 return str;
917 };
918 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
919 };
Steven Thomasf734df42020-04-13 21:09:28 -0700920
921 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
922 &mPrimaryRefreshRates);
923 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
924 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800925}
926
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100927Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
928 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700929 return *mKnownFrameRates.begin();
930 }
931
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100932 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700933 return *std::prev(mKnownFrameRates.end());
934 }
935
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100936 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
937 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700938
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100939 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
940 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700941 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
942}
943
Ana Krulecb9afd792020-06-11 13:16:15 -0700944RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
945 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100946 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700947 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
948 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
TreeHugger Robot758ab612021-06-22 19:17:29 +0000949 const auto& currentPolicy = getCurrentPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700950
951 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
952 // the min allowed refresh rate is higher than the device min, we do not want to enable the
953 // timer.
954 if (deviceMin < minByPolicy) {
955 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
956 }
957 if (minByPolicy == maxByPolicy) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000958 // when min primary range in display manager policy is below device min turn on the timer.
959 if (currentPolicy->primaryRange.min.lessThanWithMargin(deviceMin.getFps())) {
960 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700961 }
962 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
963 }
964 // Turn on the timer in all other cases.
965 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
966}
967
Ady Abraham62a0be22020-12-08 16:54:10 -0800968int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700969 // This calculation needs to be in sync with the java code
970 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200971
972 // The threshold must be smaller than 0.001 in order to differentiate
973 // between the fractional pairs (e.g. 59.94 and 60).
974 constexpr float kThreshold = 0.0009f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800975 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700976 const auto numPeriodsRounded = std::round(numPeriods);
977 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800978 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700979 }
980
Ady Abraham62f216c2020-10-13 19:07:23 -0700981 return static_cast<int>(numPeriodsRounded);
982}
983
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200984bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
985 if (smaller.getValue() > bigger.getValue()) {
986 return isFractionalPairOrMultiple(bigger, smaller);
987 }
988
989 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
990 constexpr float kCoef = 1000.f / 1001.f;
991 return bigger.equalsWithMargin(Fps(smaller.getValue() * multiplier / kCoef)) ||
992 bigger.equalsWithMargin(Fps(smaller.getValue() * multiplier * kCoef));
993}
994
Marin Shalamanovba421a82020-11-10 21:49:26 +0100995void RefreshRateConfigs::dump(std::string& result) const {
996 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100997 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100998 mDisplayManagerPolicy.toString().c_str());
999 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
1000 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001001 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +01001002 currentPolicy.toString().c_str());
1003 }
1004
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001005 auto mode = mCurrentRefreshRate->mode;
1006 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +01001007
1008 result.append("Refresh rates:\n");
1009 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001010 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +01001011 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
1012 }
1013
Ady Abraham64c2fc02020-12-29 12:07:50 -08001014 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
1015 mSupportsFrameRateOverride ? "yes" : "no");
Ady Abraham6d885932021-09-03 18:05:48 -07001016 base::StringAppendF(&result, "Idle timer: (%s) %s\n",
1017 mConfig.supportKernelIdleTimer ? "kernel" : "platform",
Ady Abraham9a2ea342021-09-03 17:32:34 -07001018 mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Marin Shalamanovba421a82020-11-10 21:49:26 +01001019 result.append("\n");
1020}
1021
Ady Abraham2139f732019-11-13 18:56:40 -08001022} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001023
1024// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001025#pragma clang diagnostic pop // ignored "-Wextra"