blob: eeeaac1170203d5c0c1ccf6b58cc1c91bde5ba1b [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
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080041constexpr RefreshRateConfigs::GlobalSignals kNoSignals;
42
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010043std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010044 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070045 ftl::enum_string(layer.vote).c_str(), weight,
46 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010047 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010048}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010049
Marin Shalamanova7fe3042021-01-29 21:02:08 +010050std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070051 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010052 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010053
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070054 // Add all supported refresh rates.
Marin Shalamanova7fe3042021-01-29 21:02:08 +010055 for (const auto& mode : modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070056 knownFrameRates.push_back(Fps::fromPeriodNsecs(mode->getVsyncPeriod()));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010057 }
58
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070059 // Sort and remove duplicates.
60 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010061 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070062 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010063 knownFrameRates.end());
64 return knownFrameRates;
65}
66
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010067} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080068
69using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080070using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080071
Marin Shalamanov46084422020-10-13 12:33:42 +020072std::string RefreshRate::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010073 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010074 getModeId().value(), mode->getHwcId(), getFps().getValue(),
75 mode->getWidth(), mode->getHeight(), getModeGroup());
Marin Shalamanov46084422020-10-13 12:33:42 +020076}
77
Marin Shalamanovb6674e72020-11-06 13:05:57 +010078std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010079 return base::StringPrintf("default mode ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010080 ", primary range: %s, app request range: %s",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010081 defaultMode.value(), allowGroupSwitching,
Dominik Laskowski953b7fd2022-01-08 19:34:59 -080082 to_string(primaryRange).c_str(), to_string(appRequestRange).c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020083}
84
Ady Abraham4ccdcb42020-02-11 17:34:34 -080085std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
86 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -080087 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
88 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
89 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
90 quotient++;
91 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -080092 }
93
Ady Abraham62a0be22020-12-08 16:54:10 -080094 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -080095}
96
rnlee3bd610662021-06-23 16:27:57 -070097bool RefreshRateConfigs::isVoteAllowed(const LayerRequirement& layer,
98 const RefreshRate& refreshRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070099 using namespace fps_approx_ops;
100
rnlee3bd610662021-06-23 16:27:57 -0700101 switch (layer.vote) {
102 case LayerVoteType::ExplicitExactOrMultiple:
103 case LayerVoteType::Heuristic:
104 if (mConfig.frameRateMultipleThreshold != 0 &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700105 refreshRate.getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold) &&
106 layer.desiredRefreshRate < Fps::fromValue(mConfig.frameRateMultipleThreshold / 2)) {
rnlee3bd610662021-06-23 16:27:57 -0700107 // Don't vote high refresh rates past the threshold for layers with a low desired
108 // refresh rate. For example, desired 24 fps with 120 Hz threshold means no vote for
109 // 120 Hz, but desired 60 fps should have a vote.
110 return false;
111 }
112 break;
113 case LayerVoteType::ExplicitDefault:
114 case LayerVoteType::ExplicitExact:
115 case LayerVoteType::Max:
116 case LayerVoteType::Min:
117 case LayerVoteType::NoVote:
118 break;
119 }
120 return true;
121}
122
Ady Abraham05243be2021-09-16 15:58:52 -0700123float RefreshRateConfigs::calculateNonExactMatchingLayerScoreLocked(
124 const LayerRequirement& layer, const RefreshRate& refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200125 constexpr float kScoreForFractionalPairs = .8f;
126
Ady Abraham62a0be22020-12-08 16:54:10 -0800127 const auto displayPeriod = refreshRate.getVsyncPeriod();
128 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
129 if (layer.vote == LayerVoteType::ExplicitDefault) {
130 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200131 // that layerPeriod is the minimal period to render a frame.
132 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
133 // then the actualLayerPeriod will be 32ms, because it is the
134 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800135 auto actualLayerPeriod = displayPeriod;
136 int multiplier = 1;
137 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
138 multiplier++;
139 actualLayerPeriod = displayPeriod * multiplier;
140 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200141
142 // Because of the threshold we used above it's possible that score is slightly
143 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800144 return std::min(1.0f,
145 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
146 }
147
148 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
149 layer.vote == LayerVoteType::Heuristic) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200150 if (isFractionalPairOrMultiple(refreshRate.getFps(), layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700151 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200152 }
153
Ady Abraham62a0be22020-12-08 16:54:10 -0800154 // Calculate how many display vsyncs we need to present a single frame for this
155 // layer
156 const auto [displayFramesQuotient, displayFramesRemainder] =
157 getDisplayFrames(layerPeriod, displayPeriod);
158 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
159 if (displayFramesRemainder == 0) {
160 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700161 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800162 }
163
164 if (displayFramesQuotient == 0) {
165 // Layer desired refresh rate is higher than the display rate.
166 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
167 (1.0f / (MAX_FRAMES_TO_FIT + 1));
168 }
169
170 // Layer desired refresh rate is lower than the display rate. Check how well it fits
171 // the cadence.
172 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
173 int iter = 2;
174 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
175 diff = diff - (displayPeriod - diff);
176 iter++;
177 }
178
Ady Abraham05243be2021-09-16 15:58:52 -0700179 return (1.0f / iter);
180 }
181
182 return 0;
183}
184
185float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
186 const RefreshRate& refreshRate,
187 bool isSeamlessSwitch) const {
188 if (!isVoteAllowed(layer, refreshRate)) {
189 return 0;
190 }
191
192 // Slightly prefer seamless switches.
193 constexpr float kSeamedSwitchPenalty = 0.95f;
194 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
195
196 // If the layer wants Max, give higher score to the higher refresh rate
197 if (layer.vote == LayerVoteType::Max) {
198 const auto ratio = refreshRate.getFps().getValue() /
199 mAppRequestRefreshRates.back()->getFps().getValue();
200 // use ratio^2 to get a lower score the more we get further from peak
201 return ratio * ratio;
Ady Abraham62a0be22020-12-08 16:54:10 -0800202 }
203
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800204 if (layer.vote == LayerVoteType::ExplicitExact) {
205 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800206 if (mSupportsFrameRateOverrideByContent) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800207 // Since we support frame rate override, allow refresh rates which are
208 // multiples of the layer's request, as those apps would be throttled
209 // down to run at the desired refresh rate.
210 return divider > 0;
211 }
212
213 return divider == 1;
214 }
215
Ady Abraham05243be2021-09-16 15:58:52 -0700216 // If the layer frame rate is a divider of the refresh rate it should score
217 // the highest score.
218 if (getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate) > 0) {
219 return 1.0f * seamlessness;
220 }
221
222 // The layer frame rate is not a divider of the refresh rate,
223 // there is a small penalty attached to the score to favor the frame rates
224 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800225 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700226 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
227 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800228}
229
230struct RefreshRateScore {
231 const RefreshRate* refreshRate;
232 float score;
233};
234
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800235auto RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
236 GlobalSignals signals) const
237 -> std::pair<RefreshRate, GlobalSignals> {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200238 std::lock_guard lock(mLock);
239
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800240 if (mGetBestRefreshRateCache &&
241 mGetBestRefreshRateCache->arguments == std::make_pair(layers, signals)) {
242 return mGetBestRefreshRateCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200243 }
244
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800245 const auto result = getBestRefreshRateLocked(layers, signals);
246 mGetBestRefreshRateCache = GetBestRefreshRateCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200247 return result;
248}
249
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800250auto RefreshRateConfigs::getBestRefreshRateLocked(const std::vector<LayerRequirement>& layers,
251 GlobalSignals signals) const
252 -> std::pair<RefreshRate, GlobalSignals> {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800253 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800254 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700255
Ady Abraham8a82ba62020-01-17 12:43:17 -0800256 int noVoteLayers = 0;
257 int minVoteLayers = 0;
258 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800259 int explicitDefaultVoteLayers = 0;
260 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800261 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800262 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100263 int seamedFocusedLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800264
Ady Abraham8a82ba62020-01-17 12:43:17 -0800265 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800266 switch (layer.vote) {
267 case LayerVoteType::NoVote:
268 noVoteLayers++;
269 break;
270 case LayerVoteType::Min:
271 minVoteLayers++;
272 break;
273 case LayerVoteType::Max:
274 maxVoteLayers++;
275 break;
276 case LayerVoteType::ExplicitDefault:
277 explicitDefaultVoteLayers++;
278 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
279 break;
280 case LayerVoteType::ExplicitExactOrMultiple:
281 explicitExactOrMultipleVoteLayers++;
282 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
283 break;
284 case LayerVoteType::ExplicitExact:
285 explicitExact++;
286 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
287 break;
288 case LayerVoteType::Heuristic:
289 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800290 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200291
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100292 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
293 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200294 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800295 }
296
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800297 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
298 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700299
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200300 const Policy* policy = getCurrentPolicyLocked();
301 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
302 // If the default mode group is different from the group of current mode,
303 // this means a layer requesting a seamed mode switch just disappeared and
304 // we should switch back to the default group.
305 // However if a seamed layer is still present we anchor around the group
306 // of the current mode, in order to prevent unnecessary seamed mode switches
307 // (e.g. when pausing a video playback).
308 const auto anchorGroup = seamedFocusedLayers > 0 ? mCurrentRefreshRate->getModeGroup()
309 : defaultMode->getModeGroup();
310
Steven Thomasf734df42020-04-13 21:09:28 -0700311 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
312 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800313 if (signals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700314 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800315 return {getMaxRefreshRateByPolicyLocked(anchorGroup), GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800316 }
317
Alec Mouri11232a22020-05-14 18:06:25 -0700318 // If the primary range consists of a single refresh rate then we can only
319 // move out the of range if layers explicitly request a different refresh
320 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100321 const bool primaryRangeIsSingleRate =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700322 isApproxEqual(policy->primaryRange.min, policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700323
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800324 if (!signals.touch && signals.idle && !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700325 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800326 return {getMinRefreshRateByPolicyLocked(), GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700327 }
328
Steven Thomasdebafed2020-05-18 17:30:35 -0700329 if (layers.empty() || noVoteLayers == layers.size()) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200330 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
331 ALOGV("no layers with votes - choose %s", refreshRate.getName().c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800332 return {refreshRate, kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700333 }
334
Ady Abraham8a82ba62020-01-17 12:43:17 -0800335 // Only if all layers want Min we should return Min
336 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700337 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800338 return {getMinRefreshRateByPolicyLocked(), kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800339 }
340
Ady Abraham8a82ba62020-01-17 12:43:17 -0800341 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800342 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700343 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800344
Steven Thomasf734df42020-04-13 21:09:28 -0700345 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800346 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800347 }
348
349 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700350 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700351 ftl::enum_string(layer.vote).c_str(), layer.weight,
rnlee3bd610662021-06-23 16:27:57 -0700352 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800353 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800354 continue;
355 }
356
Ady Abraham71c437d2020-01-31 15:56:57 -0800357 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800358
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800359 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100360 const bool isSeamlessSwitch =
361 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200362
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100363 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100364 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800365 formatLayerInfo(layer, weight).c_str(),
366 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100367 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200368 continue;
369 }
370
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100371 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
372 !layer.focused) {
373 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100374 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800375 formatLayerInfo(layer, weight).c_str(),
376 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100377 mCurrentRefreshRate->toString().c_str());
378 continue;
379 }
380
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100381 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100382 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100383 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100384 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
385 // disappeared.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200386 const bool isInPolicyForDefault = scores[i].refreshRate->getModeGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100387 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100388 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800389 scores[i].refreshRate->toString().c_str(),
390 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200391 continue;
392 }
393
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800394 const bool inPrimaryRange =
395 policy->primaryRange.includes(scores[i].refreshRate->getFps());
396
Alec Mouri11232a22020-05-14 18:06:25 -0700397 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800398 !(layer.focused &&
399 (layer.vote == LayerVoteType::ExplicitDefault ||
400 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700401 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700402 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700403 continue;
404 }
405
Ady Abraham62a0be22020-12-08 16:54:10 -0800406 const auto layerScore =
407 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200408 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800409 scores[i].refreshRate->getName().c_str(), layerScore);
410 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800411 }
412 }
413
Ady Abraham34702102020-02-10 14:12:05 -0800414 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
415 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
416 // or the lower otherwise.
417 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
418 ? getBestRefreshRate(scores.rbegin(), scores.rend())
419 : getBestRefreshRate(scores.begin(), scores.end());
420
Alec Mouri11232a22020-05-14 18:06:25 -0700421 if (primaryRangeIsSingleRate) {
422 // If we never scored any layers, then choose the rate from the primary
423 // range instead of picking a random score from the app range.
424 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800425 [](RefreshRateScore score) { return score.score == 0; })) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200426 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
427 ALOGV("layers not scored - choose %s", refreshRate.getName().c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800428 return {refreshRate, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700429 } else {
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800430 return {*bestRefreshRate, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700431 }
432 }
433
Steven Thomasf734df42020-04-13 21:09:28 -0700434 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
435 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
436 // vote we should not change it if we get a touch event. Only apply touch boost if it will
437 // actually increase the refresh rate over the normal selection.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200438 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
Alec Mouri11232a22020-05-14 18:06:25 -0700439
Ady Abraham5e4e9832021-06-14 13:40:56 -0700440 const bool touchBoostForExplicitExact = [&] {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800441 if (mSupportsFrameRateOverrideByContent) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700442 // Enable touch boost if there are other layers besides exact
443 return explicitExact + noVoteLayers != layers.size();
444 } else {
445 // Enable touch boost if there are no exact layers
446 return explicitExact == 0;
447 }
448 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700449
450 using fps_approx_ops::operator<;
451
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800452 if (signals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700453 bestRefreshRate->getFps() < touchRefreshRate.getFps()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700454 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800455 return {touchRefreshRate, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700456 }
457
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800458 return {*bestRefreshRate, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800459}
460
Ady Abraham62a0be22020-12-08 16:54:10 -0800461std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
462groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
463 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
464 for (const auto& layer : layers) {
465 auto iter = layersByUid.emplace(layer.ownerUid,
466 std::vector<const RefreshRateConfigs::LayerRequirement*>());
467 auto& layersWithSameUid = iter.first->second;
468 layersWithSameUid.push_back(&layer);
469 }
470
471 // Remove uids that can't have a frame rate override
472 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
473 const auto& layersWithSameUid = iter->second;
474 bool skipUid = false;
475 for (const auto& layer : layersWithSameUid) {
476 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
477 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
478 skipUid = true;
479 break;
480 }
481 }
482 if (skipUid) {
483 iter = layersByUid.erase(iter);
484 } else {
485 ++iter;
486 }
487 }
488
489 return layersByUid;
490}
491
492std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
493 const AllRefreshRatesMapType& refreshRates) {
494 std::vector<RefreshRateScore> scores;
495 scores.reserve(refreshRates.size());
496 for (const auto& [ignored, refreshRate] : refreshRates) {
497 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
498 }
499 std::sort(scores.begin(), scores.end(),
500 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
501 return scores;
502}
503
504RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700505 const std::vector<LayerRequirement>& layers, Fps displayFrameRate,
506 GlobalSignals globalSignals) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800507 ATRACE_CALL();
Ady Abraham62a0be22020-12-08 16:54:10 -0800508
Ady Abraham64c2fc02020-12-29 12:07:50 -0800509 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800510 std::lock_guard lock(mLock);
511 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
512 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
513 groupLayersByUid(layers);
514 UidToFrameRateOverride frameRateOverrides;
515 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800516 // Layers with ExplicitExactOrMultiple expect touch boost
517 const bool hasExplicitExactOrMultiple =
518 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
519 [](const auto& layer) {
520 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
521 });
522
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700523 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800524 continue;
525 }
526
Ady Abraham62a0be22020-12-08 16:54:10 -0800527 for (auto& score : scores) {
528 score.score = 0;
529 }
530
531 for (const auto& layer : layersWithSameUid) {
532 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
533 continue;
534 }
535
536 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800537 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
538 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800539 for (RefreshRateScore& score : scores) {
540 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
541 /*isSeamlessSwitch*/ true);
542 score.score += layer->weight * layerScore;
543 }
544 }
545
546 // We just care about the refresh rates which are a divider of the
547 // display refresh rate
548 auto iter =
549 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
550 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
551 });
552 scores.erase(iter, scores.end());
553
554 // If we never scored any layers, we don't have a preferred frame rate
555 if (std::all_of(scores.begin(), scores.end(),
556 [](const RefreshRateScore& score) { return score.score == 0; })) {
557 continue;
558 }
559
560 // Now that we scored all the refresh rates we need to pick the one that got the highest
561 // score.
562 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700563 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800564 }
565
566 return frameRateOverrides;
567}
568
Ady Abraham34702102020-02-10 14:12:05 -0800569template <typename Iter>
570const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200571 constexpr auto kEpsilon = 0.0001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800572 const RefreshRate* bestRefreshRate = begin->refreshRate;
573 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800574 for (auto i = begin; i != end; ++i) {
575 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100576 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800577
Dominik Laskowski62eff352021-12-06 09:59:41 -0800578 ATRACE_INT(refreshRate->getName().c_str(), static_cast<int>(std::round(score * 100)));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800579
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200580 if (score > max * (1 + kEpsilon)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800581 max = score;
582 bestRefreshRate = refreshRate;
583 }
584 }
585
Ady Abraham34702102020-02-10 14:12:05 -0800586 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800587}
588
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100589std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100590 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800591 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100592
593 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
594 : *mCurrentRefreshRate;
595 const auto& min = *mMinSupportedRefreshRate;
596
597 if (current != min) {
598 const auto& refreshRate = timerExpired ? min : current;
599 return refreshRate.getFps();
600 }
601
602 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700603}
604
605const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200606 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100607 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200608 return *refreshRate;
609 }
610 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100611 ALOGE("Can't find min refresh rate by policy with the same mode group"
612 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200613 mCurrentRefreshRate->toString().c_str());
614 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700615 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800616}
617
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100618RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800619 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700620 return getMaxRefreshRateByPolicyLocked();
621}
622
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200623const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200624 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
625 const auto& refreshRate = (**it);
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200626 if (anchorGroup == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200627 return refreshRate;
628 }
629 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100630 ALOGE("Can't find max refresh rate by policy with the same mode group"
631 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200632 mCurrentRefreshRate->toString().c_str());
633 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700634 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800635}
636
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100637RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800638 std::lock_guard lock(mLock);
639 return *mCurrentRefreshRate;
640}
641
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100642RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800643 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800644 return getCurrentRefreshRateByPolicyLocked();
645}
646
647const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700648 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
649 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800650 return *mCurrentRefreshRate;
651 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100652 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800653}
654
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100655void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800656 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200657
658 // Invalidate the cached invocation to getBestRefreshRate. This forces
659 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800660 mGetBestRefreshRateCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200661
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100662 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800663}
664
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100665RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
rnlee3bd610662021-06-23 16:27:57 -0700666 Config config)
667 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700668 initializeIdleTimer();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100669 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100670}
671
Ady Abraham9a2ea342021-09-03 17:32:34 -0700672void RefreshRateConfigs::initializeIdleTimer() {
Ady Abraham6d885932021-09-03 18:05:48 -0700673 if (mConfig.idleTimerTimeoutMs > 0) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700674 mIdleTimer.emplace(
Ady Abraham6d885932021-09-03 18:05:48 -0700675 "IdleTimer", std::chrono::milliseconds(mConfig.idleTimerTimeoutMs),
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800676 [this] {
677 std::scoped_lock lock(mIdleTimerCallbacksMutex);
678 if (const auto callbacks = getIdleTimerCallbacks()) {
679 callbacks->onReset();
680 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700681 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800682 [this] {
683 std::scoped_lock lock(mIdleTimerCallbacksMutex);
684 if (const auto callbacks = getIdleTimerCallbacks()) {
685 callbacks->onExpired();
686 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700687 });
Ady Abraham9a2ea342021-09-03 17:32:34 -0700688 }
689}
690
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100691void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
692 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100693 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200694
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100695 // The current mode should be supported
696 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
697 return mode->getId() == currentModeId;
698 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700699
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200700 // Invalidate the cached invocation to getBestRefreshRate. This forces
701 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800702 mGetBestRefreshRateCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200703
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100704 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100705 for (const auto& mode : modes) {
706 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100707 mRefreshRates.emplace(modeId,
Ady Abraham6b7ad652021-06-23 17:34:57 -0700708 std::make_unique<RefreshRate>(mode, RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100709 if (modeId == currentModeId) {
710 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700711 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800712 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700713
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100714 std::vector<const RefreshRate*> sortedModes;
715 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100716 // Reset the policy because the old one may no longer be valid.
717 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100718 mDisplayManagerPolicy.defaultMode = currentModeId;
719 mMinSupportedRefreshRate = sortedModes.front();
720 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800721
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800722 mSupportsFrameRateOverrideByContent = false;
rnlee3bd610662021-06-23 16:27:57 -0700723 if (mConfig.enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100724 for (const auto& mode1 : sortedModes) {
725 for (const auto& mode2 : sortedModes) {
726 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800727 mSupportsFrameRateOverrideByContent = true;
Ady Abraham4899ff82021-01-06 13:53:29 -0800728 break;
729 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800730 }
731 }
732 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800733
Ady Abrahamabc27602020-04-08 17:20:29 -0700734 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800735}
736
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100737bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100738 // defaultMode must be a valid mode, and within the given refresh rate range.
739 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700740 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100741 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700742 return false;
743 }
744 const RefreshRate& refreshRate = *iter->second;
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800745 if (!policy.primaryRange.includes(refreshRate.getFps())) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100746 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700747 return false;
748 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700749
750 using namespace fps_approx_ops;
751 return policy.appRequestRange.min <= policy.primaryRange.min &&
752 policy.appRequestRange.max >= policy.primaryRange.max;
Steven Thomasd4071902020-03-24 16:02:53 -0700753}
754
755status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800756 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100757 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100758 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100759 return BAD_VALUE;
760 }
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800761 mGetBestRefreshRateCache.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700762 Policy previousPolicy = *getCurrentPolicyLocked();
763 mDisplayManagerPolicy = policy;
764 if (*getCurrentPolicyLocked() == previousPolicy) {
765 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100766 }
Ady Abraham2139f732019-11-13 18:56:40 -0800767 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100768 return NO_ERROR;
769}
770
Steven Thomasd4071902020-03-24 16:02:53 -0700771status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100772 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100773 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700774 return BAD_VALUE;
775 }
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800776 mGetBestRefreshRateCache.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700777 Policy previousPolicy = *getCurrentPolicyLocked();
778 mOverridePolicy = policy;
779 if (*getCurrentPolicyLocked() == previousPolicy) {
780 return CURRENT_POLICY_UNCHANGED;
781 }
782 constructAvailableRefreshRates();
783 return NO_ERROR;
784}
785
786const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
787 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
788}
789
790RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
791 std::lock_guard lock(mLock);
792 return *getCurrentPolicyLocked();
793}
794
795RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
796 std::lock_guard lock(mLock);
797 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100798}
799
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100800bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100801 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700802 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700803 if (refreshRate->getModeId() == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100804 return true;
805 }
806 }
807 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800808}
809
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100810void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800811 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
812 std::vector<const RefreshRate*>* outRefreshRates) {
813 outRefreshRates->clear();
814 outRefreshRates->reserve(mRefreshRates.size());
815 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800816 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100817 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Ady Abraham6b7ad652021-06-23 17:34:57 -0700818 refreshRate->getModeId().value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800819 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800820 }
821 }
822
823 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
824 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100825 if (refreshRate1->mode->getVsyncPeriod() !=
826 refreshRate2->mode->getVsyncPeriod()) {
827 return refreshRate1->mode->getVsyncPeriod() >
828 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700829 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100830 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700831 }
Ady Abraham2139f732019-11-13 18:56:40 -0800832 });
833}
834
835void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100836 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700837 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100838 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100839 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700840
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100841 auto filterRefreshRates =
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800842 [&](FpsRange range, const char* rangeName,
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100843 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
844 getSortedRefreshRateListLocked(
845 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
846 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800847
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100848 return mode->getHeight() == defaultMode->getHeight() &&
849 mode->getWidth() == defaultMode->getWidth() &&
850 mode->getDpiX() == defaultMode->getDpiX() &&
851 mode->getDpiY() == defaultMode->getDpiY() &&
852 (policy->allowGroupSwitching ||
853 mode->getGroup() == defaultMode->getGroup()) &&
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800854 range.includes(mode->getFps());
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100855 },
856 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800857
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800858 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(), "No matching modes for %s range %s",
859 rangeName, to_string(range).c_str());
860
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100861 auto stringifyRefreshRates = [&]() -> std::string {
862 std::string str;
863 for (auto refreshRate : *outRefreshRates) {
864 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
865 }
866 return str;
867 };
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800868 ALOGV("%s refresh rates: %s", rangeName, stringifyRefreshRates().c_str());
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100869 };
Steven Thomasf734df42020-04-13 21:09:28 -0700870
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800871 filterRefreshRates(policy->primaryRange, "primary", &mPrimaryRefreshRates);
872 filterRefreshRates(policy->appRequestRange, "app request", &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800873}
874
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100875Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700876 using namespace fps_approx_ops;
877
878 if (frameRate <= mKnownFrameRates.front()) {
879 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700880 }
881
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700882 if (frameRate >= mKnownFrameRates.back()) {
883 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700884 }
885
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100886 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700887 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700888
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700889 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
890 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700891 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
892}
893
Ana Krulecb9afd792020-06-11 13:16:15 -0700894RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
895 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100896 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700897 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
898 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
TreeHugger Robot758ab612021-06-22 19:17:29 +0000899 const auto& currentPolicy = getCurrentPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700900
901 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
902 // the min allowed refresh rate is higher than the device min, we do not want to enable the
903 // timer.
904 if (deviceMin < minByPolicy) {
905 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
906 }
907 if (minByPolicy == maxByPolicy) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000908 // when min primary range in display manager policy is below device min turn on the timer.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700909 if (isApproxLess(currentPolicy->primaryRange.min, deviceMin.getFps())) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000910 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700911 }
912 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
913 }
914 // Turn on the timer in all other cases.
915 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
916}
917
Ady Abraham62a0be22020-12-08 16:54:10 -0800918int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700919 // This calculation needs to be in sync with the java code
920 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200921
922 // The threshold must be smaller than 0.001 in order to differentiate
923 // between the fractional pairs (e.g. 59.94 and 60).
924 constexpr float kThreshold = 0.0009f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800925 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700926 const auto numPeriodsRounded = std::round(numPeriods);
927 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800928 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700929 }
930
Ady Abraham62f216c2020-10-13 19:07:23 -0700931 return static_cast<int>(numPeriodsRounded);
932}
933
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200934bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700935 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200936 return isFractionalPairOrMultiple(bigger, smaller);
937 }
938
939 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
940 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700941 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
942 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200943}
944
Marin Shalamanovba421a82020-11-10 21:49:26 +0100945void RefreshRateConfigs::dump(std::string& result) const {
946 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100947 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100948 mDisplayManagerPolicy.toString().c_str());
949 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
950 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100951 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100952 currentPolicy.toString().c_str());
953 }
954
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100955 auto mode = mCurrentRefreshRate->mode;
956 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100957
958 result.append("Refresh rates:\n");
959 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100960 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +0100961 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
962 }
963
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800964 base::StringAppendF(&result, "Supports Frame Rate Override By Content: %s\n",
965 mSupportsFrameRateOverrideByContent ? "yes" : "no");
Ady Abraham6d885932021-09-03 18:05:48 -0700966 base::StringAppendF(&result, "Idle timer: (%s) %s\n",
967 mConfig.supportKernelIdleTimer ? "kernel" : "platform",
Ady Abraham9a2ea342021-09-03 17:32:34 -0700968 mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100969 result.append("\n");
970}
971
Ady Abraham2139f732019-11-13 18:56:40 -0800972} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100973
974// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800975#pragma clang diagnostic pop // ignored "-Wextra"