blob: 4f47ed89124716c0ae67455e54ad4788652e53c7 [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 &&
116 refreshRate.fps.greaterThanOrEqualWithMargin(
117 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
Ady Abraham62a0be22020-12-08 16:54:10 -0800143 // Slightly prefer seamless switches.
144 constexpr float kSeamedSwitchPenalty = 0.95f;
145 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
146
147 // If the layer wants Max, give higher score to the higher refresh rate
148 if (layer.vote == LayerVoteType::Max) {
149 const auto ratio =
150 refreshRate.fps.getValue() / mAppRequestRefreshRates.back()->fps.getValue();
151 // use ratio^2 to get a lower score the more we get further from peak
152 return ratio * ratio;
153 }
154
155 const auto displayPeriod = refreshRate.getVsyncPeriod();
156 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
157 if (layer.vote == LayerVoteType::ExplicitDefault) {
158 // Find the actual rate the layer will render, assuming
159 // that layerPeriod is the minimal time to render a frame
160 auto actualLayerPeriod = displayPeriod;
161 int multiplier = 1;
162 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
163 multiplier++;
164 actualLayerPeriod = displayPeriod * multiplier;
165 }
166 return std::min(1.0f,
167 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
168 }
169
170 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
171 layer.vote == LayerVoteType::Heuristic) {
172 // Calculate how many display vsyncs we need to present a single frame for this
173 // layer
174 const auto [displayFramesQuotient, displayFramesRemainder] =
175 getDisplayFrames(layerPeriod, displayPeriod);
176 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
177 if (displayFramesRemainder == 0) {
178 // Layer desired refresh rate matches the display rate.
179 return 1.0f * seamlessness;
180 }
181
182 if (displayFramesQuotient == 0) {
183 // Layer desired refresh rate is higher than the display rate.
184 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
185 (1.0f / (MAX_FRAMES_TO_FIT + 1));
186 }
187
188 // Layer desired refresh rate is lower than the display rate. Check how well it fits
189 // the cadence.
190 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
191 int iter = 2;
192 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
193 diff = diff - (displayPeriod - diff);
194 iter++;
195 }
196
197 return (1.0f / iter) * seamlessness;
198 }
199
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800200 if (layer.vote == LayerVoteType::ExplicitExact) {
201 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
202 if (mSupportsFrameRateOverride) {
203 // Since we support frame rate override, allow refresh rates which are
204 // multiples of the layer's request, as those apps would be throttled
205 // down to run at the desired refresh rate.
206 return divider > 0;
207 }
208
209 return divider == 1;
210 }
211
Ady Abraham62a0be22020-12-08 16:54:10 -0800212 return 0;
213}
214
215struct RefreshRateScore {
216 const RefreshRate* refreshRate;
217 float score;
218};
219
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100220RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
221 const GlobalSignals& globalSignals,
222 GlobalSignals* outSignalsConsidered) const {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200223 std::lock_guard lock(mLock);
224
225 if (auto cached = getCachedBestRefreshRate(layers, globalSignals, outSignalsConsidered)) {
226 return *cached;
227 }
228
229 GlobalSignals signalsConsidered;
230 RefreshRate result = getBestRefreshRateLocked(layers, globalSignals, &signalsConsidered);
231 lastBestRefreshRateInvocation.emplace(
232 GetBestRefreshRateInvocation{.layerRequirements = layers,
233 .globalSignals = globalSignals,
234 .outSignalsConsidered = signalsConsidered,
235 .resultingBestRefreshRate = result});
236 if (outSignalsConsidered) {
237 *outSignalsConsidered = signalsConsidered;
238 }
239 return result;
240}
241
242std::optional<RefreshRate> RefreshRateConfigs::getCachedBestRefreshRate(
243 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
244 GlobalSignals* outSignalsConsidered) const {
245 const bool sameAsLastCall = lastBestRefreshRateInvocation &&
246 lastBestRefreshRateInvocation->layerRequirements == layers &&
247 lastBestRefreshRateInvocation->globalSignals == globalSignals;
248
249 if (sameAsLastCall) {
250 if (outSignalsConsidered) {
251 *outSignalsConsidered = lastBestRefreshRateInvocation->outSignalsConsidered;
252 }
253 return lastBestRefreshRateInvocation->resultingBestRefreshRate;
254 }
255
256 return {};
257}
258
259RefreshRate RefreshRateConfigs::getBestRefreshRateLocked(
260 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
261 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800262 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200263 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800264
Ady Abrahamdfd62162020-06-10 16:11:56 -0700265 if (outSignalsConsidered) *outSignalsConsidered = {};
266 const auto setTouchConsidered = [&] {
267 if (outSignalsConsidered) {
268 outSignalsConsidered->touch = true;
269 }
270 };
271
272 const auto setIdleConsidered = [&] {
273 if (outSignalsConsidered) {
274 outSignalsConsidered->idle = true;
275 }
276 };
277
Ady Abraham8a82ba62020-01-17 12:43:17 -0800278 int noVoteLayers = 0;
279 int minVoteLayers = 0;
280 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800281 int explicitDefaultVoteLayers = 0;
282 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800283 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800284 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100285 int seamedFocusedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800286 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800287 switch (layer.vote) {
288 case LayerVoteType::NoVote:
289 noVoteLayers++;
290 break;
291 case LayerVoteType::Min:
292 minVoteLayers++;
293 break;
294 case LayerVoteType::Max:
295 maxVoteLayers++;
296 break;
297 case LayerVoteType::ExplicitDefault:
298 explicitDefaultVoteLayers++;
299 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
300 break;
301 case LayerVoteType::ExplicitExactOrMultiple:
302 explicitExactOrMultipleVoteLayers++;
303 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
304 break;
305 case LayerVoteType::ExplicitExact:
306 explicitExact++;
307 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
308 break;
309 case LayerVoteType::Heuristic:
310 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800311 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200312
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100313 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
314 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200315 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800316 }
317
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800318 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
319 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700320
Steven Thomasf734df42020-04-13 21:09:28 -0700321 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
322 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700323 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700324 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700325 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700326 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800327 }
328
Alec Mouri11232a22020-05-14 18:06:25 -0700329 // If the primary range consists of a single refresh rate then we can only
330 // move out the of range if layers explicitly request a different refresh
331 // rate.
332 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100333 const bool primaryRangeIsSingleRate =
334 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700335
Ady Abrahamdfd62162020-06-10 16:11:56 -0700336 if (!globalSignals.touch && globalSignals.idle &&
337 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700338 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700339 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700340 return getMinRefreshRateByPolicyLocked();
341 }
342
Steven Thomasdebafed2020-05-18 17:30:35 -0700343 if (layers.empty() || noVoteLayers == layers.size()) {
344 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700345 }
346
Ady Abraham8a82ba62020-01-17 12:43:17 -0800347 // Only if all layers want Min we should return Min
348 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700349 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700350 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800351 }
352
Ady Abraham8a82ba62020-01-17 12:43:17 -0800353 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800354 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700355 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800356
Steven Thomasf734df42020-04-13 21:09:28 -0700357 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800358 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800359 }
360
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100361 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
Marin Shalamanov46084422020-10-13 12:33:42 +0200362
Ady Abraham8a82ba62020-01-17 12:43:17 -0800363 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700364 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
365 layerVoteTypeString(layer.vote).c_str(), layer.weight,
366 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800367 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800368 continue;
369 }
370
Ady Abraham71c437d2020-01-31 15:56:57 -0800371 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800372
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800373 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100374 const bool isSeamlessSwitch =
375 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200376
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100377 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100378 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800379 formatLayerInfo(layer, weight).c_str(),
380 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100381 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200382 continue;
383 }
384
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100385 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
386 !layer.focused) {
387 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100388 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800389 formatLayerInfo(layer, weight).c_str(),
390 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100391 mCurrentRefreshRate->toString().c_str());
392 continue;
393 }
394
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100395 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100396 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100397 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100398 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
399 // disappeared.
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100400 const bool isInPolicyForDefault = seamedFocusedLayers > 0
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100401 ? scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup()
402 : scores[i].refreshRate->getModeGroup() == defaultMode->getModeGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100403
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100404 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100405 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800406 scores[i].refreshRate->toString().c_str(),
407 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200408 continue;
409 }
410
Ady Abraham62a0be22020-12-08 16:54:10 -0800411 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
412 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700413 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800414 !(layer.focused &&
415 (layer.vote == LayerVoteType::ExplicitDefault ||
416 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700417 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700418 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700419 continue;
420 }
421
Ady Abraham62a0be22020-12-08 16:54:10 -0800422 const auto layerScore =
423 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
424 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
425 scores[i].refreshRate->getName().c_str(), layerScore);
426 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800427 }
428 }
429
Ady Abraham34702102020-02-10 14:12:05 -0800430 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
431 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
432 // or the lower otherwise.
433 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
434 ? getBestRefreshRate(scores.rbegin(), scores.rend())
435 : getBestRefreshRate(scores.begin(), scores.end());
436
Alec Mouri11232a22020-05-14 18:06:25 -0700437 if (primaryRangeIsSingleRate) {
438 // If we never scored any layers, then choose the rate from the primary
439 // range instead of picking a random score from the app range.
440 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800441 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700442 ALOGV("layers not scored - choose %s",
443 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700444 return getMaxRefreshRateByPolicyLocked();
445 } else {
446 return *bestRefreshRate;
447 }
448 }
449
Steven Thomasf734df42020-04-13 21:09:28 -0700450 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
451 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
452 // vote we should not change it if we get a touch event. Only apply touch boost if it will
453 // actually increase the refresh rate over the normal selection.
454 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700455
Ady Abraham5e4e9832021-06-14 13:40:56 -0700456 const bool touchBoostForExplicitExact = [&] {
457 if (mSupportsFrameRateOverride) {
458 // Enable touch boost if there are other layers besides exact
459 return explicitExact + noVoteLayers != layers.size();
460 } else {
461 // Enable touch boost if there are no exact layers
462 return explicitExact == 0;
463 }
464 }();
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800465 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100466 bestRefreshRate->fps.lessThanWithMargin(touchRefreshRate.fps)) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700467 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700468 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700469 return touchRefreshRate;
470 }
471
Ady Abrahamde7156e2020-02-28 17:29:39 -0800472 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800473}
474
Ady Abraham62a0be22020-12-08 16:54:10 -0800475std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
476groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
477 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
478 for (const auto& layer : layers) {
479 auto iter = layersByUid.emplace(layer.ownerUid,
480 std::vector<const RefreshRateConfigs::LayerRequirement*>());
481 auto& layersWithSameUid = iter.first->second;
482 layersWithSameUid.push_back(&layer);
483 }
484
485 // Remove uids that can't have a frame rate override
486 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
487 const auto& layersWithSameUid = iter->second;
488 bool skipUid = false;
489 for (const auto& layer : layersWithSameUid) {
490 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
491 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
492 skipUid = true;
493 break;
494 }
495 }
496 if (skipUid) {
497 iter = layersByUid.erase(iter);
498 } else {
499 ++iter;
500 }
501 }
502
503 return layersByUid;
504}
505
506std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
507 const AllRefreshRatesMapType& refreshRates) {
508 std::vector<RefreshRateScore> scores;
509 scores.reserve(refreshRates.size());
510 for (const auto& [ignored, refreshRate] : refreshRates) {
511 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
512 }
513 std::sort(scores.begin(), scores.end(),
514 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
515 return scores;
516}
517
518RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800519 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800520 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800521 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800522
Ady Abraham64c2fc02020-12-29 12:07:50 -0800523 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800524 std::lock_guard lock(mLock);
525 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
526 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
527 groupLayersByUid(layers);
528 UidToFrameRateOverride frameRateOverrides;
529 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800530 // Layers with ExplicitExactOrMultiple expect touch boost
531 const bool hasExplicitExactOrMultiple =
532 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
533 [](const auto& layer) {
534 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
535 });
536
537 if (touch && hasExplicitExactOrMultiple) {
538 continue;
539 }
540
Ady Abraham62a0be22020-12-08 16:54:10 -0800541 for (auto& score : scores) {
542 score.score = 0;
543 }
544
545 for (const auto& layer : layersWithSameUid) {
546 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
547 continue;
548 }
549
550 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800551 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
552 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800553 for (RefreshRateScore& score : scores) {
554 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
555 /*isSeamlessSwitch*/ true);
556 score.score += layer->weight * layerScore;
557 }
558 }
559
560 // We just care about the refresh rates which are a divider of the
561 // display refresh rate
562 auto iter =
563 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
564 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
565 });
566 scores.erase(iter, scores.end());
567
568 // If we never scored any layers, we don't have a preferred frame rate
569 if (std::all_of(scores.begin(), scores.end(),
570 [](const RefreshRateScore& score) { return score.score == 0; })) {
571 continue;
572 }
573
574 // Now that we scored all the refresh rates we need to pick the one that got the highest
575 // score.
576 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700577 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800578 }
579
580 return frameRateOverrides;
581}
582
Ady Abraham34702102020-02-10 14:12:05 -0800583template <typename Iter>
584const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800585 constexpr auto EPSILON = 0.001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800586 const RefreshRate* bestRefreshRate = begin->refreshRate;
587 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800588 for (auto i = begin; i != end; ++i) {
589 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100590 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800591
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100592 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800593
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800594 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800595 max = score;
596 bestRefreshRate = refreshRate;
597 }
598 }
599
Ady Abraham34702102020-02-10 14:12:05 -0800600 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800601}
602
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100603std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100604 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800605 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100606
607 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
608 : *mCurrentRefreshRate;
609 const auto& min = *mMinSupportedRefreshRate;
610
611 if (current != min) {
612 const auto& refreshRate = timerExpired ? min : current;
613 return refreshRate.getFps();
614 }
615
616 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700617}
618
619const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200620 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100621 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200622 return *refreshRate;
623 }
624 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100625 ALOGE("Can't find min refresh rate by policy with the same mode group"
626 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200627 mCurrentRefreshRate->toString().c_str());
628 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700629 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800630}
631
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100632RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800633 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700634 return getMaxRefreshRateByPolicyLocked();
635}
636
637const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200638 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
639 const auto& refreshRate = (**it);
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 max 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 highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700648 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800649}
650
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100651RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800652 std::lock_guard lock(mLock);
653 return *mCurrentRefreshRate;
654}
655
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100656RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800657 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800658 return getCurrentRefreshRateByPolicyLocked();
659}
660
661const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700662 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
663 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800664 return *mCurrentRefreshRate;
665 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100666 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800667}
668
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100669void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800670 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200671
672 // Invalidate the cached invocation to getBestRefreshRate. This forces
673 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
674 lastBestRefreshRateInvocation.reset();
675
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100676 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800677}
678
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100679RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
rnlee3bd610662021-06-23 16:27:57 -0700680 Config config)
681 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100682 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100683}
684
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100685void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
686 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100687 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200688
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100689 // The current mode should be supported
690 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
691 return mode->getId() == currentModeId;
692 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700693
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200694 // Invalidate the cached invocation to getBestRefreshRate. This forces
695 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
696 lastBestRefreshRateInvocation.reset();
697
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100698 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100699 for (const auto& mode : modes) {
700 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100701 mRefreshRates.emplace(modeId,
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100702 std::make_unique<RefreshRate>(modeId, mode, mode->getFps(),
Ady Abrahamabc27602020-04-08 17:20:29 -0700703 RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100704 if (modeId == currentModeId) {
705 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700706 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800707 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700708
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100709 std::vector<const RefreshRate*> sortedModes;
710 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100711 // Reset the policy because the old one may no longer be valid.
712 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100713 mDisplayManagerPolicy.defaultMode = currentModeId;
714 mMinSupportedRefreshRate = sortedModes.front();
715 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800716
717 mSupportsFrameRateOverride = false;
rnlee3bd610662021-06-23 16:27:57 -0700718 if (mConfig.enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100719 for (const auto& mode1 : sortedModes) {
720 for (const auto& mode2 : sortedModes) {
721 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800722 mSupportsFrameRateOverride = true;
723 break;
724 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800725 }
726 }
727 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800728
Ady Abrahamabc27602020-04-08 17:20:29 -0700729 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800730}
731
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100732bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100733 // defaultMode must be a valid mode, and within the given refresh rate range.
734 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700735 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100736 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700737 return false;
738 }
739 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700740 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100741 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700742 return false;
743 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100744 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
745 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700746}
747
748status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800749 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100750 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100751 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100752 return BAD_VALUE;
753 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200754 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700755 Policy previousPolicy = *getCurrentPolicyLocked();
756 mDisplayManagerPolicy = policy;
757 if (*getCurrentPolicyLocked() == previousPolicy) {
758 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100759 }
Ady Abraham2139f732019-11-13 18:56:40 -0800760 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100761 return NO_ERROR;
762}
763
Steven Thomasd4071902020-03-24 16:02:53 -0700764status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100765 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100766 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700767 return BAD_VALUE;
768 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200769 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700770 Policy previousPolicy = *getCurrentPolicyLocked();
771 mOverridePolicy = policy;
772 if (*getCurrentPolicyLocked() == previousPolicy) {
773 return CURRENT_POLICY_UNCHANGED;
774 }
775 constructAvailableRefreshRates();
776 return NO_ERROR;
777}
778
779const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
780 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
781}
782
783RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
784 std::lock_guard lock(mLock);
785 return *getCurrentPolicyLocked();
786}
787
788RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
789 std::lock_guard lock(mLock);
790 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100791}
792
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100793bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100794 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700795 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100796 if (refreshRate->modeId == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100797 return true;
798 }
799 }
800 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800801}
802
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100803void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800804 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
805 std::vector<const RefreshRate*>* outRefreshRates) {
806 outRefreshRates->clear();
807 outRefreshRates->reserve(mRefreshRates.size());
808 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800809 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100810 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100811 refreshRate->modeId.value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800812 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800813 }
814 }
815
816 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
817 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100818 if (refreshRate1->mode->getVsyncPeriod() !=
819 refreshRate2->mode->getVsyncPeriod()) {
820 return refreshRate1->mode->getVsyncPeriod() >
821 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700822 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100823 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700824 }
Ady Abraham2139f732019-11-13 18:56:40 -0800825 });
826}
827
828void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100829 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700830 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100831 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100832 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700833
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100834 auto filterRefreshRates =
835 [&](Fps min, Fps max, const char* listName,
836 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
837 getSortedRefreshRateListLocked(
838 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
839 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800840
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100841 return mode->getHeight() == defaultMode->getHeight() &&
842 mode->getWidth() == defaultMode->getWidth() &&
843 mode->getDpiX() == defaultMode->getDpiX() &&
844 mode->getDpiY() == defaultMode->getDpiY() &&
845 (policy->allowGroupSwitching ||
846 mode->getGroup() == defaultMode->getGroup()) &&
847 refreshRate.inPolicy(min, max);
848 },
849 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800850
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100851 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
852 "No matching modes for %s range: min=%s max=%s", listName,
853 to_string(min).c_str(), to_string(max).c_str());
854 auto stringifyRefreshRates = [&]() -> std::string {
855 std::string str;
856 for (auto refreshRate : *outRefreshRates) {
857 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
858 }
859 return str;
860 };
861 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
862 };
Steven Thomasf734df42020-04-13 21:09:28 -0700863
864 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
865 &mPrimaryRefreshRates);
866 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
867 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800868}
869
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100870Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
871 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700872 return *mKnownFrameRates.begin();
873 }
874
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100875 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700876 return *std::prev(mKnownFrameRates.end());
877 }
878
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100879 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
880 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700881
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100882 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
883 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700884 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
885}
886
Ana Krulecb9afd792020-06-11 13:16:15 -0700887RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
888 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100889 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700890 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
891 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
892
893 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
894 // the min allowed refresh rate is higher than the device min, we do not want to enable the
895 // timer.
896 if (deviceMin < minByPolicy) {
897 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
898 }
899 if (minByPolicy == maxByPolicy) {
Ana Krulecb9afd792020-06-11 13:16:15 -0700900 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
901 }
902 // Turn on the timer in all other cases.
903 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
904}
905
Ady Abraham62a0be22020-12-08 16:54:10 -0800906int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700907 // This calculation needs to be in sync with the java code
908 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
909 constexpr float kThreshold = 0.1f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800910 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700911 const auto numPeriodsRounded = std::round(numPeriods);
912 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800913 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700914 }
915
Ady Abraham62f216c2020-10-13 19:07:23 -0700916 return static_cast<int>(numPeriodsRounded);
917}
918
Marin Shalamanovba421a82020-11-10 21:49:26 +0100919void RefreshRateConfigs::dump(std::string& result) const {
920 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100921 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100922 mDisplayManagerPolicy.toString().c_str());
923 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
924 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100925 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100926 currentPolicy.toString().c_str());
927 }
928
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100929 auto mode = mCurrentRefreshRate->mode;
930 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100931
932 result.append("Refresh rates:\n");
933 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100934 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +0100935 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
936 }
937
Ady Abraham64c2fc02020-12-29 12:07:50 -0800938 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
939 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100940 result.append("\n");
941}
942
Ady Abraham2139f732019-11-13 18:56:40 -0800943} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100944
945// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800946#pragma clang diagnostic pop // ignored "-Wextra"