blob: 3b9cfa6340a33a69a630e73383bb26c2373fd0c4 [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
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070072bool RefreshRate::inPolicy(Fps minRefreshRate, Fps maxRefreshRate) const {
73 using fps_approx_ops::operator<=;
74 return minRefreshRate <= getFps() && getFps() <= maxRefreshRate;
75}
76
Marin Shalamanov46084422020-10-13 12:33:42 +020077std::string RefreshRate::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010078 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010079 getModeId().value(), mode->getHwcId(), getFps().getValue(),
80 mode->getWidth(), mode->getHeight(), getModeGroup());
Marin Shalamanov46084422020-10-13 12:33:42 +020081}
82
Marin Shalamanovb6674e72020-11-06 13:05:57 +010083std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010084 return base::StringPrintf("default mode ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010085 ", primary range: %s, app request range: %s",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010086 defaultMode.value(), allowGroupSwitching,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010087 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020088}
89
Ady Abraham4ccdcb42020-02-11 17:34:34 -080090std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
91 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -080092 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
93 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
94 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
95 quotient++;
96 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -080097 }
98
Ady Abraham62a0be22020-12-08 16:54:10 -080099 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800100}
101
rnlee3bd610662021-06-23 16:27:57 -0700102bool RefreshRateConfigs::isVoteAllowed(const LayerRequirement& layer,
103 const RefreshRate& refreshRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700104 using namespace fps_approx_ops;
105
rnlee3bd610662021-06-23 16:27:57 -0700106 switch (layer.vote) {
107 case LayerVoteType::ExplicitExactOrMultiple:
108 case LayerVoteType::Heuristic:
109 if (mConfig.frameRateMultipleThreshold != 0 &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700110 refreshRate.getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold) &&
111 layer.desiredRefreshRate < Fps::fromValue(mConfig.frameRateMultipleThreshold / 2)) {
rnlee3bd610662021-06-23 16:27:57 -0700112 // Don't vote high refresh rates past the threshold for layers with a low desired
113 // refresh rate. For example, desired 24 fps with 120 Hz threshold means no vote for
114 // 120 Hz, but desired 60 fps should have a vote.
115 return false;
116 }
117 break;
118 case LayerVoteType::ExplicitDefault:
119 case LayerVoteType::ExplicitExact:
120 case LayerVoteType::Max:
121 case LayerVoteType::Min:
122 case LayerVoteType::NoVote:
123 break;
124 }
125 return true;
126}
127
Ady Abraham05243be2021-09-16 15:58:52 -0700128float RefreshRateConfigs::calculateNonExactMatchingLayerScoreLocked(
129 const LayerRequirement& layer, const RefreshRate& refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200130 constexpr float kScoreForFractionalPairs = .8f;
131
Ady Abraham62a0be22020-12-08 16:54:10 -0800132 const auto displayPeriod = refreshRate.getVsyncPeriod();
133 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
134 if (layer.vote == LayerVoteType::ExplicitDefault) {
135 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200136 // that layerPeriod is the minimal period to render a frame.
137 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
138 // then the actualLayerPeriod will be 32ms, because it is the
139 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800140 auto actualLayerPeriod = displayPeriod;
141 int multiplier = 1;
142 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
143 multiplier++;
144 actualLayerPeriod = displayPeriod * multiplier;
145 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200146
147 // Because of the threshold we used above it's possible that score is slightly
148 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800149 return std::min(1.0f,
150 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
151 }
152
153 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
154 layer.vote == LayerVoteType::Heuristic) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200155 if (isFractionalPairOrMultiple(refreshRate.getFps(), layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700156 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200157 }
158
Ady Abraham62a0be22020-12-08 16:54:10 -0800159 // Calculate how many display vsyncs we need to present a single frame for this
160 // layer
161 const auto [displayFramesQuotient, displayFramesRemainder] =
162 getDisplayFrames(layerPeriod, displayPeriod);
163 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
164 if (displayFramesRemainder == 0) {
165 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700166 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800167 }
168
169 if (displayFramesQuotient == 0) {
170 // Layer desired refresh rate is higher than the display rate.
171 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
172 (1.0f / (MAX_FRAMES_TO_FIT + 1));
173 }
174
175 // Layer desired refresh rate is lower than the display rate. Check how well it fits
176 // the cadence.
177 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
178 int iter = 2;
179 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
180 diff = diff - (displayPeriod - diff);
181 iter++;
182 }
183
Ady Abraham05243be2021-09-16 15:58:52 -0700184 return (1.0f / iter);
185 }
186
187 return 0;
188}
189
190float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
191 const RefreshRate& refreshRate,
192 bool isSeamlessSwitch) const {
193 if (!isVoteAllowed(layer, refreshRate)) {
194 return 0;
195 }
196
197 // Slightly prefer seamless switches.
198 constexpr float kSeamedSwitchPenalty = 0.95f;
199 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
200
201 // If the layer wants Max, give higher score to the higher refresh rate
202 if (layer.vote == LayerVoteType::Max) {
203 const auto ratio = refreshRate.getFps().getValue() /
204 mAppRequestRefreshRates.back()->getFps().getValue();
205 // use ratio^2 to get a lower score the more we get further from peak
206 return ratio * ratio;
Ady Abraham62a0be22020-12-08 16:54:10 -0800207 }
208
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800209 if (layer.vote == LayerVoteType::ExplicitExact) {
210 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800211 if (mSupportsFrameRateOverrideByContent) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800212 // Since we support frame rate override, allow refresh rates which are
213 // multiples of the layer's request, as those apps would be throttled
214 // down to run at the desired refresh rate.
215 return divider > 0;
216 }
217
218 return divider == 1;
219 }
220
Ady Abraham05243be2021-09-16 15:58:52 -0700221 // If the layer frame rate is a divider of the refresh rate it should score
222 // the highest score.
223 if (getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate) > 0) {
224 return 1.0f * seamlessness;
225 }
226
227 // The layer frame rate is not a divider of the refresh rate,
228 // there is a small penalty attached to the score to favor the frame rates
229 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800230 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700231 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
232 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800233}
234
235struct RefreshRateScore {
236 const RefreshRate* refreshRate;
237 float score;
238};
239
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800240auto RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
241 GlobalSignals signals) const
242 -> std::pair<RefreshRate, GlobalSignals> {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200243 std::lock_guard lock(mLock);
244
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800245 if (mGetBestRefreshRateCache &&
246 mGetBestRefreshRateCache->arguments == std::make_pair(layers, signals)) {
247 return mGetBestRefreshRateCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200248 }
249
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800250 const auto result = getBestRefreshRateLocked(layers, signals);
251 mGetBestRefreshRateCache = GetBestRefreshRateCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200252 return result;
253}
254
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800255auto RefreshRateConfigs::getBestRefreshRateLocked(const std::vector<LayerRequirement>& layers,
256 GlobalSignals signals) const
257 -> std::pair<RefreshRate, GlobalSignals> {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800258 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800259 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700260
Ady Abraham8a82ba62020-01-17 12:43:17 -0800261 int noVoteLayers = 0;
262 int minVoteLayers = 0;
263 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800264 int explicitDefaultVoteLayers = 0;
265 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800266 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800267 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100268 int seamedFocusedLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800269
Ady Abraham8a82ba62020-01-17 12:43:17 -0800270 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800271 switch (layer.vote) {
272 case LayerVoteType::NoVote:
273 noVoteLayers++;
274 break;
275 case LayerVoteType::Min:
276 minVoteLayers++;
277 break;
278 case LayerVoteType::Max:
279 maxVoteLayers++;
280 break;
281 case LayerVoteType::ExplicitDefault:
282 explicitDefaultVoteLayers++;
283 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
284 break;
285 case LayerVoteType::ExplicitExactOrMultiple:
286 explicitExactOrMultipleVoteLayers++;
287 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
288 break;
289 case LayerVoteType::ExplicitExact:
290 explicitExact++;
291 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
292 break;
293 case LayerVoteType::Heuristic:
294 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800295 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200296
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100297 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
298 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200299 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800300 }
301
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800302 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
303 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700304
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200305 const Policy* policy = getCurrentPolicyLocked();
306 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
307 // If the default mode group is different from the group of current mode,
308 // this means a layer requesting a seamed mode switch just disappeared and
309 // we should switch back to the default group.
310 // However if a seamed layer is still present we anchor around the group
311 // of the current mode, in order to prevent unnecessary seamed mode switches
312 // (e.g. when pausing a video playback).
313 const auto anchorGroup = seamedFocusedLayers > 0 ? mCurrentRefreshRate->getModeGroup()
314 : defaultMode->getModeGroup();
315
Steven Thomasf734df42020-04-13 21:09:28 -0700316 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
317 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800318 if (signals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700319 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800320 return {getMaxRefreshRateByPolicyLocked(anchorGroup), GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800321 }
322
Alec Mouri11232a22020-05-14 18:06:25 -0700323 // If the primary range consists of a single refresh rate then we can only
324 // move out the of range if layers explicitly request a different refresh
325 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100326 const bool primaryRangeIsSingleRate =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700327 isApproxEqual(policy->primaryRange.min, policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700328
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800329 if (!signals.touch && signals.idle && !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700330 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800331 return {getMinRefreshRateByPolicyLocked(), GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700332 }
333
Steven Thomasdebafed2020-05-18 17:30:35 -0700334 if (layers.empty() || noVoteLayers == layers.size()) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200335 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
336 ALOGV("no layers with votes - choose %s", refreshRate.getName().c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800337 return {refreshRate, kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700338 }
339
Ady Abraham8a82ba62020-01-17 12:43:17 -0800340 // Only if all layers want Min we should return Min
341 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700342 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800343 return {getMinRefreshRateByPolicyLocked(), kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800344 }
345
Ady Abraham8a82ba62020-01-17 12:43:17 -0800346 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800347 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700348 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800349
Steven Thomasf734df42020-04-13 21:09:28 -0700350 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800351 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800352 }
353
354 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700355 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700356 ftl::enum_string(layer.vote).c_str(), layer.weight,
rnlee3bd610662021-06-23 16:27:57 -0700357 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800358 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800359 continue;
360 }
361
Ady Abraham71c437d2020-01-31 15:56:57 -0800362 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800363
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800364 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100365 const bool isSeamlessSwitch =
366 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200367
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100368 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100369 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800370 formatLayerInfo(layer, weight).c_str(),
371 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100372 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200373 continue;
374 }
375
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100376 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
377 !layer.focused) {
378 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100379 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800380 formatLayerInfo(layer, weight).c_str(),
381 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100382 mCurrentRefreshRate->toString().c_str());
383 continue;
384 }
385
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100386 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100387 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100388 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100389 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
390 // disappeared.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200391 const bool isInPolicyForDefault = scores[i].refreshRate->getModeGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100392 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100393 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800394 scores[i].refreshRate->toString().c_str(),
395 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200396 continue;
397 }
398
Ady Abraham62a0be22020-12-08 16:54:10 -0800399 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
400 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700401 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800402 !(layer.focused &&
403 (layer.vote == LayerVoteType::ExplicitDefault ||
404 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700405 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700406 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700407 continue;
408 }
409
Ady Abraham62a0be22020-12-08 16:54:10 -0800410 const auto layerScore =
411 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200412 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800413 scores[i].refreshRate->getName().c_str(), layerScore);
414 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800415 }
416 }
417
Ady Abraham34702102020-02-10 14:12:05 -0800418 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
419 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
420 // or the lower otherwise.
421 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
422 ? getBestRefreshRate(scores.rbegin(), scores.rend())
423 : getBestRefreshRate(scores.begin(), scores.end());
424
Alec Mouri11232a22020-05-14 18:06:25 -0700425 if (primaryRangeIsSingleRate) {
426 // If we never scored any layers, then choose the rate from the primary
427 // range instead of picking a random score from the app range.
428 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800429 [](RefreshRateScore score) { return score.score == 0; })) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200430 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
431 ALOGV("layers not scored - choose %s", refreshRate.getName().c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800432 return {refreshRate, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700433 } else {
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800434 return {*bestRefreshRate, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700435 }
436 }
437
Steven Thomasf734df42020-04-13 21:09:28 -0700438 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
439 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
440 // vote we should not change it if we get a touch event. Only apply touch boost if it will
441 // actually increase the refresh rate over the normal selection.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200442 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
Alec Mouri11232a22020-05-14 18:06:25 -0700443
Ady Abraham5e4e9832021-06-14 13:40:56 -0700444 const bool touchBoostForExplicitExact = [&] {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800445 if (mSupportsFrameRateOverrideByContent) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700446 // Enable touch boost if there are other layers besides exact
447 return explicitExact + noVoteLayers != layers.size();
448 } else {
449 // Enable touch boost if there are no exact layers
450 return explicitExact == 0;
451 }
452 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700453
454 using fps_approx_ops::operator<;
455
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800456 if (signals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700457 bestRefreshRate->getFps() < touchRefreshRate.getFps()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700458 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800459 return {touchRefreshRate, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700460 }
461
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800462 return {*bestRefreshRate, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800463}
464
Ady Abraham62a0be22020-12-08 16:54:10 -0800465std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
466groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
467 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
468 for (const auto& layer : layers) {
469 auto iter = layersByUid.emplace(layer.ownerUid,
470 std::vector<const RefreshRateConfigs::LayerRequirement*>());
471 auto& layersWithSameUid = iter.first->second;
472 layersWithSameUid.push_back(&layer);
473 }
474
475 // Remove uids that can't have a frame rate override
476 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
477 const auto& layersWithSameUid = iter->second;
478 bool skipUid = false;
479 for (const auto& layer : layersWithSameUid) {
480 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
481 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
482 skipUid = true;
483 break;
484 }
485 }
486 if (skipUid) {
487 iter = layersByUid.erase(iter);
488 } else {
489 ++iter;
490 }
491 }
492
493 return layersByUid;
494}
495
496std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
497 const AllRefreshRatesMapType& refreshRates) {
498 std::vector<RefreshRateScore> scores;
499 scores.reserve(refreshRates.size());
500 for (const auto& [ignored, refreshRate] : refreshRates) {
501 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
502 }
503 std::sort(scores.begin(), scores.end(),
504 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
505 return scores;
506}
507
508RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700509 const std::vector<LayerRequirement>& layers, Fps displayFrameRate,
510 GlobalSignals globalSignals) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800511 ATRACE_CALL();
Ady Abraham62a0be22020-12-08 16:54:10 -0800512
Ady Abraham64c2fc02020-12-29 12:07:50 -0800513 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800514 std::lock_guard lock(mLock);
515 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
516 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
517 groupLayersByUid(layers);
518 UidToFrameRateOverride frameRateOverrides;
519 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800520 // Layers with ExplicitExactOrMultiple expect touch boost
521 const bool hasExplicitExactOrMultiple =
522 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
523 [](const auto& layer) {
524 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
525 });
526
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700527 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800528 continue;
529 }
530
Ady Abraham62a0be22020-12-08 16:54:10 -0800531 for (auto& score : scores) {
532 score.score = 0;
533 }
534
535 for (const auto& layer : layersWithSameUid) {
536 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
537 continue;
538 }
539
540 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800541 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
542 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800543 for (RefreshRateScore& score : scores) {
544 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
545 /*isSeamlessSwitch*/ true);
546 score.score += layer->weight * layerScore;
547 }
548 }
549
550 // We just care about the refresh rates which are a divider of the
551 // display refresh rate
552 auto iter =
553 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
554 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
555 });
556 scores.erase(iter, scores.end());
557
558 // If we never scored any layers, we don't have a preferred frame rate
559 if (std::all_of(scores.begin(), scores.end(),
560 [](const RefreshRateScore& score) { return score.score == 0; })) {
561 continue;
562 }
563
564 // Now that we scored all the refresh rates we need to pick the one that got the highest
565 // score.
566 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700567 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800568 }
569
570 return frameRateOverrides;
571}
572
Ady Abraham34702102020-02-10 14:12:05 -0800573template <typename Iter>
574const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200575 constexpr auto kEpsilon = 0.0001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800576 const RefreshRate* bestRefreshRate = begin->refreshRate;
577 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800578 for (auto i = begin; i != end; ++i) {
579 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100580 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800581
Dominik Laskowski62eff352021-12-06 09:59:41 -0800582 ATRACE_INT(refreshRate->getName().c_str(), static_cast<int>(std::round(score * 100)));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800583
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200584 if (score > max * (1 + kEpsilon)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800585 max = score;
586 bestRefreshRate = refreshRate;
587 }
588 }
589
Ady Abraham34702102020-02-10 14:12:05 -0800590 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800591}
592
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100593std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100594 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800595 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100596
597 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
598 : *mCurrentRefreshRate;
599 const auto& min = *mMinSupportedRefreshRate;
600
601 if (current != min) {
602 const auto& refreshRate = timerExpired ? min : current;
603 return refreshRate.getFps();
604 }
605
606 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700607}
608
609const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200610 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100611 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200612 return *refreshRate;
613 }
614 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100615 ALOGE("Can't find min refresh rate by policy with the same mode group"
616 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200617 mCurrentRefreshRate->toString().c_str());
618 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700619 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800620}
621
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100622RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800623 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700624 return getMaxRefreshRateByPolicyLocked();
625}
626
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200627const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200628 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
629 const auto& refreshRate = (**it);
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200630 if (anchorGroup == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200631 return refreshRate;
632 }
633 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100634 ALOGE("Can't find max refresh rate by policy with the same mode group"
635 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200636 mCurrentRefreshRate->toString().c_str());
637 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700638 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800639}
640
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100641RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800642 std::lock_guard lock(mLock);
643 return *mCurrentRefreshRate;
644}
645
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100646RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800647 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800648 return getCurrentRefreshRateByPolicyLocked();
649}
650
651const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700652 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
653 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800654 return *mCurrentRefreshRate;
655 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100656 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800657}
658
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100659void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800660 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200661
662 // Invalidate the cached invocation to getBestRefreshRate. This forces
663 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800664 mGetBestRefreshRateCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200665
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100666 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800667}
668
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100669RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
rnlee3bd610662021-06-23 16:27:57 -0700670 Config config)
671 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700672 initializeIdleTimer();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100673 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100674}
675
Ady Abraham9a2ea342021-09-03 17:32:34 -0700676void RefreshRateConfigs::initializeIdleTimer() {
Ady Abraham6d885932021-09-03 18:05:48 -0700677 if (mConfig.idleTimerTimeoutMs > 0) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700678 mIdleTimer.emplace(
Ady Abraham6d885932021-09-03 18:05:48 -0700679 "IdleTimer", std::chrono::milliseconds(mConfig.idleTimerTimeoutMs),
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800680 [this] {
681 std::scoped_lock lock(mIdleTimerCallbacksMutex);
682 if (const auto callbacks = getIdleTimerCallbacks()) {
683 callbacks->onReset();
684 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700685 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800686 [this] {
687 std::scoped_lock lock(mIdleTimerCallbacksMutex);
688 if (const auto callbacks = getIdleTimerCallbacks()) {
689 callbacks->onExpired();
690 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700691 });
Ady Abraham9a2ea342021-09-03 17:32:34 -0700692 }
693}
694
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100695void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
696 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100697 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200698
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100699 // The current mode should be supported
700 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
701 return mode->getId() == currentModeId;
702 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700703
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200704 // Invalidate the cached invocation to getBestRefreshRate. This forces
705 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800706 mGetBestRefreshRateCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200707
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100708 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100709 for (const auto& mode : modes) {
710 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100711 mRefreshRates.emplace(modeId,
Ady Abraham6b7ad652021-06-23 17:34:57 -0700712 std::make_unique<RefreshRate>(mode, RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100713 if (modeId == currentModeId) {
714 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700715 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800716 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700717
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100718 std::vector<const RefreshRate*> sortedModes;
719 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100720 // Reset the policy because the old one may no longer be valid.
721 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100722 mDisplayManagerPolicy.defaultMode = currentModeId;
723 mMinSupportedRefreshRate = sortedModes.front();
724 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800725
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800726 mSupportsFrameRateOverrideByContent = false;
rnlee3bd610662021-06-23 16:27:57 -0700727 if (mConfig.enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100728 for (const auto& mode1 : sortedModes) {
729 for (const auto& mode2 : sortedModes) {
730 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800731 mSupportsFrameRateOverrideByContent = true;
Ady Abraham4899ff82021-01-06 13:53:29 -0800732 break;
733 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800734 }
735 }
736 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800737
Ady Abrahamabc27602020-04-08 17:20:29 -0700738 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800739}
740
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100741bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100742 // defaultMode must be a valid mode, and within the given refresh rate range.
743 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700744 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100745 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700746 return false;
747 }
748 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700749 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100750 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700751 return false;
752 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700753
754 using namespace fps_approx_ops;
755 return policy.appRequestRange.min <= policy.primaryRange.min &&
756 policy.appRequestRange.max >= policy.primaryRange.max;
Steven Thomasd4071902020-03-24 16:02:53 -0700757}
758
759status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800760 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100761 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100762 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100763 return BAD_VALUE;
764 }
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800765 mGetBestRefreshRateCache.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700766 Policy previousPolicy = *getCurrentPolicyLocked();
767 mDisplayManagerPolicy = policy;
768 if (*getCurrentPolicyLocked() == previousPolicy) {
769 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100770 }
Ady Abraham2139f732019-11-13 18:56:40 -0800771 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100772 return NO_ERROR;
773}
774
Steven Thomasd4071902020-03-24 16:02:53 -0700775status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100776 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100777 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700778 return BAD_VALUE;
779 }
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800780 mGetBestRefreshRateCache.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700781 Policy previousPolicy = *getCurrentPolicyLocked();
782 mOverridePolicy = policy;
783 if (*getCurrentPolicyLocked() == previousPolicy) {
784 return CURRENT_POLICY_UNCHANGED;
785 }
786 constructAvailableRefreshRates();
787 return NO_ERROR;
788}
789
790const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
791 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
792}
793
794RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
795 std::lock_guard lock(mLock);
796 return *getCurrentPolicyLocked();
797}
798
799RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
800 std::lock_guard lock(mLock);
801 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100802}
803
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100804bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100805 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700806 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700807 if (refreshRate->getModeId() == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100808 return true;
809 }
810 }
811 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800812}
813
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100814void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800815 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
816 std::vector<const RefreshRate*>* outRefreshRates) {
817 outRefreshRates->clear();
818 outRefreshRates->reserve(mRefreshRates.size());
819 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800820 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100821 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Ady Abraham6b7ad652021-06-23 17:34:57 -0700822 refreshRate->getModeId().value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800823 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800824 }
825 }
826
827 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
828 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100829 if (refreshRate1->mode->getVsyncPeriod() !=
830 refreshRate2->mode->getVsyncPeriod()) {
831 return refreshRate1->mode->getVsyncPeriod() >
832 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700833 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100834 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700835 }
Ady Abraham2139f732019-11-13 18:56:40 -0800836 });
837}
838
839void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100840 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700841 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100842 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100843 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700844
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100845 auto filterRefreshRates =
846 [&](Fps min, Fps max, const char* listName,
847 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
848 getSortedRefreshRateListLocked(
849 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
850 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800851
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100852 return mode->getHeight() == defaultMode->getHeight() &&
853 mode->getWidth() == defaultMode->getWidth() &&
854 mode->getDpiX() == defaultMode->getDpiX() &&
855 mode->getDpiY() == defaultMode->getDpiY() &&
856 (policy->allowGroupSwitching ||
857 mode->getGroup() == defaultMode->getGroup()) &&
858 refreshRate.inPolicy(min, max);
859 },
860 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800861
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100862 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
863 "No matching modes for %s range: min=%s max=%s", listName,
864 to_string(min).c_str(), to_string(max).c_str());
865 auto stringifyRefreshRates = [&]() -> std::string {
866 std::string str;
867 for (auto refreshRate : *outRefreshRates) {
868 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
869 }
870 return str;
871 };
872 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
873 };
Steven Thomasf734df42020-04-13 21:09:28 -0700874
875 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
876 &mPrimaryRefreshRates);
877 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
878 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800879}
880
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100881Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700882 using namespace fps_approx_ops;
883
884 if (frameRate <= mKnownFrameRates.front()) {
885 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700886 }
887
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700888 if (frameRate >= mKnownFrameRates.back()) {
889 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700890 }
891
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100892 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700893 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700894
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700895 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
896 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700897 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
898}
899
Ana Krulecb9afd792020-06-11 13:16:15 -0700900RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
901 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100902 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700903 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
904 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
TreeHugger Robot758ab612021-06-22 19:17:29 +0000905 const auto& currentPolicy = getCurrentPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700906
907 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
908 // the min allowed refresh rate is higher than the device min, we do not want to enable the
909 // timer.
910 if (deviceMin < minByPolicy) {
911 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
912 }
913 if (minByPolicy == maxByPolicy) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000914 // when min primary range in display manager policy is below device min turn on the timer.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700915 if (isApproxLess(currentPolicy->primaryRange.min, deviceMin.getFps())) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000916 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700917 }
918 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
919 }
920 // Turn on the timer in all other cases.
921 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
922}
923
Ady Abraham62a0be22020-12-08 16:54:10 -0800924int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700925 // This calculation needs to be in sync with the java code
926 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200927
928 // The threshold must be smaller than 0.001 in order to differentiate
929 // between the fractional pairs (e.g. 59.94 and 60).
930 constexpr float kThreshold = 0.0009f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800931 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700932 const auto numPeriodsRounded = std::round(numPeriods);
933 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800934 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700935 }
936
Ady Abraham62f216c2020-10-13 19:07:23 -0700937 return static_cast<int>(numPeriodsRounded);
938}
939
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200940bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700941 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200942 return isFractionalPairOrMultiple(bigger, smaller);
943 }
944
945 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
946 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700947 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
948 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200949}
950
Marin Shalamanovba421a82020-11-10 21:49:26 +0100951void RefreshRateConfigs::dump(std::string& result) const {
952 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100953 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100954 mDisplayManagerPolicy.toString().c_str());
955 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
956 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100957 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100958 currentPolicy.toString().c_str());
959 }
960
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100961 auto mode = mCurrentRefreshRate->mode;
962 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100963
964 result.append("Refresh rates:\n");
965 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100966 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +0100967 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
968 }
969
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800970 base::StringAppendF(&result, "Supports Frame Rate Override By Content: %s\n",
971 mSupportsFrameRateOverrideByContent ? "yes" : "no");
Ady Abraham6d885932021-09-03 18:05:48 -0700972 base::StringAppendF(&result, "Idle timer: (%s) %s\n",
973 mConfig.supportKernelIdleTimer ? "kernel" : "platform",
Ady Abraham9a2ea342021-09-03 17:32:34 -0700974 mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100975 result.append("\n");
976}
977
Ady Abraham2139f732019-11-13 18:56:40 -0800978} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100979
980// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800981#pragma clang diagnostic pop // ignored "-Wextra"