blob: ee1d7301c143dfe350553882fba7b7bd24b81868 [file] [log] [blame]
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001/*
2 * Copyright 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Ady Abraham2139f732019-11-13 18:56:40 -080016
Ady Abraham8a82ba62020-01-17 12:43:17 -080017// #define LOG_NDEBUG 0
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020// TODO(b/129481165): remove the #pragma below and fix conversion issues
21#pragma clang diagnostic push
22#pragma clang diagnostic ignored "-Wextra"
23
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080024#include "RefreshRateConfigs.h"
Ady Abraham9a2ea342021-09-03 17:32:34 -070025#include <android-base/properties.h>
Ady Abraham8a82ba62020-01-17 12:43:17 -080026#include <android-base/stringprintf.h>
27#include <utils/Trace.h>
28#include <chrono>
29#include <cmath>
Ady Abraham4899ff82021-01-06 13:53:29 -080030#include "../SurfaceFlingerProperties.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080031
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080032#undef LOG_TAG
33#define LOG_TAG "RefreshRateConfigs"
34
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080035namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010036namespace {
37std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010038 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010039 RefreshRateConfigs::layerVoteTypeString(layer.vote).c_str(), weight,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010040 toString(layer.seamlessness).c_str(),
41 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010042}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010043
Marin Shalamanova7fe3042021-01-29 21:02:08 +010044std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010045 std::vector<Fps> knownFrameRates = {Fps(24.0f), Fps(30.0f), Fps(45.0f), Fps(60.0f), Fps(72.0f)};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010046 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010047
48 // Add all supported refresh rates to the set
Marin Shalamanova7fe3042021-01-29 21:02:08 +010049 for (const auto& mode : modes) {
50 const auto refreshRate = Fps::fromPeriodNsecs(mode->getVsyncPeriod());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010051 knownFrameRates.emplace_back(refreshRate);
52 }
53
54 // Sort and remove duplicates
55 std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
56 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
57 Fps::EqualsWithMargin()),
58 knownFrameRates.end());
59 return knownFrameRates;
60}
61
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010062} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080063
64using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080065using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080066
Marin Shalamanov46084422020-10-13 12:33:42 +020067std::string RefreshRate::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010068 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010069 getModeId().value(), mode->getHwcId(), getFps().getValue(),
70 mode->getWidth(), mode->getHeight(), getModeGroup());
Marin Shalamanov46084422020-10-13 12:33:42 +020071}
72
Ady Abrahama6b676e2020-05-27 14:29:09 -070073std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
74 switch (vote) {
75 case LayerVoteType::NoVote:
76 return "NoVote";
77 case LayerVoteType::Min:
78 return "Min";
79 case LayerVoteType::Max:
80 return "Max";
81 case LayerVoteType::Heuristic:
82 return "Heuristic";
83 case LayerVoteType::ExplicitDefault:
84 return "ExplicitDefault";
85 case LayerVoteType::ExplicitExactOrMultiple:
86 return "ExplicitExactOrMultiple";
Ady Abrahamdd5bfa92021-01-07 17:56:08 -080087 case LayerVoteType::ExplicitExact:
88 return "ExplicitExact";
Ady Abrahama6b676e2020-05-27 14:29:09 -070089 }
90}
91
Marin Shalamanovb6674e72020-11-06 13:05:57 +010092std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010093 return base::StringPrintf("default mode ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010094 ", primary range: %s, app request range: %s",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010095 defaultMode.value(), allowGroupSwitching,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010096 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020097}
98
Ady Abraham4ccdcb42020-02-11 17:34:34 -080099std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
100 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800101 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
102 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
103 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
104 quotient++;
105 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800106 }
107
Ady Abraham62a0be22020-12-08 16:54:10 -0800108 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800109}
110
rnlee3bd610662021-06-23 16:27:57 -0700111bool RefreshRateConfigs::isVoteAllowed(const LayerRequirement& layer,
112 const RefreshRate& refreshRate) const {
113 switch (layer.vote) {
114 case LayerVoteType::ExplicitExactOrMultiple:
115 case LayerVoteType::Heuristic:
116 if (mConfig.frameRateMultipleThreshold != 0 &&
Ady Abraham6b7ad652021-06-23 17:34:57 -0700117 refreshRate.getFps().greaterThanOrEqualWithMargin(
rnlee3bd610662021-06-23 16:27:57 -0700118 Fps(mConfig.frameRateMultipleThreshold)) &&
119 layer.desiredRefreshRate.lessThanWithMargin(
120 Fps(mConfig.frameRateMultipleThreshold / 2))) {
121 // Don't vote high refresh rates past the threshold for layers with a low desired
122 // refresh rate. For example, desired 24 fps with 120 Hz threshold means no vote for
123 // 120 Hz, but desired 60 fps should have a vote.
124 return false;
125 }
126 break;
127 case LayerVoteType::ExplicitDefault:
128 case LayerVoteType::ExplicitExact:
129 case LayerVoteType::Max:
130 case LayerVoteType::Min:
131 case LayerVoteType::NoVote:
132 break;
133 }
134 return true;
135}
136
Ady Abraham62a0be22020-12-08 16:54:10 -0800137float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
138 const RefreshRate& refreshRate,
139 bool isSeamlessSwitch) const {
rnlee3bd610662021-06-23 16:27:57 -0700140 if (!isVoteAllowed(layer, refreshRate)) {
141 return 0;
142 }
143
Ady Abraham62a0be22020-12-08 16:54:10 -0800144 // Slightly prefer seamless switches.
145 constexpr float kSeamedSwitchPenalty = 0.95f;
146 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
147
148 // If the layer wants Max, give higher score to the higher refresh rate
149 if (layer.vote == LayerVoteType::Max) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700150 const auto ratio = refreshRate.getFps().getValue() /
151 mAppRequestRefreshRates.back()->getFps().getValue();
Ady Abraham62a0be22020-12-08 16:54:10 -0800152 // use ratio^2 to get a lower score the more we get further from peak
153 return ratio * ratio;
154 }
155
156 const auto displayPeriod = refreshRate.getVsyncPeriod();
157 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
158 if (layer.vote == LayerVoteType::ExplicitDefault) {
159 // Find the actual rate the layer will render, assuming
160 // that layerPeriod is the minimal time to render a frame
161 auto actualLayerPeriod = displayPeriod;
162 int multiplier = 1;
163 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
164 multiplier++;
165 actualLayerPeriod = displayPeriod * multiplier;
166 }
167 return std::min(1.0f,
168 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
169 }
170
171 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
172 layer.vote == LayerVoteType::Heuristic) {
173 // Calculate how many display vsyncs we need to present a single frame for this
174 // layer
175 const auto [displayFramesQuotient, displayFramesRemainder] =
176 getDisplayFrames(layerPeriod, displayPeriod);
177 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
178 if (displayFramesRemainder == 0) {
179 // Layer desired refresh rate matches the display rate.
180 return 1.0f * seamlessness;
181 }
182
183 if (displayFramesQuotient == 0) {
184 // Layer desired refresh rate is higher than the display rate.
185 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
186 (1.0f / (MAX_FRAMES_TO_FIT + 1));
187 }
188
189 // Layer desired refresh rate is lower than the display rate. Check how well it fits
190 // the cadence.
191 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
192 int iter = 2;
193 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
194 diff = diff - (displayPeriod - diff);
195 iter++;
196 }
197
198 return (1.0f / iter) * seamlessness;
199 }
200
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800201 if (layer.vote == LayerVoteType::ExplicitExact) {
202 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
203 if (mSupportsFrameRateOverride) {
204 // Since we support frame rate override, allow refresh rates which are
205 // multiples of the layer's request, as those apps would be throttled
206 // down to run at the desired refresh rate.
207 return divider > 0;
208 }
209
210 return divider == 1;
211 }
212
Ady Abraham62a0be22020-12-08 16:54:10 -0800213 return 0;
214}
215
216struct RefreshRateScore {
217 const RefreshRate* refreshRate;
218 float score;
219};
220
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100221RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
222 const GlobalSignals& globalSignals,
223 GlobalSignals* outSignalsConsidered) const {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200224 std::lock_guard lock(mLock);
225
226 if (auto cached = getCachedBestRefreshRate(layers, globalSignals, outSignalsConsidered)) {
227 return *cached;
228 }
229
230 GlobalSignals signalsConsidered;
231 RefreshRate result = getBestRefreshRateLocked(layers, globalSignals, &signalsConsidered);
232 lastBestRefreshRateInvocation.emplace(
233 GetBestRefreshRateInvocation{.layerRequirements = layers,
234 .globalSignals = globalSignals,
235 .outSignalsConsidered = signalsConsidered,
236 .resultingBestRefreshRate = result});
237 if (outSignalsConsidered) {
238 *outSignalsConsidered = signalsConsidered;
239 }
240 return result;
241}
242
243std::optional<RefreshRate> RefreshRateConfigs::getCachedBestRefreshRate(
244 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
245 GlobalSignals* outSignalsConsidered) const {
246 const bool sameAsLastCall = lastBestRefreshRateInvocation &&
247 lastBestRefreshRateInvocation->layerRequirements == layers &&
248 lastBestRefreshRateInvocation->globalSignals == globalSignals;
249
250 if (sameAsLastCall) {
251 if (outSignalsConsidered) {
252 *outSignalsConsidered = lastBestRefreshRateInvocation->outSignalsConsidered;
253 }
254 return lastBestRefreshRateInvocation->resultingBestRefreshRate;
255 }
256
257 return {};
258}
259
260RefreshRate RefreshRateConfigs::getBestRefreshRateLocked(
261 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
262 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800263 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200264 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800265
Ady Abrahamdfd62162020-06-10 16:11:56 -0700266 if (outSignalsConsidered) *outSignalsConsidered = {};
267 const auto setTouchConsidered = [&] {
268 if (outSignalsConsidered) {
269 outSignalsConsidered->touch = true;
270 }
271 };
272
273 const auto setIdleConsidered = [&] {
274 if (outSignalsConsidered) {
275 outSignalsConsidered->idle = true;
276 }
277 };
278
Ady Abraham8a82ba62020-01-17 12:43:17 -0800279 int noVoteLayers = 0;
280 int minVoteLayers = 0;
281 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800282 int explicitDefaultVoteLayers = 0;
283 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800284 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800285 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100286 int seamedFocusedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800287 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800288 switch (layer.vote) {
289 case LayerVoteType::NoVote:
290 noVoteLayers++;
291 break;
292 case LayerVoteType::Min:
293 minVoteLayers++;
294 break;
295 case LayerVoteType::Max:
296 maxVoteLayers++;
297 break;
298 case LayerVoteType::ExplicitDefault:
299 explicitDefaultVoteLayers++;
300 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
301 break;
302 case LayerVoteType::ExplicitExactOrMultiple:
303 explicitExactOrMultipleVoteLayers++;
304 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
305 break;
306 case LayerVoteType::ExplicitExact:
307 explicitExact++;
308 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
309 break;
310 case LayerVoteType::Heuristic:
311 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800312 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200313
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100314 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
315 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200316 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800317 }
318
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800319 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
320 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700321
Steven Thomasf734df42020-04-13 21:09:28 -0700322 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
323 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700324 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700325 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700326 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700327 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800328 }
329
Alec Mouri11232a22020-05-14 18:06:25 -0700330 // If the primary range consists of a single refresh rate then we can only
331 // move out the of range if layers explicitly request a different refresh
332 // rate.
333 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100334 const bool primaryRangeIsSingleRate =
335 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700336
Ady Abrahamdfd62162020-06-10 16:11:56 -0700337 if (!globalSignals.touch && globalSignals.idle &&
338 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700339 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700340 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700341 return getMinRefreshRateByPolicyLocked();
342 }
343
Steven Thomasdebafed2020-05-18 17:30:35 -0700344 if (layers.empty() || noVoteLayers == layers.size()) {
345 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700346 }
347
Ady Abraham8a82ba62020-01-17 12:43:17 -0800348 // Only if all layers want Min we should return Min
349 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700350 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700351 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800352 }
353
Ady Abraham8a82ba62020-01-17 12:43:17 -0800354 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800355 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700356 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800357
Steven Thomasf734df42020-04-13 21:09:28 -0700358 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800359 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800360 }
361
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100362 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
Marin Shalamanov46084422020-10-13 12:33:42 +0200363
Ady Abraham8a82ba62020-01-17 12:43:17 -0800364 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700365 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
366 layerVoteTypeString(layer.vote).c_str(), layer.weight,
367 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800368 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800369 continue;
370 }
371
Ady Abraham71c437d2020-01-31 15:56:57 -0800372 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800373
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800374 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100375 const bool isSeamlessSwitch =
376 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200377
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100378 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100379 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800380 formatLayerInfo(layer, weight).c_str(),
381 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100382 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200383 continue;
384 }
385
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100386 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
387 !layer.focused) {
388 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100389 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800390 formatLayerInfo(layer, weight).c_str(),
391 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100392 mCurrentRefreshRate->toString().c_str());
393 continue;
394 }
395
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100396 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100397 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100398 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100399 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
400 // disappeared.
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100401 const bool isInPolicyForDefault = seamedFocusedLayers > 0
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100402 ? scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup()
403 : scores[i].refreshRate->getModeGroup() == defaultMode->getModeGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100404
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100405 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100406 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800407 scores[i].refreshRate->toString().c_str(),
408 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200409 continue;
410 }
411
Ady Abraham62a0be22020-12-08 16:54:10 -0800412 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
413 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700414 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800415 !(layer.focused &&
416 (layer.vote == LayerVoteType::ExplicitDefault ||
417 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700418 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700419 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700420 continue;
421 }
422
Ady Abraham62a0be22020-12-08 16:54:10 -0800423 const auto layerScore =
424 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
425 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
426 scores[i].refreshRate->getName().c_str(), layerScore);
427 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800428 }
429 }
430
Ady Abraham34702102020-02-10 14:12:05 -0800431 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
432 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
433 // or the lower otherwise.
434 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
435 ? getBestRefreshRate(scores.rbegin(), scores.rend())
436 : getBestRefreshRate(scores.begin(), scores.end());
437
Alec Mouri11232a22020-05-14 18:06:25 -0700438 if (primaryRangeIsSingleRate) {
439 // If we never scored any layers, then choose the rate from the primary
440 // range instead of picking a random score from the app range.
441 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800442 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700443 ALOGV("layers not scored - choose %s",
444 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700445 return getMaxRefreshRateByPolicyLocked();
446 } else {
447 return *bestRefreshRate;
448 }
449 }
450
Steven Thomasf734df42020-04-13 21:09:28 -0700451 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
452 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
453 // vote we should not change it if we get a touch event. Only apply touch boost if it will
454 // actually increase the refresh rate over the normal selection.
455 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700456
Ady Abraham5e4e9832021-06-14 13:40:56 -0700457 const bool touchBoostForExplicitExact = [&] {
458 if (mSupportsFrameRateOverride) {
459 // Enable touch boost if there are other layers besides exact
460 return explicitExact + noVoteLayers != layers.size();
461 } else {
462 // Enable touch boost if there are no exact layers
463 return explicitExact == 0;
464 }
465 }();
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800466 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Ady Abraham6b7ad652021-06-23 17:34:57 -0700467 bestRefreshRate->getFps().lessThanWithMargin(touchRefreshRate.getFps())) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700468 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700469 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700470 return touchRefreshRate;
471 }
472
Ady Abrahamde7156e2020-02-28 17:29:39 -0800473 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800474}
475
Ady Abraham62a0be22020-12-08 16:54:10 -0800476std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
477groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
478 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
479 for (const auto& layer : layers) {
480 auto iter = layersByUid.emplace(layer.ownerUid,
481 std::vector<const RefreshRateConfigs::LayerRequirement*>());
482 auto& layersWithSameUid = iter.first->second;
483 layersWithSameUid.push_back(&layer);
484 }
485
486 // Remove uids that can't have a frame rate override
487 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
488 const auto& layersWithSameUid = iter->second;
489 bool skipUid = false;
490 for (const auto& layer : layersWithSameUid) {
491 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
492 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
493 skipUid = true;
494 break;
495 }
496 }
497 if (skipUid) {
498 iter = layersByUid.erase(iter);
499 } else {
500 ++iter;
501 }
502 }
503
504 return layersByUid;
505}
506
507std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
508 const AllRefreshRatesMapType& refreshRates) {
509 std::vector<RefreshRateScore> scores;
510 scores.reserve(refreshRates.size());
511 for (const auto& [ignored, refreshRate] : refreshRates) {
512 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
513 }
514 std::sort(scores.begin(), scores.end(),
515 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
516 return scores;
517}
518
519RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800520 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800521 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800522 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800523
Ady Abraham64c2fc02020-12-29 12:07:50 -0800524 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800525 std::lock_guard lock(mLock);
526 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
527 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
528 groupLayersByUid(layers);
529 UidToFrameRateOverride frameRateOverrides;
530 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800531 // Layers with ExplicitExactOrMultiple expect touch boost
532 const bool hasExplicitExactOrMultiple =
533 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
534 [](const auto& layer) {
535 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
536 });
537
538 if (touch && hasExplicitExactOrMultiple) {
539 continue;
540 }
541
Ady Abraham62a0be22020-12-08 16:54:10 -0800542 for (auto& score : scores) {
543 score.score = 0;
544 }
545
546 for (const auto& layer : layersWithSameUid) {
547 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
548 continue;
549 }
550
551 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800552 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
553 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800554 for (RefreshRateScore& score : scores) {
555 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
556 /*isSeamlessSwitch*/ true);
557 score.score += layer->weight * layerScore;
558 }
559 }
560
561 // We just care about the refresh rates which are a divider of the
562 // display refresh rate
563 auto iter =
564 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
565 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
566 });
567 scores.erase(iter, scores.end());
568
569 // If we never scored any layers, we don't have a preferred frame rate
570 if (std::all_of(scores.begin(), scores.end(),
571 [](const RefreshRateScore& score) { return score.score == 0; })) {
572 continue;
573 }
574
575 // Now that we scored all the refresh rates we need to pick the one that got the highest
576 // score.
577 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700578 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800579 }
580
581 return frameRateOverrides;
582}
583
Ady Abraham34702102020-02-10 14:12:05 -0800584template <typename Iter>
585const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800586 constexpr auto EPSILON = 0.001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800587 const RefreshRate* bestRefreshRate = begin->refreshRate;
588 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800589 for (auto i = begin; i != end; ++i) {
590 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100591 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800592
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100593 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800594
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800595 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800596 max = score;
597 bestRefreshRate = refreshRate;
598 }
599 }
600
Ady Abraham34702102020-02-10 14:12:05 -0800601 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800602}
603
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100604std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100605 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800606 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100607
608 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
609 : *mCurrentRefreshRate;
610 const auto& min = *mMinSupportedRefreshRate;
611
612 if (current != min) {
613 const auto& refreshRate = timerExpired ? min : current;
614 return refreshRate.getFps();
615 }
616
617 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700618}
619
620const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200621 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100622 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200623 return *refreshRate;
624 }
625 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100626 ALOGE("Can't find min refresh rate by policy with the same mode group"
627 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200628 mCurrentRefreshRate->toString().c_str());
629 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700630 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800631}
632
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100633RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800634 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700635 return getMaxRefreshRateByPolicyLocked();
636}
637
638const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200639 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
640 const auto& refreshRate = (**it);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100641 if (mCurrentRefreshRate->getModeGroup() == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200642 return refreshRate;
643 }
644 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100645 ALOGE("Can't find max refresh rate by policy with the same mode group"
646 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200647 mCurrentRefreshRate->toString().c_str());
648 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700649 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800650}
651
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100652RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800653 std::lock_guard lock(mLock);
654 return *mCurrentRefreshRate;
655}
656
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100657RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800658 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800659 return getCurrentRefreshRateByPolicyLocked();
660}
661
662const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700663 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
664 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800665 return *mCurrentRefreshRate;
666 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100667 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800668}
669
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100670void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800671 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200672
673 // Invalidate the cached invocation to getBestRefreshRate. This forces
674 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
675 lastBestRefreshRateInvocation.reset();
676
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100677 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800678}
679
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100680RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
rnlee3bd610662021-06-23 16:27:57 -0700681 Config config)
682 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700683 initializeIdleTimer();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100684 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100685}
686
Ady Abraham9a2ea342021-09-03 17:32:34 -0700687void RefreshRateConfigs::initializeIdleTimer() {
Ady Abraham6d885932021-09-03 18:05:48 -0700688 if (mConfig.idleTimerTimeoutMs > 0) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700689 const auto getCallback = [this]() -> std::optional<IdleTimerCallbacks::Callbacks> {
690 std::scoped_lock lock(mIdleTimerCallbacksMutex);
691 if (!mIdleTimerCallbacks.has_value()) return {};
Ady Abraham6d885932021-09-03 18:05:48 -0700692 return mConfig.supportKernelIdleTimer ? mIdleTimerCallbacks->kernel
693 : mIdleTimerCallbacks->platform;
Ady Abraham9a2ea342021-09-03 17:32:34 -0700694 };
695
696 mIdleTimer.emplace(
Ady Abraham6d885932021-09-03 18:05:48 -0700697 "IdleTimer", std::chrono::milliseconds(mConfig.idleTimerTimeoutMs),
Ady Abraham9a2ea342021-09-03 17:32:34 -0700698 [getCallback] {
699 if (const auto callback = getCallback()) callback->onReset();
700 },
701 [getCallback] {
702 if (const auto callback = getCallback()) callback->onExpired();
703 });
704 mIdleTimer->start();
705 }
706}
707
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100708void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
709 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100710 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200711
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100712 // The current mode should be supported
713 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
714 return mode->getId() == currentModeId;
715 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700716
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200717 // Invalidate the cached invocation to getBestRefreshRate. This forces
718 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
719 lastBestRefreshRateInvocation.reset();
720
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100721 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100722 for (const auto& mode : modes) {
723 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100724 mRefreshRates.emplace(modeId,
Ady Abraham6b7ad652021-06-23 17:34:57 -0700725 std::make_unique<RefreshRate>(mode, RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100726 if (modeId == currentModeId) {
727 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700728 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800729 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700730
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100731 std::vector<const RefreshRate*> sortedModes;
732 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100733 // Reset the policy because the old one may no longer be valid.
734 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100735 mDisplayManagerPolicy.defaultMode = currentModeId;
736 mMinSupportedRefreshRate = sortedModes.front();
737 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800738
739 mSupportsFrameRateOverride = false;
rnlee3bd610662021-06-23 16:27:57 -0700740 if (mConfig.enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100741 for (const auto& mode1 : sortedModes) {
742 for (const auto& mode2 : sortedModes) {
743 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800744 mSupportsFrameRateOverride = true;
745 break;
746 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800747 }
748 }
749 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800750
Ady Abrahamabc27602020-04-08 17:20:29 -0700751 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800752}
753
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100754bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100755 // defaultMode must be a valid mode, and within the given refresh rate range.
756 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700757 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100758 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700759 return false;
760 }
761 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700762 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100763 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700764 return false;
765 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100766 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
767 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700768}
769
770status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800771 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100772 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100773 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100774 return BAD_VALUE;
775 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200776 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700777 Policy previousPolicy = *getCurrentPolicyLocked();
778 mDisplayManagerPolicy = policy;
779 if (*getCurrentPolicyLocked() == previousPolicy) {
780 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100781 }
Ady Abraham2139f732019-11-13 18:56:40 -0800782 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100783 return NO_ERROR;
784}
785
Steven Thomasd4071902020-03-24 16:02:53 -0700786status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100787 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100788 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700789 return BAD_VALUE;
790 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200791 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700792 Policy previousPolicy = *getCurrentPolicyLocked();
793 mOverridePolicy = policy;
794 if (*getCurrentPolicyLocked() == previousPolicy) {
795 return CURRENT_POLICY_UNCHANGED;
796 }
797 constructAvailableRefreshRates();
798 return NO_ERROR;
799}
800
801const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
802 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
803}
804
805RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
806 std::lock_guard lock(mLock);
807 return *getCurrentPolicyLocked();
808}
809
810RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
811 std::lock_guard lock(mLock);
812 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100813}
814
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100815bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100816 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700817 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700818 if (refreshRate->getModeId() == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100819 return true;
820 }
821 }
822 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800823}
824
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100825void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800826 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
827 std::vector<const RefreshRate*>* outRefreshRates) {
828 outRefreshRates->clear();
829 outRefreshRates->reserve(mRefreshRates.size());
830 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800831 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100832 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Ady Abraham6b7ad652021-06-23 17:34:57 -0700833 refreshRate->getModeId().value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800834 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800835 }
836 }
837
838 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
839 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100840 if (refreshRate1->mode->getVsyncPeriod() !=
841 refreshRate2->mode->getVsyncPeriod()) {
842 return refreshRate1->mode->getVsyncPeriod() >
843 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700844 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100845 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700846 }
Ady Abraham2139f732019-11-13 18:56:40 -0800847 });
848}
849
850void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100851 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700852 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100853 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100854 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700855
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100856 auto filterRefreshRates =
857 [&](Fps min, Fps max, const char* listName,
858 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
859 getSortedRefreshRateListLocked(
860 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
861 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800862
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100863 return mode->getHeight() == defaultMode->getHeight() &&
864 mode->getWidth() == defaultMode->getWidth() &&
865 mode->getDpiX() == defaultMode->getDpiX() &&
866 mode->getDpiY() == defaultMode->getDpiY() &&
867 (policy->allowGroupSwitching ||
868 mode->getGroup() == defaultMode->getGroup()) &&
869 refreshRate.inPolicy(min, max);
870 },
871 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800872
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100873 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
874 "No matching modes for %s range: min=%s max=%s", listName,
875 to_string(min).c_str(), to_string(max).c_str());
876 auto stringifyRefreshRates = [&]() -> std::string {
877 std::string str;
878 for (auto refreshRate : *outRefreshRates) {
879 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
880 }
881 return str;
882 };
883 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
884 };
Steven Thomasf734df42020-04-13 21:09:28 -0700885
886 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
887 &mPrimaryRefreshRates);
888 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
889 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800890}
891
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100892Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
893 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700894 return *mKnownFrameRates.begin();
895 }
896
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100897 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700898 return *std::prev(mKnownFrameRates.end());
899 }
900
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100901 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
902 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700903
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100904 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
905 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700906 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
907}
908
Ana Krulecb9afd792020-06-11 13:16:15 -0700909RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
910 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100911 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700912 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
913 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
TreeHugger Robot758ab612021-06-22 19:17:29 +0000914 const auto& currentPolicy = getCurrentPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700915
916 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
917 // the min allowed refresh rate is higher than the device min, we do not want to enable the
918 // timer.
919 if (deviceMin < minByPolicy) {
920 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
921 }
922 if (minByPolicy == maxByPolicy) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000923 // when min primary range in display manager policy is below device min turn on the timer.
924 if (currentPolicy->primaryRange.min.lessThanWithMargin(deviceMin.getFps())) {
925 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700926 }
927 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
928 }
929 // Turn on the timer in all other cases.
930 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
931}
932
Ady Abraham62a0be22020-12-08 16:54:10 -0800933int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700934 // This calculation needs to be in sync with the java code
935 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Ady Abraham3819b9f2021-08-20 10:11:31 -0700936
937 // The threshold must be smaller than 0.001 in order to differentiate
938 // between the fractional pairs (e.g. 59.94 and 60).
939 constexpr float kThreshold = 0.0009f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800940 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700941 const auto numPeriodsRounded = std::round(numPeriods);
942 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800943 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700944 }
945
Ady Abraham62f216c2020-10-13 19:07:23 -0700946 return static_cast<int>(numPeriodsRounded);
947}
948
Marin Shalamanovba421a82020-11-10 21:49:26 +0100949void RefreshRateConfigs::dump(std::string& result) const {
950 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100951 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100952 mDisplayManagerPolicy.toString().c_str());
953 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
954 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100955 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100956 currentPolicy.toString().c_str());
957 }
958
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100959 auto mode = mCurrentRefreshRate->mode;
960 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100961
962 result.append("Refresh rates:\n");
963 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100964 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +0100965 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
966 }
967
Ady Abraham64c2fc02020-12-29 12:07:50 -0800968 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
969 mSupportsFrameRateOverride ? "yes" : "no");
Ady Abraham6d885932021-09-03 18:05:48 -0700970 base::StringAppendF(&result, "Idle timer: (%s) %s\n",
971 mConfig.supportKernelIdleTimer ? "kernel" : "platform",
Ady Abraham9a2ea342021-09-03 17:32:34 -0700972 mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100973 result.append("\n");
974}
975
Ady Abraham2139f732019-11-13 18:56:40 -0800976} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100977
978// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800979#pragma clang diagnostic pop // ignored "-Wextra"