blob: eaec789257634f0fd16edca43cfc6da935c4a3ce [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 Abraham8a82ba62020-01-17 12:43:17 -080024#include <chrono>
25#include <cmath>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070026
27#include <android-base/properties.h>
28#include <android-base/stringprintf.h>
29#include <ftl/enum.h>
30#include <utils/Trace.h>
31
Ady Abraham4899ff82021-01-06 13:53:29 -080032#include "../SurfaceFlingerProperties.h"
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070033#include "RefreshRateConfigs.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080034
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080035#undef LOG_TAG
36#define LOG_TAG "RefreshRateConfigs"
37
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080038namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010039namespace {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070040
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010041std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010042 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070043 ftl::enum_string(layer.vote).c_str(), weight,
44 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010045 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010046}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010047
Marin Shalamanova7fe3042021-01-29 21:02:08 +010048std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070049 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010050 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010051
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070052 // Add all supported refresh rates.
Marin Shalamanova7fe3042021-01-29 21:02:08 +010053 for (const auto& mode : modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070054 knownFrameRates.push_back(Fps::fromPeriodNsecs(mode->getVsyncPeriod()));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010055 }
56
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070057 // Sort and remove duplicates.
58 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010059 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070060 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010061 knownFrameRates.end());
62 return knownFrameRates;
63}
64
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010065} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080066
67using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080068using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080069
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070070bool RefreshRate::inPolicy(Fps minRefreshRate, Fps maxRefreshRate) const {
71 using fps_approx_ops::operator<=;
72 return minRefreshRate <= getFps() && getFps() <= maxRefreshRate;
73}
74
Marin Shalamanov46084422020-10-13 12:33:42 +020075std::string RefreshRate::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010076 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010077 getModeId().value(), mode->getHwcId(), getFps().getValue(),
78 mode->getWidth(), mode->getHeight(), getModeGroup());
Marin Shalamanov46084422020-10-13 12:33:42 +020079}
80
Marin Shalamanovb6674e72020-11-06 13:05:57 +010081std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010082 return base::StringPrintf("default mode ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010083 ", primary range: %s, app request range: %s",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010084 defaultMode.value(), allowGroupSwitching,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010085 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020086}
87
Ady Abraham4ccdcb42020-02-11 17:34:34 -080088std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
89 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -080090 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
91 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
92 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
93 quotient++;
94 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -080095 }
96
Ady Abraham62a0be22020-12-08 16:54:10 -080097 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -080098}
99
rnlee3bd610662021-06-23 16:27:57 -0700100bool RefreshRateConfigs::isVoteAllowed(const LayerRequirement& layer,
101 const RefreshRate& refreshRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700102 using namespace fps_approx_ops;
103
rnlee3bd610662021-06-23 16:27:57 -0700104 switch (layer.vote) {
105 case LayerVoteType::ExplicitExactOrMultiple:
106 case LayerVoteType::Heuristic:
107 if (mConfig.frameRateMultipleThreshold != 0 &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700108 refreshRate.getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold) &&
109 layer.desiredRefreshRate < Fps::fromValue(mConfig.frameRateMultipleThreshold / 2)) {
rnlee3bd610662021-06-23 16:27:57 -0700110 // Don't vote high refresh rates past the threshold for layers with a low desired
111 // refresh rate. For example, desired 24 fps with 120 Hz threshold means no vote for
112 // 120 Hz, but desired 60 fps should have a vote.
113 return false;
114 }
115 break;
116 case LayerVoteType::ExplicitDefault:
117 case LayerVoteType::ExplicitExact:
118 case LayerVoteType::Max:
119 case LayerVoteType::Min:
120 case LayerVoteType::NoVote:
121 break;
122 }
123 return true;
124}
125
Ady Abraham05243be2021-09-16 15:58:52 -0700126float RefreshRateConfigs::calculateNonExactMatchingLayerScoreLocked(
127 const LayerRequirement& layer, const RefreshRate& refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200128 constexpr float kScoreForFractionalPairs = .8f;
129
Ady Abraham62a0be22020-12-08 16:54:10 -0800130 const auto displayPeriod = refreshRate.getVsyncPeriod();
131 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
132 if (layer.vote == LayerVoteType::ExplicitDefault) {
133 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200134 // that layerPeriod is the minimal period to render a frame.
135 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
136 // then the actualLayerPeriod will be 32ms, because it is the
137 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800138 auto actualLayerPeriod = displayPeriod;
139 int multiplier = 1;
140 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
141 multiplier++;
142 actualLayerPeriod = displayPeriod * multiplier;
143 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200144
145 // Because of the threshold we used above it's possible that score is slightly
146 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800147 return std::min(1.0f,
148 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
149 }
150
151 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
152 layer.vote == LayerVoteType::Heuristic) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200153 if (isFractionalPairOrMultiple(refreshRate.getFps(), layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700154 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200155 }
156
Ady Abraham62a0be22020-12-08 16:54:10 -0800157 // Calculate how many display vsyncs we need to present a single frame for this
158 // layer
159 const auto [displayFramesQuotient, displayFramesRemainder] =
160 getDisplayFrames(layerPeriod, displayPeriod);
161 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
162 if (displayFramesRemainder == 0) {
163 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700164 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800165 }
166
167 if (displayFramesQuotient == 0) {
168 // Layer desired refresh rate is higher than the display rate.
169 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
170 (1.0f / (MAX_FRAMES_TO_FIT + 1));
171 }
172
173 // Layer desired refresh rate is lower than the display rate. Check how well it fits
174 // the cadence.
175 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
176 int iter = 2;
177 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
178 diff = diff - (displayPeriod - diff);
179 iter++;
180 }
181
Ady Abraham05243be2021-09-16 15:58:52 -0700182 return (1.0f / iter);
183 }
184
185 return 0;
186}
187
188float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
189 const RefreshRate& refreshRate,
190 bool isSeamlessSwitch) const {
191 if (!isVoteAllowed(layer, refreshRate)) {
192 return 0;
193 }
194
195 // Slightly prefer seamless switches.
196 constexpr float kSeamedSwitchPenalty = 0.95f;
197 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
198
199 // If the layer wants Max, give higher score to the higher refresh rate
200 if (layer.vote == LayerVoteType::Max) {
201 const auto ratio = refreshRate.getFps().getValue() /
202 mAppRequestRefreshRates.back()->getFps().getValue();
203 // use ratio^2 to get a lower score the more we get further from peak
204 return ratio * ratio;
Ady Abraham62a0be22020-12-08 16:54:10 -0800205 }
206
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800207 if (layer.vote == LayerVoteType::ExplicitExact) {
208 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800209 if (mSupportsFrameRateOverrideByContent) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800210 // Since we support frame rate override, allow refresh rates which are
211 // multiples of the layer's request, as those apps would be throttled
212 // down to run at the desired refresh rate.
213 return divider > 0;
214 }
215
216 return divider == 1;
217 }
218
Ady Abraham05243be2021-09-16 15:58:52 -0700219 // If the layer frame rate is a divider of the refresh rate it should score
220 // the highest score.
221 if (getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate) > 0) {
222 return 1.0f * seamlessness;
223 }
224
225 // The layer frame rate is not a divider of the refresh rate,
226 // there is a small penalty attached to the score to favor the frame rates
227 // the exactly matches the display refresh rate or a multiple.
228 constexpr float kNonExactMatchingPenalty = 0.99f;
229 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
230 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800231}
232
233struct RefreshRateScore {
234 const RefreshRate* refreshRate;
235 float score;
236};
237
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100238RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700239 GlobalSignals globalSignals,
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100240 GlobalSignals* outSignalsConsidered) const {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200241 std::lock_guard lock(mLock);
242
243 if (auto cached = getCachedBestRefreshRate(layers, globalSignals, outSignalsConsidered)) {
244 return *cached;
245 }
246
247 GlobalSignals signalsConsidered;
248 RefreshRate result = getBestRefreshRateLocked(layers, globalSignals, &signalsConsidered);
249 lastBestRefreshRateInvocation.emplace(
250 GetBestRefreshRateInvocation{.layerRequirements = layers,
251 .globalSignals = globalSignals,
252 .outSignalsConsidered = signalsConsidered,
253 .resultingBestRefreshRate = result});
254 if (outSignalsConsidered) {
255 *outSignalsConsidered = signalsConsidered;
256 }
257 return result;
258}
259
260std::optional<RefreshRate> RefreshRateConfigs::getCachedBestRefreshRate(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700261 const std::vector<LayerRequirement>& layers, GlobalSignals globalSignals,
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200262 GlobalSignals* outSignalsConsidered) const {
263 const bool sameAsLastCall = lastBestRefreshRateInvocation &&
264 lastBestRefreshRateInvocation->layerRequirements == layers &&
265 lastBestRefreshRateInvocation->globalSignals == globalSignals;
266
267 if (sameAsLastCall) {
268 if (outSignalsConsidered) {
269 *outSignalsConsidered = lastBestRefreshRateInvocation->outSignalsConsidered;
270 }
271 return lastBestRefreshRateInvocation->resultingBestRefreshRate;
272 }
273
274 return {};
275}
276
277RefreshRate RefreshRateConfigs::getBestRefreshRateLocked(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700278 const std::vector<LayerRequirement>& layers, GlobalSignals globalSignals,
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200279 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800280 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200281 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800282
Ady Abrahamdfd62162020-06-10 16:11:56 -0700283 if (outSignalsConsidered) *outSignalsConsidered = {};
284 const auto setTouchConsidered = [&] {
285 if (outSignalsConsidered) {
286 outSignalsConsidered->touch = true;
287 }
288 };
289
290 const auto setIdleConsidered = [&] {
291 if (outSignalsConsidered) {
292 outSignalsConsidered->idle = true;
293 }
294 };
295
Ady Abraham8a82ba62020-01-17 12:43:17 -0800296 int noVoteLayers = 0;
297 int minVoteLayers = 0;
298 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800299 int explicitDefaultVoteLayers = 0;
300 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800301 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800302 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100303 int seamedFocusedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800304 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800305 switch (layer.vote) {
306 case LayerVoteType::NoVote:
307 noVoteLayers++;
308 break;
309 case LayerVoteType::Min:
310 minVoteLayers++;
311 break;
312 case LayerVoteType::Max:
313 maxVoteLayers++;
314 break;
315 case LayerVoteType::ExplicitDefault:
316 explicitDefaultVoteLayers++;
317 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
318 break;
319 case LayerVoteType::ExplicitExactOrMultiple:
320 explicitExactOrMultipleVoteLayers++;
321 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
322 break;
323 case LayerVoteType::ExplicitExact:
324 explicitExact++;
325 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
326 break;
327 case LayerVoteType::Heuristic:
328 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800329 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200330
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100331 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
332 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200333 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800334 }
335
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800336 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
337 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700338
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200339 const Policy* policy = getCurrentPolicyLocked();
340 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
341 // If the default mode group is different from the group of current mode,
342 // this means a layer requesting a seamed mode switch just disappeared and
343 // we should switch back to the default group.
344 // However if a seamed layer is still present we anchor around the group
345 // of the current mode, in order to prevent unnecessary seamed mode switches
346 // (e.g. when pausing a video playback).
347 const auto anchorGroup = seamedFocusedLayers > 0 ? mCurrentRefreshRate->getModeGroup()
348 : defaultMode->getModeGroup();
349
Steven Thomasf734df42020-04-13 21:09:28 -0700350 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
351 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700352 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700353 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700354 setTouchConsidered();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200355 return getMaxRefreshRateByPolicyLocked(anchorGroup);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800356 }
357
Alec Mouri11232a22020-05-14 18:06:25 -0700358 // If the primary range consists of a single refresh rate then we can only
359 // move out the of range if layers explicitly request a different refresh
360 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100361 const bool primaryRangeIsSingleRate =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700362 isApproxEqual(policy->primaryRange.min, policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700363
Ady Abrahamdfd62162020-06-10 16:11:56 -0700364 if (!globalSignals.touch && globalSignals.idle &&
365 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700366 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700367 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700368 return getMinRefreshRateByPolicyLocked();
369 }
370
Steven Thomasdebafed2020-05-18 17:30:35 -0700371 if (layers.empty() || noVoteLayers == layers.size()) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200372 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
373 ALOGV("no layers with votes - choose %s", refreshRate.getName().c_str());
374 return refreshRate;
Steven Thomasbb374322020-04-28 22:47:16 -0700375 }
376
Ady Abraham8a82ba62020-01-17 12:43:17 -0800377 // Only if all layers want Min we should return Min
378 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700379 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700380 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800381 }
382
Ady Abraham8a82ba62020-01-17 12:43:17 -0800383 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800384 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700385 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800386
Steven Thomasf734df42020-04-13 21:09:28 -0700387 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800388 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800389 }
390
391 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700392 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700393 ftl::enum_string(layer.vote).c_str(), layer.weight,
rnlee3bd610662021-06-23 16:27:57 -0700394 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800395 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800396 continue;
397 }
398
Ady Abraham71c437d2020-01-31 15:56:57 -0800399 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800400
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800401 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100402 const bool isSeamlessSwitch =
403 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200404
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100405 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100406 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800407 formatLayerInfo(layer, weight).c_str(),
408 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100409 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200410 continue;
411 }
412
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100413 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
414 !layer.focused) {
415 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100416 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800417 formatLayerInfo(layer, weight).c_str(),
418 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100419 mCurrentRefreshRate->toString().c_str());
420 continue;
421 }
422
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100423 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100424 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100425 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100426 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
427 // disappeared.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200428 const bool isInPolicyForDefault = scores[i].refreshRate->getModeGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100429 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100430 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800431 scores[i].refreshRate->toString().c_str(),
432 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200433 continue;
434 }
435
Ady Abraham62a0be22020-12-08 16:54:10 -0800436 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
437 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700438 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800439 !(layer.focused &&
440 (layer.vote == LayerVoteType::ExplicitDefault ||
441 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700442 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700443 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700444 continue;
445 }
446
Ady Abraham62a0be22020-12-08 16:54:10 -0800447 const auto layerScore =
448 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200449 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800450 scores[i].refreshRate->getName().c_str(), layerScore);
451 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800452 }
453 }
454
Ady Abraham34702102020-02-10 14:12:05 -0800455 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
456 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
457 // or the lower otherwise.
458 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
459 ? getBestRefreshRate(scores.rbegin(), scores.rend())
460 : getBestRefreshRate(scores.begin(), scores.end());
461
Alec Mouri11232a22020-05-14 18:06:25 -0700462 if (primaryRangeIsSingleRate) {
463 // If we never scored any layers, then choose the rate from the primary
464 // range instead of picking a random score from the app range.
465 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800466 [](RefreshRateScore score) { return score.score == 0; })) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200467 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
468 ALOGV("layers not scored - choose %s", refreshRate.getName().c_str());
469 return refreshRate;
Alec Mouri11232a22020-05-14 18:06:25 -0700470 } else {
471 return *bestRefreshRate;
472 }
473 }
474
Steven Thomasf734df42020-04-13 21:09:28 -0700475 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
476 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
477 // vote we should not change it if we get a touch event. Only apply touch boost if it will
478 // actually increase the refresh rate over the normal selection.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200479 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
Alec Mouri11232a22020-05-14 18:06:25 -0700480
Ady Abraham5e4e9832021-06-14 13:40:56 -0700481 const bool touchBoostForExplicitExact = [&] {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800482 if (mSupportsFrameRateOverrideByContent) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700483 // Enable touch boost if there are other layers besides exact
484 return explicitExact + noVoteLayers != layers.size();
485 } else {
486 // Enable touch boost if there are no exact layers
487 return explicitExact == 0;
488 }
489 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700490
491 using fps_approx_ops::operator<;
492
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800493 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700494 bestRefreshRate->getFps() < touchRefreshRate.getFps()) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700495 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700496 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700497 return touchRefreshRate;
498 }
499
Ady Abrahamde7156e2020-02-28 17:29:39 -0800500 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800501}
502
Ady Abraham62a0be22020-12-08 16:54:10 -0800503std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
504groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
505 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
506 for (const auto& layer : layers) {
507 auto iter = layersByUid.emplace(layer.ownerUid,
508 std::vector<const RefreshRateConfigs::LayerRequirement*>());
509 auto& layersWithSameUid = iter.first->second;
510 layersWithSameUid.push_back(&layer);
511 }
512
513 // Remove uids that can't have a frame rate override
514 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
515 const auto& layersWithSameUid = iter->second;
516 bool skipUid = false;
517 for (const auto& layer : layersWithSameUid) {
518 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
519 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
520 skipUid = true;
521 break;
522 }
523 }
524 if (skipUid) {
525 iter = layersByUid.erase(iter);
526 } else {
527 ++iter;
528 }
529 }
530
531 return layersByUid;
532}
533
534std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
535 const AllRefreshRatesMapType& refreshRates) {
536 std::vector<RefreshRateScore> scores;
537 scores.reserve(refreshRates.size());
538 for (const auto& [ignored, refreshRate] : refreshRates) {
539 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
540 }
541 std::sort(scores.begin(), scores.end(),
542 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
543 return scores;
544}
545
546RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700547 const std::vector<LayerRequirement>& layers, Fps displayFrameRate,
548 GlobalSignals globalSignals) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800549 ATRACE_CALL();
Ady Abraham62a0be22020-12-08 16:54:10 -0800550
Ady Abraham64c2fc02020-12-29 12:07:50 -0800551 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800552 std::lock_guard lock(mLock);
553 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
554 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
555 groupLayersByUid(layers);
556 UidToFrameRateOverride frameRateOverrides;
557 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800558 // Layers with ExplicitExactOrMultiple expect touch boost
559 const bool hasExplicitExactOrMultiple =
560 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
561 [](const auto& layer) {
562 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
563 });
564
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700565 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800566 continue;
567 }
568
Ady Abraham62a0be22020-12-08 16:54:10 -0800569 for (auto& score : scores) {
570 score.score = 0;
571 }
572
573 for (const auto& layer : layersWithSameUid) {
574 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
575 continue;
576 }
577
578 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800579 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
580 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800581 for (RefreshRateScore& score : scores) {
582 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
583 /*isSeamlessSwitch*/ true);
584 score.score += layer->weight * layerScore;
585 }
586 }
587
588 // We just care about the refresh rates which are a divider of the
589 // display refresh rate
590 auto iter =
591 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
592 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
593 });
594 scores.erase(iter, scores.end());
595
596 // If we never scored any layers, we don't have a preferred frame rate
597 if (std::all_of(scores.begin(), scores.end(),
598 [](const RefreshRateScore& score) { return score.score == 0; })) {
599 continue;
600 }
601
602 // Now that we scored all the refresh rates we need to pick the one that got the highest
603 // score.
604 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700605 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800606 }
607
608 return frameRateOverrides;
609}
610
Ady Abraham34702102020-02-10 14:12:05 -0800611template <typename Iter>
612const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200613 constexpr auto kEpsilon = 0.0001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800614 const RefreshRate* bestRefreshRate = begin->refreshRate;
615 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800616 for (auto i = begin; i != end; ++i) {
617 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100618 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800619
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100620 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800621
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200622 if (score > max * (1 + kEpsilon)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800623 max = score;
624 bestRefreshRate = refreshRate;
625 }
626 }
627
Ady Abraham34702102020-02-10 14:12:05 -0800628 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800629}
630
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100631std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100632 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800633 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100634
635 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
636 : *mCurrentRefreshRate;
637 const auto& min = *mMinSupportedRefreshRate;
638
639 if (current != min) {
640 const auto& refreshRate = timerExpired ? min : current;
641 return refreshRate.getFps();
642 }
643
644 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700645}
646
647const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200648 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100649 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200650 return *refreshRate;
651 }
652 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100653 ALOGE("Can't find min refresh rate by policy with the same mode group"
654 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200655 mCurrentRefreshRate->toString().c_str());
656 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700657 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800658}
659
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100660RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800661 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700662 return getMaxRefreshRateByPolicyLocked();
663}
664
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200665const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200666 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
667 const auto& refreshRate = (**it);
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200668 if (anchorGroup == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200669 return refreshRate;
670 }
671 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100672 ALOGE("Can't find max refresh rate by policy with the same mode group"
673 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200674 mCurrentRefreshRate->toString().c_str());
675 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700676 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800677}
678
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100679RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800680 std::lock_guard lock(mLock);
681 return *mCurrentRefreshRate;
682}
683
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100684RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800685 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800686 return getCurrentRefreshRateByPolicyLocked();
687}
688
689const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700690 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
691 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800692 return *mCurrentRefreshRate;
693 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100694 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800695}
696
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100697void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800698 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200699
700 // Invalidate the cached invocation to getBestRefreshRate. This forces
701 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
702 lastBestRefreshRateInvocation.reset();
703
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100704 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800705}
706
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100707RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
rnlee3bd610662021-06-23 16:27:57 -0700708 Config config)
709 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700710 initializeIdleTimer();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100711 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100712}
713
Ady Abraham9a2ea342021-09-03 17:32:34 -0700714void RefreshRateConfigs::initializeIdleTimer() {
Ady Abraham6d885932021-09-03 18:05:48 -0700715 if (mConfig.idleTimerTimeoutMs > 0) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700716 mIdleTimer.emplace(
Ady Abraham6d885932021-09-03 18:05:48 -0700717 "IdleTimer", std::chrono::milliseconds(mConfig.idleTimerTimeoutMs),
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800718 [this] {
719 std::scoped_lock lock(mIdleTimerCallbacksMutex);
720 if (const auto callbacks = getIdleTimerCallbacks()) {
721 callbacks->onReset();
722 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700723 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800724 [this] {
725 std::scoped_lock lock(mIdleTimerCallbacksMutex);
726 if (const auto callbacks = getIdleTimerCallbacks()) {
727 callbacks->onExpired();
728 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700729 });
Ady Abraham9a2ea342021-09-03 17:32:34 -0700730 }
731}
732
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100733void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
734 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100735 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200736
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100737 // The current mode should be supported
738 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
739 return mode->getId() == currentModeId;
740 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700741
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200742 // Invalidate the cached invocation to getBestRefreshRate. This forces
743 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
744 lastBestRefreshRateInvocation.reset();
745
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100746 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100747 for (const auto& mode : modes) {
748 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100749 mRefreshRates.emplace(modeId,
Ady Abraham6b7ad652021-06-23 17:34:57 -0700750 std::make_unique<RefreshRate>(mode, RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100751 if (modeId == currentModeId) {
752 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700753 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800754 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700755
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100756 std::vector<const RefreshRate*> sortedModes;
757 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100758 // Reset the policy because the old one may no longer be valid.
759 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100760 mDisplayManagerPolicy.defaultMode = currentModeId;
761 mMinSupportedRefreshRate = sortedModes.front();
762 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800763
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800764 mSupportsFrameRateOverrideByContent = false;
rnlee3bd610662021-06-23 16:27:57 -0700765 if (mConfig.enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100766 for (const auto& mode1 : sortedModes) {
767 for (const auto& mode2 : sortedModes) {
768 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800769 mSupportsFrameRateOverrideByContent = true;
Ady Abraham4899ff82021-01-06 13:53:29 -0800770 break;
771 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800772 }
773 }
774 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800775
Ady Abrahamabc27602020-04-08 17:20:29 -0700776 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800777}
778
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100779bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100780 // defaultMode must be a valid mode, and within the given refresh rate range.
781 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700782 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100783 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700784 return false;
785 }
786 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700787 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100788 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700789 return false;
790 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700791
792 using namespace fps_approx_ops;
793 return policy.appRequestRange.min <= policy.primaryRange.min &&
794 policy.appRequestRange.max >= policy.primaryRange.max;
Steven Thomasd4071902020-03-24 16:02:53 -0700795}
796
797status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800798 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100799 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100800 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100801 return BAD_VALUE;
802 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200803 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700804 Policy previousPolicy = *getCurrentPolicyLocked();
805 mDisplayManagerPolicy = policy;
806 if (*getCurrentPolicyLocked() == previousPolicy) {
807 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100808 }
Ady Abraham2139f732019-11-13 18:56:40 -0800809 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100810 return NO_ERROR;
811}
812
Steven Thomasd4071902020-03-24 16:02:53 -0700813status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100814 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100815 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700816 return BAD_VALUE;
817 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200818 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700819 Policy previousPolicy = *getCurrentPolicyLocked();
820 mOverridePolicy = policy;
821 if (*getCurrentPolicyLocked() == previousPolicy) {
822 return CURRENT_POLICY_UNCHANGED;
823 }
824 constructAvailableRefreshRates();
825 return NO_ERROR;
826}
827
828const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
829 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
830}
831
832RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
833 std::lock_guard lock(mLock);
834 return *getCurrentPolicyLocked();
835}
836
837RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
838 std::lock_guard lock(mLock);
839 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100840}
841
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100842bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100843 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700844 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700845 if (refreshRate->getModeId() == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100846 return true;
847 }
848 }
849 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800850}
851
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100852void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800853 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
854 std::vector<const RefreshRate*>* outRefreshRates) {
855 outRefreshRates->clear();
856 outRefreshRates->reserve(mRefreshRates.size());
857 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800858 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100859 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Ady Abraham6b7ad652021-06-23 17:34:57 -0700860 refreshRate->getModeId().value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800861 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800862 }
863 }
864
865 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
866 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100867 if (refreshRate1->mode->getVsyncPeriod() !=
868 refreshRate2->mode->getVsyncPeriod()) {
869 return refreshRate1->mode->getVsyncPeriod() >
870 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700871 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100872 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700873 }
Ady Abraham2139f732019-11-13 18:56:40 -0800874 });
875}
876
877void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100878 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700879 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100880 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100881 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700882
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100883 auto filterRefreshRates =
884 [&](Fps min, Fps max, const char* listName,
885 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
886 getSortedRefreshRateListLocked(
887 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
888 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800889
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100890 return mode->getHeight() == defaultMode->getHeight() &&
891 mode->getWidth() == defaultMode->getWidth() &&
892 mode->getDpiX() == defaultMode->getDpiX() &&
893 mode->getDpiY() == defaultMode->getDpiY() &&
894 (policy->allowGroupSwitching ||
895 mode->getGroup() == defaultMode->getGroup()) &&
896 refreshRate.inPolicy(min, max);
897 },
898 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800899
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100900 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
901 "No matching modes for %s range: min=%s max=%s", listName,
902 to_string(min).c_str(), to_string(max).c_str());
903 auto stringifyRefreshRates = [&]() -> std::string {
904 std::string str;
905 for (auto refreshRate : *outRefreshRates) {
906 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
907 }
908 return str;
909 };
910 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
911 };
Steven Thomasf734df42020-04-13 21:09:28 -0700912
913 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
914 &mPrimaryRefreshRates);
915 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
916 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800917}
918
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100919Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700920 using namespace fps_approx_ops;
921
922 if (frameRate <= mKnownFrameRates.front()) {
923 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700924 }
925
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700926 if (frameRate >= mKnownFrameRates.back()) {
927 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700928 }
929
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100930 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700931 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700932
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700933 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
934 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700935 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
936}
937
Ana Krulecb9afd792020-06-11 13:16:15 -0700938RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
939 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100940 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700941 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
942 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
TreeHugger Robot758ab612021-06-22 19:17:29 +0000943 const auto& currentPolicy = getCurrentPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700944
945 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
946 // the min allowed refresh rate is higher than the device min, we do not want to enable the
947 // timer.
948 if (deviceMin < minByPolicy) {
949 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
950 }
951 if (minByPolicy == maxByPolicy) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000952 // when min primary range in display manager policy is below device min turn on the timer.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700953 if (isApproxLess(currentPolicy->primaryRange.min, deviceMin.getFps())) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000954 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700955 }
956 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
957 }
958 // Turn on the timer in all other cases.
959 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
960}
961
Ady Abraham62a0be22020-12-08 16:54:10 -0800962int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700963 // This calculation needs to be in sync with the java code
964 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200965
966 // The threshold must be smaller than 0.001 in order to differentiate
967 // between the fractional pairs (e.g. 59.94 and 60).
968 constexpr float kThreshold = 0.0009f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800969 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700970 const auto numPeriodsRounded = std::round(numPeriods);
971 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800972 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700973 }
974
Ady Abraham62f216c2020-10-13 19:07:23 -0700975 return static_cast<int>(numPeriodsRounded);
976}
977
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200978bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700979 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200980 return isFractionalPairOrMultiple(bigger, smaller);
981 }
982
983 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
984 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700985 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
986 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200987}
988
Marin Shalamanovba421a82020-11-10 21:49:26 +0100989void RefreshRateConfigs::dump(std::string& result) const {
990 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100991 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100992 mDisplayManagerPolicy.toString().c_str());
993 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
994 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100995 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100996 currentPolicy.toString().c_str());
997 }
998
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100999 auto mode = mCurrentRefreshRate->mode;
1000 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +01001001
1002 result.append("Refresh rates:\n");
1003 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001004 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +01001005 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
1006 }
1007
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001008 base::StringAppendF(&result, "Supports Frame Rate Override By Content: %s\n",
1009 mSupportsFrameRateOverrideByContent ? "yes" : "no");
Ady Abraham6d885932021-09-03 18:05:48 -07001010 base::StringAppendF(&result, "Idle timer: (%s) %s\n",
1011 mConfig.supportKernelIdleTimer ? "kernel" : "platform",
Ady Abraham9a2ea342021-09-03 17:32:34 -07001012 mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Marin Shalamanovba421a82020-11-10 21:49:26 +01001013 result.append("\n");
1014}
1015
Ady Abraham2139f732019-11-13 18:56:40 -08001016} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001017
1018// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001019#pragma clang diagnostic pop // ignored "-Wextra"