blob: b00423e6b71c148d20af30e42b96c9b7e2978720 [file] [log] [blame]
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001/*
2 * Copyright 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Ady Abraham2139f732019-11-13 18:56:40 -080016
Ady Abraham8a82ba62020-01-17 12:43:17 -080017// #define LOG_NDEBUG 0
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020// TODO(b/129481165): remove the #pragma below and fix conversion issues
21#pragma clang diagnostic push
22#pragma clang diagnostic ignored "-Wextra"
23
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080024#include "RefreshRateConfigs.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080025#include <android-base/stringprintf.h>
26#include <utils/Trace.h>
27#include <chrono>
28#include <cmath>
Ady Abraham4899ff82021-01-06 13:53:29 -080029#include "../SurfaceFlingerProperties.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080030
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080031#undef LOG_TAG
32#define LOG_TAG "RefreshRateConfigs"
33
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080034namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010035namespace {
36std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010037 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010038 RefreshRateConfigs::layerVoteTypeString(layer.vote).c_str(), weight,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010039 toString(layer.seamlessness).c_str(),
40 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010041}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010042
Marin Shalamanova7fe3042021-01-29 21:02:08 +010043std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010044 std::vector<Fps> knownFrameRates = {Fps(24.0f), Fps(30.0f), Fps(45.0f), Fps(60.0f), Fps(72.0f)};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010045 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010046
47 // Add all supported refresh rates to the set
Marin Shalamanova7fe3042021-01-29 21:02:08 +010048 for (const auto& mode : modes) {
49 const auto refreshRate = Fps::fromPeriodNsecs(mode->getVsyncPeriod());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010050 knownFrameRates.emplace_back(refreshRate);
51 }
52
53 // Sort and remove duplicates
54 std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
55 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
56 Fps::EqualsWithMargin()),
57 knownFrameRates.end());
58 return knownFrameRates;
59}
60
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010061} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080062
63using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080064using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080065
Marin Shalamanov46084422020-10-13 12:33:42 +020066std::string RefreshRate::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010067 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010068 getModeId().value(), mode->getHwcId(), getFps().getValue(),
69 mode->getWidth(), mode->getHeight(), getModeGroup());
Marin Shalamanov46084422020-10-13 12:33:42 +020070}
71
Ady Abrahama6b676e2020-05-27 14:29:09 -070072std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
73 switch (vote) {
74 case LayerVoteType::NoVote:
75 return "NoVote";
76 case LayerVoteType::Min:
77 return "Min";
78 case LayerVoteType::Max:
79 return "Max";
80 case LayerVoteType::Heuristic:
81 return "Heuristic";
82 case LayerVoteType::ExplicitDefault:
83 return "ExplicitDefault";
84 case LayerVoteType::ExplicitExactOrMultiple:
85 return "ExplicitExactOrMultiple";
Ady Abrahamdd5bfa92021-01-07 17:56:08 -080086 case LayerVoteType::ExplicitExact:
87 return "ExplicitExact";
Ady Abrahama6b676e2020-05-27 14:29:09 -070088 }
89}
90
Marin Shalamanovb6674e72020-11-06 13:05:57 +010091std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010092 return base::StringPrintf("default mode ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010093 ", primary range: %s, app request range: %s",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010094 defaultMode.value(), allowGroupSwitching,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010095 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020096}
97
Ady Abraham4ccdcb42020-02-11 17:34:34 -080098std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
99 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800100 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
101 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
102 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
103 quotient++;
104 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800105 }
106
Ady Abraham62a0be22020-12-08 16:54:10 -0800107 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800108}
109
rnlee3bd610662021-06-23 16:27:57 -0700110bool RefreshRateConfigs::isVoteAllowed(const LayerRequirement& layer,
111 const RefreshRate& refreshRate) const {
112 switch (layer.vote) {
113 case LayerVoteType::ExplicitExactOrMultiple:
114 case LayerVoteType::Heuristic:
115 if (mConfig.frameRateMultipleThreshold != 0 &&
Ady Abraham6b7ad652021-06-23 17:34:57 -0700116 refreshRate.getFps().greaterThanOrEqualWithMargin(
rnlee3bd610662021-06-23 16:27:57 -0700117 Fps(mConfig.frameRateMultipleThreshold)) &&
118 layer.desiredRefreshRate.lessThanWithMargin(
119 Fps(mConfig.frameRateMultipleThreshold / 2))) {
120 // Don't vote high refresh rates past the threshold for layers with a low desired
121 // refresh rate. For example, desired 24 fps with 120 Hz threshold means no vote for
122 // 120 Hz, but desired 60 fps should have a vote.
123 return false;
124 }
125 break;
126 case LayerVoteType::ExplicitDefault:
127 case LayerVoteType::ExplicitExact:
128 case LayerVoteType::Max:
129 case LayerVoteType::Min:
130 case LayerVoteType::NoVote:
131 break;
132 }
133 return true;
134}
135
Ady Abraham62a0be22020-12-08 16:54:10 -0800136float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
137 const RefreshRate& refreshRate,
138 bool isSeamlessSwitch) const {
rnlee3bd610662021-06-23 16:27:57 -0700139 if (!isVoteAllowed(layer, refreshRate)) {
140 return 0;
141 }
142
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200143 constexpr float kScoreForFractionalPairs = .8f;
144
Ady Abraham62a0be22020-12-08 16:54:10 -0800145 // Slightly prefer seamless switches.
146 constexpr float kSeamedSwitchPenalty = 0.95f;
147 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
148
149 // If the layer wants Max, give higher score to the higher refresh rate
150 if (layer.vote == LayerVoteType::Max) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700151 const auto ratio = refreshRate.getFps().getValue() /
152 mAppRequestRefreshRates.back()->getFps().getValue();
Ady Abraham62a0be22020-12-08 16:54:10 -0800153 // use ratio^2 to get a lower score the more we get further from peak
154 return ratio * ratio;
155 }
156
157 const auto displayPeriod = refreshRate.getVsyncPeriod();
158 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
159 if (layer.vote == LayerVoteType::ExplicitDefault) {
160 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200161 // that layerPeriod is the minimal period to render a frame.
162 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
163 // then the actualLayerPeriod will be 32ms, because it is the
164 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800165 auto actualLayerPeriod = displayPeriod;
166 int multiplier = 1;
167 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
168 multiplier++;
169 actualLayerPeriod = displayPeriod * multiplier;
170 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200171
172 // Because of the threshold we used above it's possible that score is slightly
173 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800174 return std::min(1.0f,
175 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
176 }
177
178 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
179 layer.vote == LayerVoteType::Heuristic) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200180 if (isFractionalPairOrMultiple(refreshRate.getFps(), layer.desiredRefreshRate)) {
181 return kScoreForFractionalPairs * seamlessness;
182 }
183
Ady Abraham62a0be22020-12-08 16:54:10 -0800184 // Calculate how many display vsyncs we need to present a single frame for this
185 // layer
186 const auto [displayFramesQuotient, displayFramesRemainder] =
187 getDisplayFrames(layerPeriod, displayPeriod);
188 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
189 if (displayFramesRemainder == 0) {
190 // Layer desired refresh rate matches the display rate.
191 return 1.0f * seamlessness;
192 }
193
194 if (displayFramesQuotient == 0) {
195 // Layer desired refresh rate is higher than the display rate.
196 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
197 (1.0f / (MAX_FRAMES_TO_FIT + 1));
198 }
199
200 // Layer desired refresh rate is lower than the display rate. Check how well it fits
201 // the cadence.
202 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
203 int iter = 2;
204 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
205 diff = diff - (displayPeriod - diff);
206 iter++;
207 }
208
209 return (1.0f / iter) * seamlessness;
210 }
211
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800212 if (layer.vote == LayerVoteType::ExplicitExact) {
213 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
214 if (mSupportsFrameRateOverride) {
215 // Since we support frame rate override, allow refresh rates which are
216 // multiples of the layer's request, as those apps would be throttled
217 // down to run at the desired refresh rate.
218 return divider > 0;
219 }
220
221 return divider == 1;
222 }
223
Ady Abraham62a0be22020-12-08 16:54:10 -0800224 return 0;
225}
226
227struct RefreshRateScore {
228 const RefreshRate* refreshRate;
229 float score;
230};
231
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100232RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
233 const GlobalSignals& globalSignals,
234 GlobalSignals* outSignalsConsidered) const {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200235 std::lock_guard lock(mLock);
236
237 if (auto cached = getCachedBestRefreshRate(layers, globalSignals, outSignalsConsidered)) {
238 return *cached;
239 }
240
241 GlobalSignals signalsConsidered;
242 RefreshRate result = getBestRefreshRateLocked(layers, globalSignals, &signalsConsidered);
243 lastBestRefreshRateInvocation.emplace(
244 GetBestRefreshRateInvocation{.layerRequirements = layers,
245 .globalSignals = globalSignals,
246 .outSignalsConsidered = signalsConsidered,
247 .resultingBestRefreshRate = result});
248 if (outSignalsConsidered) {
249 *outSignalsConsidered = signalsConsidered;
250 }
251 return result;
252}
253
254std::optional<RefreshRate> RefreshRateConfigs::getCachedBestRefreshRate(
255 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
256 GlobalSignals* outSignalsConsidered) const {
257 const bool sameAsLastCall = lastBestRefreshRateInvocation &&
258 lastBestRefreshRateInvocation->layerRequirements == layers &&
259 lastBestRefreshRateInvocation->globalSignals == globalSignals;
260
261 if (sameAsLastCall) {
262 if (outSignalsConsidered) {
263 *outSignalsConsidered = lastBestRefreshRateInvocation->outSignalsConsidered;
264 }
265 return lastBestRefreshRateInvocation->resultingBestRefreshRate;
266 }
267
268 return {};
269}
270
271RefreshRate RefreshRateConfigs::getBestRefreshRateLocked(
272 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
273 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800274 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200275 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800276
Ady Abrahamdfd62162020-06-10 16:11:56 -0700277 if (outSignalsConsidered) *outSignalsConsidered = {};
278 const auto setTouchConsidered = [&] {
279 if (outSignalsConsidered) {
280 outSignalsConsidered->touch = true;
281 }
282 };
283
284 const auto setIdleConsidered = [&] {
285 if (outSignalsConsidered) {
286 outSignalsConsidered->idle = true;
287 }
288 };
289
Ady Abraham8a82ba62020-01-17 12:43:17 -0800290 int noVoteLayers = 0;
291 int minVoteLayers = 0;
292 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800293 int explicitDefaultVoteLayers = 0;
294 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800295 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800296 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100297 int seamedFocusedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800298 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800299 switch (layer.vote) {
300 case LayerVoteType::NoVote:
301 noVoteLayers++;
302 break;
303 case LayerVoteType::Min:
304 minVoteLayers++;
305 break;
306 case LayerVoteType::Max:
307 maxVoteLayers++;
308 break;
309 case LayerVoteType::ExplicitDefault:
310 explicitDefaultVoteLayers++;
311 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
312 break;
313 case LayerVoteType::ExplicitExactOrMultiple:
314 explicitExactOrMultipleVoteLayers++;
315 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
316 break;
317 case LayerVoteType::ExplicitExact:
318 explicitExact++;
319 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
320 break;
321 case LayerVoteType::Heuristic:
322 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800323 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200324
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100325 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
326 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200327 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800328 }
329
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800330 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
331 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700332
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200333 const Policy* policy = getCurrentPolicyLocked();
334 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
335 // If the default mode group is different from the group of current mode,
336 // this means a layer requesting a seamed mode switch just disappeared and
337 // we should switch back to the default group.
338 // However if a seamed layer is still present we anchor around the group
339 // of the current mode, in order to prevent unnecessary seamed mode switches
340 // (e.g. when pausing a video playback).
341 const auto anchorGroup = seamedFocusedLayers > 0 ? mCurrentRefreshRate->getModeGroup()
342 : defaultMode->getModeGroup();
343
Steven Thomasf734df42020-04-13 21:09:28 -0700344 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
345 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700346 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700347 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700348 setTouchConsidered();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200349 return getMaxRefreshRateByPolicyLocked(anchorGroup);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800350 }
351
Alec Mouri11232a22020-05-14 18:06:25 -0700352 // If the primary range consists of a single refresh rate then we can only
353 // move out the of range if layers explicitly request a different refresh
354 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100355 const bool primaryRangeIsSingleRate =
356 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700357
Ady Abrahamdfd62162020-06-10 16:11:56 -0700358 if (!globalSignals.touch && globalSignals.idle &&
359 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700360 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700361 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700362 return getMinRefreshRateByPolicyLocked();
363 }
364
Steven Thomasdebafed2020-05-18 17:30:35 -0700365 if (layers.empty() || noVoteLayers == layers.size()) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200366 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
367 ALOGV("no layers with votes - choose %s", refreshRate.getName().c_str());
368 return refreshRate;
Steven Thomasbb374322020-04-28 22:47:16 -0700369 }
370
Ady Abraham8a82ba62020-01-17 12:43:17 -0800371 // Only if all layers want Min we should return Min
372 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700373 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700374 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800375 }
376
Ady Abraham8a82ba62020-01-17 12:43:17 -0800377 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800378 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700379 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800380
Steven Thomasf734df42020-04-13 21:09:28 -0700381 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800382 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800383 }
384
385 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700386 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
387 layerVoteTypeString(layer.vote).c_str(), layer.weight,
388 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800389 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800390 continue;
391 }
392
Ady Abraham71c437d2020-01-31 15:56:57 -0800393 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800394
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800395 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100396 const bool isSeamlessSwitch =
397 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200398
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100399 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100400 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800401 formatLayerInfo(layer, weight).c_str(),
402 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100403 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200404 continue;
405 }
406
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100407 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
408 !layer.focused) {
409 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100410 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800411 formatLayerInfo(layer, weight).c_str(),
412 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100413 mCurrentRefreshRate->toString().c_str());
414 continue;
415 }
416
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100417 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100418 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100419 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100420 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
421 // disappeared.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200422 const bool isInPolicyForDefault = scores[i].refreshRate->getModeGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100423 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100424 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800425 scores[i].refreshRate->toString().c_str(),
426 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200427 continue;
428 }
429
Ady Abraham62a0be22020-12-08 16:54:10 -0800430 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
431 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700432 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800433 !(layer.focused &&
434 (layer.vote == LayerVoteType::ExplicitDefault ||
435 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700436 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700437 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700438 continue;
439 }
440
Ady Abraham62a0be22020-12-08 16:54:10 -0800441 const auto layerScore =
442 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200443 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800444 scores[i].refreshRate->getName().c_str(), layerScore);
445 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800446 }
447 }
448
Ady Abraham34702102020-02-10 14:12:05 -0800449 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
450 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
451 // or the lower otherwise.
452 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
453 ? getBestRefreshRate(scores.rbegin(), scores.rend())
454 : getBestRefreshRate(scores.begin(), scores.end());
455
Alec Mouri11232a22020-05-14 18:06:25 -0700456 if (primaryRangeIsSingleRate) {
457 // If we never scored any layers, then choose the rate from the primary
458 // range instead of picking a random score from the app range.
459 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800460 [](RefreshRateScore score) { return score.score == 0; })) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200461 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
462 ALOGV("layers not scored - choose %s", refreshRate.getName().c_str());
463 return refreshRate;
Alec Mouri11232a22020-05-14 18:06:25 -0700464 } else {
465 return *bestRefreshRate;
466 }
467 }
468
Steven Thomasf734df42020-04-13 21:09:28 -0700469 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
470 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
471 // vote we should not change it if we get a touch event. Only apply touch boost if it will
472 // actually increase the refresh rate over the normal selection.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200473 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
Alec Mouri11232a22020-05-14 18:06:25 -0700474
Ady Abraham5e4e9832021-06-14 13:40:56 -0700475 const bool touchBoostForExplicitExact = [&] {
476 if (mSupportsFrameRateOverride) {
477 // Enable touch boost if there are other layers besides exact
478 return explicitExact + noVoteLayers != layers.size();
479 } else {
480 // Enable touch boost if there are no exact layers
481 return explicitExact == 0;
482 }
483 }();
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800484 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Ady Abraham6b7ad652021-06-23 17:34:57 -0700485 bestRefreshRate->getFps().lessThanWithMargin(touchRefreshRate.getFps())) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700486 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700487 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700488 return touchRefreshRate;
489 }
490
Ady Abrahamde7156e2020-02-28 17:29:39 -0800491 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800492}
493
Ady Abraham62a0be22020-12-08 16:54:10 -0800494std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
495groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
496 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
497 for (const auto& layer : layers) {
498 auto iter = layersByUid.emplace(layer.ownerUid,
499 std::vector<const RefreshRateConfigs::LayerRequirement*>());
500 auto& layersWithSameUid = iter.first->second;
501 layersWithSameUid.push_back(&layer);
502 }
503
504 // Remove uids that can't have a frame rate override
505 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
506 const auto& layersWithSameUid = iter->second;
507 bool skipUid = false;
508 for (const auto& layer : layersWithSameUid) {
509 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
510 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
511 skipUid = true;
512 break;
513 }
514 }
515 if (skipUid) {
516 iter = layersByUid.erase(iter);
517 } else {
518 ++iter;
519 }
520 }
521
522 return layersByUid;
523}
524
525std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
526 const AllRefreshRatesMapType& refreshRates) {
527 std::vector<RefreshRateScore> scores;
528 scores.reserve(refreshRates.size());
529 for (const auto& [ignored, refreshRate] : refreshRates) {
530 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
531 }
532 std::sort(scores.begin(), scores.end(),
533 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
534 return scores;
535}
536
537RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800538 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800539 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800540 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800541
Ady Abraham64c2fc02020-12-29 12:07:50 -0800542 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800543 std::lock_guard lock(mLock);
544 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
545 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
546 groupLayersByUid(layers);
547 UidToFrameRateOverride frameRateOverrides;
548 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800549 // Layers with ExplicitExactOrMultiple expect touch boost
550 const bool hasExplicitExactOrMultiple =
551 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
552 [](const auto& layer) {
553 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
554 });
555
556 if (touch && hasExplicitExactOrMultiple) {
557 continue;
558 }
559
Ady Abraham62a0be22020-12-08 16:54:10 -0800560 for (auto& score : scores) {
561 score.score = 0;
562 }
563
564 for (const auto& layer : layersWithSameUid) {
565 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
566 continue;
567 }
568
569 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800570 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
571 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800572 for (RefreshRateScore& score : scores) {
573 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
574 /*isSeamlessSwitch*/ true);
575 score.score += layer->weight * layerScore;
576 }
577 }
578
579 // We just care about the refresh rates which are a divider of the
580 // display refresh rate
581 auto iter =
582 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
583 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
584 });
585 scores.erase(iter, scores.end());
586
587 // If we never scored any layers, we don't have a preferred frame rate
588 if (std::all_of(scores.begin(), scores.end(),
589 [](const RefreshRateScore& score) { return score.score == 0; })) {
590 continue;
591 }
592
593 // Now that we scored all the refresh rates we need to pick the one that got the highest
594 // score.
595 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700596 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800597 }
598
599 return frameRateOverrides;
600}
601
Ady Abraham34702102020-02-10 14:12:05 -0800602template <typename Iter>
603const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200604 constexpr auto kEpsilon = 0.0001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800605 const RefreshRate* bestRefreshRate = begin->refreshRate;
606 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800607 for (auto i = begin; i != end; ++i) {
608 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100609 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800610
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100611 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800612
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200613 if (score > max * (1 + kEpsilon)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800614 max = score;
615 bestRefreshRate = refreshRate;
616 }
617 }
618
Ady Abraham34702102020-02-10 14:12:05 -0800619 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800620}
621
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100622std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100623 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800624 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100625
626 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
627 : *mCurrentRefreshRate;
628 const auto& min = *mMinSupportedRefreshRate;
629
630 if (current != min) {
631 const auto& refreshRate = timerExpired ? min : current;
632 return refreshRate.getFps();
633 }
634
635 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700636}
637
638const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200639 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100640 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200641 return *refreshRate;
642 }
643 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100644 ALOGE("Can't find min refresh rate by policy with the same mode group"
645 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200646 mCurrentRefreshRate->toString().c_str());
647 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700648 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800649}
650
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100651RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800652 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700653 return getMaxRefreshRateByPolicyLocked();
654}
655
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200656const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200657 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
658 const auto& refreshRate = (**it);
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200659 if (anchorGroup == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200660 return refreshRate;
661 }
662 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100663 ALOGE("Can't find max refresh rate by policy with the same mode group"
664 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200665 mCurrentRefreshRate->toString().c_str());
666 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700667 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800668}
669
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100670RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800671 std::lock_guard lock(mLock);
672 return *mCurrentRefreshRate;
673}
674
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100675RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800676 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800677 return getCurrentRefreshRateByPolicyLocked();
678}
679
680const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700681 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
682 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800683 return *mCurrentRefreshRate;
684 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100685 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800686}
687
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100688void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800689 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200690
691 // Invalidate the cached invocation to getBestRefreshRate. This forces
692 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
693 lastBestRefreshRateInvocation.reset();
694
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100695 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800696}
697
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100698RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
rnlee3bd610662021-06-23 16:27:57 -0700699 Config config)
700 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100701 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100702}
703
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100704void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
705 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100706 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200707
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100708 // The current mode should be supported
709 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
710 return mode->getId() == currentModeId;
711 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700712
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200713 // Invalidate the cached invocation to getBestRefreshRate. This forces
714 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
715 lastBestRefreshRateInvocation.reset();
716
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100717 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100718 for (const auto& mode : modes) {
719 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100720 mRefreshRates.emplace(modeId,
Ady Abraham6b7ad652021-06-23 17:34:57 -0700721 std::make_unique<RefreshRate>(mode, RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100722 if (modeId == currentModeId) {
723 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700724 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800725 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700726
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100727 std::vector<const RefreshRate*> sortedModes;
728 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100729 // Reset the policy because the old one may no longer be valid.
730 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100731 mDisplayManagerPolicy.defaultMode = currentModeId;
732 mMinSupportedRefreshRate = sortedModes.front();
733 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800734
735 mSupportsFrameRateOverride = false;
rnlee3bd610662021-06-23 16:27:57 -0700736 if (mConfig.enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100737 for (const auto& mode1 : sortedModes) {
738 for (const auto& mode2 : sortedModes) {
739 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800740 mSupportsFrameRateOverride = true;
741 break;
742 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800743 }
744 }
745 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800746
Ady Abrahamabc27602020-04-08 17:20:29 -0700747 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800748}
749
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100750bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100751 // defaultMode must be a valid mode, and within the given refresh rate range.
752 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700753 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100754 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700755 return false;
756 }
757 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700758 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100759 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700760 return false;
761 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100762 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
763 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700764}
765
766status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800767 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100768 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100769 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100770 return BAD_VALUE;
771 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200772 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700773 Policy previousPolicy = *getCurrentPolicyLocked();
774 mDisplayManagerPolicy = policy;
775 if (*getCurrentPolicyLocked() == previousPolicy) {
776 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100777 }
Ady Abraham2139f732019-11-13 18:56:40 -0800778 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100779 return NO_ERROR;
780}
781
Steven Thomasd4071902020-03-24 16:02:53 -0700782status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100783 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100784 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700785 return BAD_VALUE;
786 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200787 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700788 Policy previousPolicy = *getCurrentPolicyLocked();
789 mOverridePolicy = policy;
790 if (*getCurrentPolicyLocked() == previousPolicy) {
791 return CURRENT_POLICY_UNCHANGED;
792 }
793 constructAvailableRefreshRates();
794 return NO_ERROR;
795}
796
797const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
798 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
799}
800
801RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
802 std::lock_guard lock(mLock);
803 return *getCurrentPolicyLocked();
804}
805
806RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
807 std::lock_guard lock(mLock);
808 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100809}
810
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100811bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100812 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700813 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700814 if (refreshRate->getModeId() == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100815 return true;
816 }
817 }
818 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800819}
820
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100821void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800822 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
823 std::vector<const RefreshRate*>* outRefreshRates) {
824 outRefreshRates->clear();
825 outRefreshRates->reserve(mRefreshRates.size());
826 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800827 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100828 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Ady Abraham6b7ad652021-06-23 17:34:57 -0700829 refreshRate->getModeId().value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800830 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800831 }
832 }
833
834 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
835 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100836 if (refreshRate1->mode->getVsyncPeriod() !=
837 refreshRate2->mode->getVsyncPeriod()) {
838 return refreshRate1->mode->getVsyncPeriod() >
839 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700840 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100841 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700842 }
Ady Abraham2139f732019-11-13 18:56:40 -0800843 });
844}
845
846void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100847 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700848 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100849 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100850 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700851
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100852 auto filterRefreshRates =
853 [&](Fps min, Fps max, const char* listName,
854 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
855 getSortedRefreshRateListLocked(
856 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
857 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800858
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100859 return mode->getHeight() == defaultMode->getHeight() &&
860 mode->getWidth() == defaultMode->getWidth() &&
861 mode->getDpiX() == defaultMode->getDpiX() &&
862 mode->getDpiY() == defaultMode->getDpiY() &&
863 (policy->allowGroupSwitching ||
864 mode->getGroup() == defaultMode->getGroup()) &&
865 refreshRate.inPolicy(min, max);
866 },
867 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800868
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100869 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
870 "No matching modes for %s range: min=%s max=%s", listName,
871 to_string(min).c_str(), to_string(max).c_str());
872 auto stringifyRefreshRates = [&]() -> std::string {
873 std::string str;
874 for (auto refreshRate : *outRefreshRates) {
875 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
876 }
877 return str;
878 };
879 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
880 };
Steven Thomasf734df42020-04-13 21:09:28 -0700881
882 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
883 &mPrimaryRefreshRates);
884 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
885 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800886}
887
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100888Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
889 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700890 return *mKnownFrameRates.begin();
891 }
892
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100893 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700894 return *std::prev(mKnownFrameRates.end());
895 }
896
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100897 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
898 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700899
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100900 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
901 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700902 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
903}
904
Ana Krulecb9afd792020-06-11 13:16:15 -0700905RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
906 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100907 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700908 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
909 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
TreeHugger Robot758ab612021-06-22 19:17:29 +0000910 const auto& currentPolicy = getCurrentPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700911
912 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
913 // the min allowed refresh rate is higher than the device min, we do not want to enable the
914 // timer.
915 if (deviceMin < minByPolicy) {
916 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
917 }
918 if (minByPolicy == maxByPolicy) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000919 // when min primary range in display manager policy is below device min turn on the timer.
920 if (currentPolicy->primaryRange.min.lessThanWithMargin(deviceMin.getFps())) {
921 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700922 }
923 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
924 }
925 // Turn on the timer in all other cases.
926 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
927}
928
Ady Abraham62a0be22020-12-08 16:54:10 -0800929int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700930 // This calculation needs to be in sync with the java code
931 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200932
933 // The threshold must be smaller than 0.001 in order to differentiate
934 // between the fractional pairs (e.g. 59.94 and 60).
935 constexpr float kThreshold = 0.0009f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800936 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700937 const auto numPeriodsRounded = std::round(numPeriods);
938 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800939 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700940 }
941
Ady Abraham62f216c2020-10-13 19:07:23 -0700942 return static_cast<int>(numPeriodsRounded);
943}
944
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200945bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
946 if (smaller.getValue() > bigger.getValue()) {
947 return isFractionalPairOrMultiple(bigger, smaller);
948 }
949
950 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
951 constexpr float kCoef = 1000.f / 1001.f;
952 return bigger.equalsWithMargin(Fps(smaller.getValue() * multiplier / kCoef)) ||
953 bigger.equalsWithMargin(Fps(smaller.getValue() * multiplier * kCoef));
954}
955
Marin Shalamanovba421a82020-11-10 21:49:26 +0100956void RefreshRateConfigs::dump(std::string& result) const {
957 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100958 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100959 mDisplayManagerPolicy.toString().c_str());
960 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
961 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100962 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100963 currentPolicy.toString().c_str());
964 }
965
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100966 auto mode = mCurrentRefreshRate->mode;
967 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100968
969 result.append("Refresh rates:\n");
970 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100971 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +0100972 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
973 }
974
Ady Abraham64c2fc02020-12-29 12:07:50 -0800975 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
976 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100977 result.append("\n");
978}
979
Ady Abraham2139f732019-11-13 18:56:40 -0800980} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100981
982// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800983#pragma clang diagnostic pop // ignored "-Wextra"