blob: ca8349636b20f64569a9327a81742f781832bc70 [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 Laskowskib0054a22022-03-03 09:03:06 -080041struct RefreshRateScore {
42 DisplayModeIterator modeIt;
43 float score;
44};
45
46template <typename Iterator>
47const DisplayModePtr& getMaxScoreRefreshRate(Iterator begin, Iterator end) {
48 const auto it =
49 std::max_element(begin, end, [](RefreshRateScore max, RefreshRateScore current) {
50 const auto& [modeIt, score] = current;
51
52 std::string name = to_string(modeIt->second->getFps());
53 ALOGV("%s scores %.2f", name.c_str(), score);
54
55 ATRACE_INT(name.c_str(), static_cast<int>(std::round(score * 100)));
56
57 constexpr float kEpsilon = 0.0001f;
58 return score > max.score * (1 + kEpsilon);
59 });
60
61 return it->modeIt->second;
62}
63
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080064constexpr RefreshRateConfigs::GlobalSignals kNoSignals;
65
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010066std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080067 return base::StringPrintf("%s (type=%s, weight=%.2f, seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070068 ftl::enum_string(layer.vote).c_str(), weight,
69 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010070 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010071}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010072
Marin Shalamanova7fe3042021-01-29 21:02:08 +010073std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070074 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010075 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010076
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070077 // Add all supported refresh rates.
Dominik Laskowskib0054a22022-03-03 09:03:06 -080078 for (const auto& [id, mode] : modes) {
79 knownFrameRates.push_back(mode->getFps());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010080 }
81
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070082 // Sort and remove duplicates.
83 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010084 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070085 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010086 knownFrameRates.end());
87 return knownFrameRates;
88}
89
Dominik Laskowskib0054a22022-03-03 09:03:06 -080090// The Filter is a `bool(const DisplayMode&)` predicate.
91template <typename Filter>
92std::vector<DisplayModeIterator> sortByRefreshRate(const DisplayModes& modes, Filter&& filter) {
93 std::vector<DisplayModeIterator> sortedModes;
94 sortedModes.reserve(modes.size());
Ady Abraham2139f732019-11-13 18:56:40 -080095
Dominik Laskowskib0054a22022-03-03 09:03:06 -080096 for (auto it = modes.begin(); it != modes.end(); ++it) {
97 const auto& [id, mode] = *it;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080098
Dominik Laskowskib0054a22022-03-03 09:03:06 -080099 if (filter(*mode)) {
100 ALOGV("%s: including mode %d", __func__, id.value());
101 sortedModes.push_back(it);
102 }
103 }
104
105 std::sort(sortedModes.begin(), sortedModes.end(), [](auto it1, auto it2) {
106 const auto& mode1 = it1->second;
107 const auto& mode2 = it2->second;
108
109 if (mode1->getVsyncPeriod() == mode2->getVsyncPeriod()) {
110 return mode1->getGroup() > mode2->getGroup();
111 }
112
113 return mode1->getVsyncPeriod() > mode2->getVsyncPeriod();
114 });
115
116 return sortedModes;
Marin Shalamanov46084422020-10-13 12:33:42 +0200117}
118
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800119bool canModesSupportFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
120 for (const auto it1 : sortedModes) {
121 const auto& mode1 = it1->second;
122 for (const auto it2 : sortedModes) {
123 const auto& mode2 = it2->second;
124
125 if (RefreshRateConfigs::getFrameRateDivisor(mode1->getFps(), mode2->getFps()) >= 2) {
126 return true;
127 }
128 }
129 }
130 return false;
131}
132
133} // namespace
134
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100135std::string RefreshRateConfigs::Policy::toString() const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700136 return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
137 ", primaryRange=%s, appRequestRange=%s}",
138 defaultMode.value(), allowGroupSwitching ? "true" : "false",
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800139 to_string(primaryRange).c_str(), to_string(appRequestRange).c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200140}
141
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800142std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
143 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800144 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
145 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
146 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
147 quotient++;
148 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800149 }
150
Ady Abraham62a0be22020-12-08 16:54:10 -0800151 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800152}
153
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800154bool RefreshRateConfigs::isVoteAllowed(const LayerRequirement& layer, Fps refreshRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700155 using namespace fps_approx_ops;
156
rnlee3bd610662021-06-23 16:27:57 -0700157 switch (layer.vote) {
158 case LayerVoteType::ExplicitExactOrMultiple:
159 case LayerVoteType::Heuristic:
160 if (mConfig.frameRateMultipleThreshold != 0 &&
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800161 refreshRate >= Fps::fromValue(mConfig.frameRateMultipleThreshold) &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700162 layer.desiredRefreshRate < Fps::fromValue(mConfig.frameRateMultipleThreshold / 2)) {
rnlee3bd610662021-06-23 16:27:57 -0700163 // Don't vote high refresh rates past the threshold for layers with a low desired
164 // refresh rate. For example, desired 24 fps with 120 Hz threshold means no vote for
165 // 120 Hz, but desired 60 fps should have a vote.
166 return false;
167 }
168 break;
169 case LayerVoteType::ExplicitDefault:
170 case LayerVoteType::ExplicitExact:
171 case LayerVoteType::Max:
172 case LayerVoteType::Min:
173 case LayerVoteType::NoVote:
174 break;
175 }
176 return true;
177}
178
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800179float RefreshRateConfigs::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
180 Fps refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200181 constexpr float kScoreForFractionalPairs = .8f;
182
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800183 const auto displayPeriod = refreshRate.getPeriodNsecs();
Ady Abraham62a0be22020-12-08 16:54:10 -0800184 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
185 if (layer.vote == LayerVoteType::ExplicitDefault) {
186 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200187 // that layerPeriod is the minimal period to render a frame.
188 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
189 // then the actualLayerPeriod will be 32ms, because it is the
190 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800191 auto actualLayerPeriod = displayPeriod;
192 int multiplier = 1;
193 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
194 multiplier++;
195 actualLayerPeriod = displayPeriod * multiplier;
196 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200197
198 // Because of the threshold we used above it's possible that score is slightly
199 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800200 return std::min(1.0f,
201 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
202 }
203
204 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
205 layer.vote == LayerVoteType::Heuristic) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800206 if (isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700207 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200208 }
209
Ady Abraham62a0be22020-12-08 16:54:10 -0800210 // Calculate how many display vsyncs we need to present a single frame for this
211 // layer
212 const auto [displayFramesQuotient, displayFramesRemainder] =
213 getDisplayFrames(layerPeriod, displayPeriod);
214 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
215 if (displayFramesRemainder == 0) {
216 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700217 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800218 }
219
220 if (displayFramesQuotient == 0) {
221 // Layer desired refresh rate is higher than the display rate.
222 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
223 (1.0f / (MAX_FRAMES_TO_FIT + 1));
224 }
225
226 // Layer desired refresh rate is lower than the display rate. Check how well it fits
227 // the cadence.
228 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
229 int iter = 2;
230 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
231 diff = diff - (displayPeriod - diff);
232 iter++;
233 }
234
Ady Abraham05243be2021-09-16 15:58:52 -0700235 return (1.0f / iter);
236 }
237
238 return 0;
239}
240
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800241float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
Ady Abraham05243be2021-09-16 15:58:52 -0700242 bool isSeamlessSwitch) const {
243 if (!isVoteAllowed(layer, refreshRate)) {
244 return 0;
245 }
246
247 // Slightly prefer seamless switches.
248 constexpr float kSeamedSwitchPenalty = 0.95f;
249 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
250
251 // If the layer wants Max, give higher score to the higher refresh rate
252 if (layer.vote == LayerVoteType::Max) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800253 const auto& maxRefreshRate = mAppRequestRefreshRates.back()->second;
254 const auto ratio = refreshRate.getValue() / maxRefreshRate->getFps().getValue();
Ady Abraham05243be2021-09-16 15:58:52 -0700255 // use ratio^2 to get a lower score the more we get further from peak
256 return ratio * ratio;
Ady Abraham62a0be22020-12-08 16:54:10 -0800257 }
258
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800259 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800260 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800261 if (mSupportsFrameRateOverrideByContent) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800262 // Since we support frame rate override, allow refresh rates which are
263 // multiples of the layer's request, as those apps would be throttled
264 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800265 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800266 }
267
Ady Abrahamcc315492022-02-17 17:06:39 -0800268 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800269 }
270
Ady Abrahamcc315492022-02-17 17:06:39 -0800271 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700272 // the highest score.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800273 if (getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700274 return 1.0f * seamlessness;
275 }
276
Ady Abrahamcc315492022-02-17 17:06:39 -0800277 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700278 // there is a small penalty attached to the score to favor the frame rates
279 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800280 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700281 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
282 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800283}
284
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800285auto RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
286 GlobalSignals signals) const
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800287 -> std::pair<DisplayModePtr, GlobalSignals> {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200288 std::lock_guard lock(mLock);
289
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800290 if (mGetBestRefreshRateCache &&
291 mGetBestRefreshRateCache->arguments == std::make_pair(layers, signals)) {
292 return mGetBestRefreshRateCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200293 }
294
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800295 const auto result = getBestRefreshRateLocked(layers, signals);
296 mGetBestRefreshRateCache = GetBestRefreshRateCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200297 return result;
298}
299
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800300auto RefreshRateConfigs::getBestRefreshRateLocked(const std::vector<LayerRequirement>& layers,
301 GlobalSignals signals) const
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800302 -> std::pair<DisplayModePtr, GlobalSignals> {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800303 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800304 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700305
Ady Abraham8a82ba62020-01-17 12:43:17 -0800306 int noVoteLayers = 0;
307 int minVoteLayers = 0;
308 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800309 int explicitDefaultVoteLayers = 0;
310 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800311 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800312 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100313 int seamedFocusedLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800314
Ady Abraham8a82ba62020-01-17 12:43:17 -0800315 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800316 switch (layer.vote) {
317 case LayerVoteType::NoVote:
318 noVoteLayers++;
319 break;
320 case LayerVoteType::Min:
321 minVoteLayers++;
322 break;
323 case LayerVoteType::Max:
324 maxVoteLayers++;
325 break;
326 case LayerVoteType::ExplicitDefault:
327 explicitDefaultVoteLayers++;
328 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
329 break;
330 case LayerVoteType::ExplicitExactOrMultiple:
331 explicitExactOrMultipleVoteLayers++;
332 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
333 break;
334 case LayerVoteType::ExplicitExact:
335 explicitExact++;
336 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
337 break;
338 case LayerVoteType::Heuristic:
339 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800340 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200341
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100342 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
343 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200344 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800345 }
346
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800347 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
348 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700349
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200350 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800351 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200352 // If the default mode group is different from the group of current mode,
353 // this means a layer requesting a seamed mode switch just disappeared and
354 // we should switch back to the default group.
355 // However if a seamed layer is still present we anchor around the group
356 // of the current mode, in order to prevent unnecessary seamed mode switches
357 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800358 const auto anchorGroup =
359 seamedFocusedLayers > 0 ? mActiveModeIt->second->getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200360
Steven Thomasf734df42020-04-13 21:09:28 -0700361 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
362 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800363 if (signals.touch && !hasExplicitVoteLayers) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800364 const DisplayModePtr& max = getMaxRefreshRateByPolicyLocked(anchorGroup);
365 ALOGV("TouchBoost - choose %s", to_string(max->getFps()).c_str());
366 return {max, GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800367 }
368
Alec Mouri11232a22020-05-14 18:06:25 -0700369 // If the primary range consists of a single refresh rate then we can only
370 // move out the of range if layers explicitly request a different refresh
371 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100372 const bool primaryRangeIsSingleRate =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700373 isApproxEqual(policy->primaryRange.min, policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700374
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800375 if (!signals.touch && signals.idle && !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800376 const DisplayModePtr& min = getMinRefreshRateByPolicyLocked();
377 ALOGV("Idle - choose %s", to_string(min->getFps()).c_str());
378 return {min, GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700379 }
380
Steven Thomasdebafed2020-05-18 17:30:35 -0700381 if (layers.empty() || noVoteLayers == layers.size()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800382 const DisplayModePtr& max = getMaxRefreshRateByPolicyLocked(anchorGroup);
383 ALOGV("no layers with votes - choose %s", to_string(max->getFps()).c_str());
384 return {max, kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700385 }
386
Ady Abraham8a82ba62020-01-17 12:43:17 -0800387 // Only if all layers want Min we should return Min
388 if (noVoteLayers + minVoteLayers == layers.size()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800389 const DisplayModePtr& min = getMinRefreshRateByPolicyLocked();
390 ALOGV("all layers Min - choose %s", to_string(min->getFps()).c_str());
391 return {min, kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800392 }
393
Ady Abraham8a82ba62020-01-17 12:43:17 -0800394 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800395 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700396 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800397
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800398 for (const DisplayModeIterator modeIt : mAppRequestRefreshRates) {
399 scores.emplace_back(RefreshRateScore{modeIt, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800400 }
401
402 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700403 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700404 ftl::enum_string(layer.vote).c_str(), layer.weight,
rnlee3bd610662021-06-23 16:27:57 -0700405 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800406 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800407 continue;
408 }
409
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800410 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800411
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800412 for (auto& [modeIt, score] : scores) {
413 const auto& [id, mode] = *modeIt;
414 const bool isSeamlessSwitch = mode->getGroup() == mActiveModeIt->second->getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200415
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100416 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100417 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800418 formatLayerInfo(layer, weight).c_str(), to_string(*mode).c_str(),
419 to_string(*mActiveModeIt->second).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200420 continue;
421 }
422
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100423 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
424 !layer.focused) {
425 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100426 " Current mode = %s",
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800427 formatLayerInfo(layer, weight).c_str(), to_string(*mode).c_str(),
428 to_string(*mActiveModeIt->second).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100429 continue;
430 }
431
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100432 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100433 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100434 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100435 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
436 // disappeared.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800437 const bool isInPolicyForDefault = mode->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100438 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100439 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800440 to_string(*mode).c_str(), to_string(*mActiveModeIt->second).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200441 continue;
442 }
443
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800444 const bool inPrimaryRange = policy->primaryRange.includes(mode->getFps());
Alec Mouri11232a22020-05-14 18:06:25 -0700445 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800446 !(layer.focused &&
447 (layer.vote == LayerVoteType::ExplicitDefault ||
448 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700449 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700450 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700451 continue;
452 }
453
Ady Abraham62a0be22020-12-08 16:54:10 -0800454 const auto layerScore =
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800455 calculateLayerScoreLocked(layer, mode->getFps(), isSeamlessSwitch);
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200456 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800457 to_string(mode->getFps()).c_str(), layerScore);
458
459 score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800460 }
461 }
462
Ady Abraham34702102020-02-10 14:12:05 -0800463 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
464 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
465 // or the lower otherwise.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800466 const DisplayModePtr& bestRefreshRate = maxVoteLayers > 0
467 ? getMaxScoreRefreshRate(scores.rbegin(), scores.rend())
468 : getMaxScoreRefreshRate(scores.begin(), scores.end());
Ady Abraham34702102020-02-10 14:12:05 -0800469
Alec Mouri11232a22020-05-14 18:06:25 -0700470 if (primaryRangeIsSingleRate) {
471 // If we never scored any layers, then choose the rate from the primary
472 // range instead of picking a random score from the app range.
473 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800474 [](RefreshRateScore score) { return score.score == 0; })) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800475 const DisplayModePtr& max = getMaxRefreshRateByPolicyLocked(anchorGroup);
476 ALOGV("layers not scored - choose %s", to_string(max->getFps()).c_str());
477 return {max, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700478 } else {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800479 return {bestRefreshRate, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700480 }
481 }
482
Steven Thomasf734df42020-04-13 21:09:28 -0700483 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
484 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
485 // vote we should not change it if we get a touch event. Only apply touch boost if it will
486 // actually increase the refresh rate over the normal selection.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800487 const DisplayModePtr& touchRefreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
Alec Mouri11232a22020-05-14 18:06:25 -0700488
Ady Abraham5e4e9832021-06-14 13:40:56 -0700489 const bool touchBoostForExplicitExact = [&] {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800490 if (mSupportsFrameRateOverrideByContent) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700491 // Enable touch boost if there are other layers besides exact
492 return explicitExact + noVoteLayers != layers.size();
493 } else {
494 // Enable touch boost if there are no exact layers
495 return explicitExact == 0;
496 }
497 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700498
499 using fps_approx_ops::operator<;
500
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800501 if (signals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800502 bestRefreshRate->getFps() < touchRefreshRate->getFps()) {
503 ALOGV("TouchBoost - choose %s", to_string(touchRefreshRate->getFps()).c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800504 return {touchRefreshRate, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700505 }
506
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800507 return {bestRefreshRate, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800508}
509
Ady Abraham62a0be22020-12-08 16:54:10 -0800510std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
511groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
512 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
513 for (const auto& layer : layers) {
514 auto iter = layersByUid.emplace(layer.ownerUid,
515 std::vector<const RefreshRateConfigs::LayerRequirement*>());
516 auto& layersWithSameUid = iter.first->second;
517 layersWithSameUid.push_back(&layer);
518 }
519
520 // Remove uids that can't have a frame rate override
521 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
522 const auto& layersWithSameUid = iter->second;
523 bool skipUid = false;
524 for (const auto& layer : layersWithSameUid) {
525 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
526 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
527 skipUid = true;
528 break;
529 }
530 }
531 if (skipUid) {
532 iter = layersByUid.erase(iter);
533 } else {
534 ++iter;
535 }
536 }
537
538 return layersByUid;
539}
540
Ady Abraham62a0be22020-12-08 16:54:10 -0800541RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800542 const std::vector<LayerRequirement>& layers, Fps displayRefreshRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700543 GlobalSignals globalSignals) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800544 ATRACE_CALL();
Ady Abraham62a0be22020-12-08 16:54:10 -0800545
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800546 ALOGV("%s: %zu layers", __func__, layers.size());
547
Ady Abraham62a0be22020-12-08 16:54:10 -0800548 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800549
550 std::vector<RefreshRateScore> scores;
551 scores.reserve(mDisplayModes.size());
552
553 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
554 scores.emplace_back(RefreshRateScore{it, 0.0f});
555 }
556
557 std::sort(scores.begin(), scores.end(), [](const auto& lhs, const auto& rhs) {
558 const auto& mode1 = lhs.modeIt->second;
559 const auto& mode2 = rhs.modeIt->second;
560 return isStrictlyLess(mode1->getFps(), mode2->getFps());
561 });
562
Ady Abraham62a0be22020-12-08 16:54:10 -0800563 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
564 groupLayersByUid(layers);
565 UidToFrameRateOverride frameRateOverrides;
566 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800567 // Layers with ExplicitExactOrMultiple expect touch boost
568 const bool hasExplicitExactOrMultiple =
569 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
570 [](const auto& layer) {
571 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
572 });
573
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700574 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800575 continue;
576 }
577
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800578 for (auto& [_, score] : scores) {
579 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -0800580 }
581
582 for (const auto& layer : layersWithSameUid) {
583 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
584 continue;
585 }
586
587 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800588 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
589 layer->vote != LayerVoteType::ExplicitExact);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800590 for (auto& [modeIt, score] : scores) {
591 constexpr bool isSeamlessSwitch = true;
592 const auto layerScore = calculateLayerScoreLocked(*layer, modeIt->second->getFps(),
593 isSeamlessSwitch);
594 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -0800595 }
596 }
597
Ady Abrahamcc315492022-02-17 17:06:39 -0800598 // We just care about the refresh rates which are a divisor of the
Ady Abraham62a0be22020-12-08 16:54:10 -0800599 // display refresh rate
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800600 const auto it = std::remove_if(scores.begin(), scores.end(), [&](RefreshRateScore score) {
601 const auto& [id, mode] = *score.modeIt;
602 return getFrameRateDivisor(displayRefreshRate, mode->getFps()) == 0;
603 });
604 scores.erase(it, scores.end());
Ady Abraham62a0be22020-12-08 16:54:10 -0800605
606 // If we never scored any layers, we don't have a preferred frame rate
607 if (std::all_of(scores.begin(), scores.end(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800608 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800609 continue;
610 }
611
612 // Now that we scored all the refresh rates we need to pick the one that got the highest
613 // score.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800614 const DisplayModePtr& bestRefreshRate =
615 getMaxScoreRefreshRate(scores.begin(), scores.end());
616
Ady Abraham5cc2e262021-03-25 13:09:17 -0700617 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800618 }
619
620 return frameRateOverrides;
621}
622
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100623std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800624 std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800625 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100626
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800627 const DisplayModePtr& current = desiredActiveModeId
628 ? mDisplayModes.get(*desiredActiveModeId)->get()
629 : mActiveModeIt->second;
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100630
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800631 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
632 if (current == min) {
633 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100634 }
635
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800636 const auto& mode = timerExpired ? min : current;
637 return mode->getFps();
Steven Thomasf734df42020-04-13 21:09:28 -0700638}
639
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800640const DisplayModePtr& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
641 for (const DisplayModeIterator modeIt : mPrimaryRefreshRates) {
642 const auto& mode = modeIt->second;
643 if (mActiveModeIt->second->getGroup() == mode->getGroup()) {
644 return mode;
Marin Shalamanov46084422020-10-13 12:33:42 +0200645 }
646 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800647
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100648 ALOGE("Can't find min refresh rate by policy with the same mode group"
649 " as the current mode %s",
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800650 to_string(*mActiveModeIt->second).c_str());
651
652 // Default to the lowest refresh rate.
653 return mPrimaryRefreshRates.front()->second;
Ady Abraham2139f732019-11-13 18:56:40 -0800654}
655
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800656DisplayModePtr RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800657 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700658 return getMaxRefreshRateByPolicyLocked();
659}
660
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800661const DisplayModePtr& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
662 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); ++it) {
663 const auto& mode = (*it)->second;
664 if (anchorGroup == mode->getGroup()) {
665 return mode;
Marin Shalamanov46084422020-10-13 12:33:42 +0200666 }
667 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800668
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100669 ALOGE("Can't find max refresh rate by policy with the same mode group"
670 " as the current mode %s",
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800671 to_string(*mActiveModeIt->second).c_str());
672
673 // Default to the highest refresh rate.
674 return mPrimaryRefreshRates.back()->second;
Ady Abraham2139f732019-11-13 18:56:40 -0800675}
676
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800677DisplayModePtr RefreshRateConfigs::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800678 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800679 return mActiveModeIt->second;
Ady Abraham2139f732019-11-13 18:56:40 -0800680}
681
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800682void RefreshRateConfigs::setActiveModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800683 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200684
685 // Invalidate the cached invocation to getBestRefreshRate. This forces
686 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800687 mGetBestRefreshRateCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200688
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800689 mActiveModeIt = mDisplayModes.find(modeId);
690 LOG_ALWAYS_FATAL_IF(mActiveModeIt == mDisplayModes.end());
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800691}
692
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800693RefreshRateConfigs::RefreshRateConfigs(DisplayModes modes, DisplayModeId activeModeId,
rnlee3bd610662021-06-23 16:27:57 -0700694 Config config)
695 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700696 initializeIdleTimer();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800697 updateDisplayModes(std::move(modes), activeModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100698}
699
Ady Abraham9a2ea342021-09-03 17:32:34 -0700700void RefreshRateConfigs::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +0000701 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700702 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +0000703 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800704 [this] {
705 std::scoped_lock lock(mIdleTimerCallbacksMutex);
706 if (const auto callbacks = getIdleTimerCallbacks()) {
707 callbacks->onReset();
708 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700709 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800710 [this] {
711 std::scoped_lock lock(mIdleTimerCallbacksMutex);
712 if (const auto callbacks = getIdleTimerCallbacks()) {
713 callbacks->onExpired();
714 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700715 });
Ady Abraham9a2ea342021-09-03 17:32:34 -0700716 }
717}
718
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800719void RefreshRateConfigs::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100720 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200721
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200722 // Invalidate the cached invocation to getBestRefreshRate. This forces
723 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800724 mGetBestRefreshRateCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200725
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800726 mDisplayModes = std::move(modes);
727 mActiveModeIt = mDisplayModes.find(activeModeId);
728 LOG_ALWAYS_FATAL_IF(mActiveModeIt == mDisplayModes.end());
Ady Abrahamabc27602020-04-08 17:20:29 -0700729
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800730 const auto sortedModes =
731 sortByRefreshRate(mDisplayModes, [](const DisplayMode&) { return true; });
732 mMinRefreshRateModeIt = sortedModes.front();
733 mMaxRefreshRateModeIt = sortedModes.back();
734
Marin Shalamanov75f37252021-02-10 21:43:57 +0100735 // Reset the policy because the old one may no longer be valid.
736 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800737 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -0800738
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800739 mSupportsFrameRateOverrideByContent =
740 mConfig.enableFrameRateOverride && canModesSupportFrameRateOverride(sortedModes);
Ady Abraham4899ff82021-01-06 13:53:29 -0800741
Ady Abrahamabc27602020-04-08 17:20:29 -0700742 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800743}
744
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100745bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100746 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800747 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
748 if (!policy.primaryRange.includes(mode->get()->getFps())) {
749 ALOGE("Default mode is not in the primary range.");
750 return false;
751 }
752 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100753 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700754 return false;
755 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700756
757 using namespace fps_approx_ops;
758 return policy.appRequestRange.min <= policy.primaryRange.min &&
759 policy.appRequestRange.max >= policy.primaryRange.max;
Steven Thomasd4071902020-03-24 16:02:53 -0700760}
761
762status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800763 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100764 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100765 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100766 return BAD_VALUE;
767 }
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800768 mGetBestRefreshRateCache.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700769 Policy previousPolicy = *getCurrentPolicyLocked();
770 mDisplayManagerPolicy = policy;
771 if (*getCurrentPolicyLocked() == previousPolicy) {
772 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100773 }
Ady Abraham2139f732019-11-13 18:56:40 -0800774 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100775 return NO_ERROR;
776}
777
Steven Thomasd4071902020-03-24 16:02:53 -0700778status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100779 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100780 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700781 return BAD_VALUE;
782 }
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800783 mGetBestRefreshRateCache.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700784 Policy previousPolicy = *getCurrentPolicyLocked();
785 mOverridePolicy = policy;
786 if (*getCurrentPolicyLocked() == previousPolicy) {
787 return CURRENT_POLICY_UNCHANGED;
788 }
789 constructAvailableRefreshRates();
790 return NO_ERROR;
791}
792
793const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
794 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
795}
796
797RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
798 std::lock_guard lock(mLock);
799 return *getCurrentPolicyLocked();
800}
801
802RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
803 std::lock_guard lock(mLock);
804 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100805}
806
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100807bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100808 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800809 return std::any_of(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
810 [modeId](DisplayModeIterator modeIt) {
811 return modeIt->second->getId() == modeId;
812 });
Ady Abraham2139f732019-11-13 18:56:40 -0800813}
814
815void RefreshRateConfigs::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800816 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -0700817 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800818 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700819
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800820 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800821
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800822 const auto filterRefreshRates = [&](FpsRange range, const char* rangeName) REQUIRES(mLock) {
823 const auto filter = [&](const DisplayMode& mode) {
824 return mode.getResolution() == defaultMode->getResolution() &&
825 mode.getDpi() == defaultMode->getDpi() &&
826 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
827 range.includes(mode.getFps());
828 };
Ady Abraham8a82ba62020-01-17 12:43:17 -0800829
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800830 const auto modes = sortByRefreshRate(mDisplayModes, filter);
831 LOG_ALWAYS_FATAL_IF(modes.empty(), "No matching modes for %s range %s", rangeName,
832 to_string(range).c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800833
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800834 const auto stringifyModes = [&] {
835 std::string str;
836 for (const auto modeIt : modes) {
837 str += to_string(modeIt->second->getFps());
838 str.push_back(' ');
839 }
840 return str;
841 };
842 ALOGV("%s refresh rates: %s", rangeName, stringifyModes().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700843
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800844 return modes;
845 };
846
847 mPrimaryRefreshRates = filterRefreshRates(policy->primaryRange, "primary");
848 mAppRequestRefreshRates = filterRefreshRates(policy->appRequestRange, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -0800849}
850
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100851Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700852 using namespace fps_approx_ops;
853
854 if (frameRate <= mKnownFrameRates.front()) {
855 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700856 }
857
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700858 if (frameRate >= mKnownFrameRates.back()) {
859 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700860 }
861
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100862 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700863 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700864
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700865 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
866 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700867 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
868}
869
Ana Krulecb9afd792020-06-11 13:16:15 -0700870RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
871 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800872
873 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getFps();
874 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700875
876 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
877 // the min allowed refresh rate is higher than the device min, we do not want to enable the
878 // timer.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800879 if (isStrictlyLess(deviceMinFps, minByPolicy->getFps())) {
880 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -0700881 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800882
883 const DisplayModePtr& maxByPolicy = getMaxRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700884 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800885 // Turn on the timer when the min of the primary range is below the device min.
886 if (const Policy* currentPolicy = getCurrentPolicyLocked();
887 isApproxLess(currentPolicy->primaryRange.min, deviceMinFps)) {
888 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700889 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800890 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -0700891 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800892
Ana Krulecb9afd792020-06-11 13:16:15 -0700893 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800894 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700895}
896
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800897int RefreshRateConfigs::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700898 // This calculation needs to be in sync with the java code
899 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200900
901 // The threshold must be smaller than 0.001 in order to differentiate
902 // between the fractional pairs (e.g. 59.94 and 60).
903 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800904 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700905 const auto numPeriodsRounded = std::round(numPeriods);
906 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800907 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700908 }
909
Ady Abraham62f216c2020-10-13 19:07:23 -0700910 return static_cast<int>(numPeriodsRounded);
911}
912
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200913bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700914 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200915 return isFractionalPairOrMultiple(bigger, smaller);
916 }
917
918 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
919 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700920 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
921 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200922}
923
Marin Shalamanovba421a82020-11-10 21:49:26 +0100924void RefreshRateConfigs::dump(std::string& result) const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700925 using namespace std::string_literals;
926
Marin Shalamanovba421a82020-11-10 21:49:26 +0100927 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +0100928
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700929 const auto activeModeId = mActiveModeIt->first;
930 result += " activeModeId="s;
931 result += std::to_string(activeModeId.value());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100932
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700933 result += "\n displayModes=\n"s;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800934 for (const auto& [id, mode] : mDisplayModes) {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700935 result += " "s;
936 result += to_string(*mode);
937 result += '\n';
Marin Shalamanovba421a82020-11-10 21:49:26 +0100938 }
939
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700940 base::StringAppendF(&result, " displayManagerPolicy=%s\n",
941 mDisplayManagerPolicy.toString().c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800942
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700943 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
944 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
945 base::StringAppendF(&result, " overridePolicy=%s\n", currentPolicy.toString().c_str());
ramindani32cf0602022-03-02 02:30:29 +0000946 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800947
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700948 base::StringAppendF(&result, " supportsFrameRateOverrideByContent=%s\n",
949 mSupportsFrameRateOverrideByContent ? "true" : "false");
950
951 result += " idleTimer="s;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800952 if (mIdleTimer) {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700953 result += mIdleTimer->dump();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800954 } else {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700955 result += "off"s;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800956 }
957
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700958 if (const auto controller = mConfig.kernelIdleTimerController) {
959 base::StringAppendF(&result, " (kernel via %s)", ftl::enum_string(*controller).c_str());
960 } else {
961 result += " (platform)"s;
962 }
963
964 result += '\n';
Marin Shalamanovba421a82020-11-10 21:49:26 +0100965}
966
ramindani32cf0602022-03-02 02:30:29 +0000967std::chrono::milliseconds RefreshRateConfigs::getIdleTimerTimeout() {
968 return mConfig.idleTimerTimeout;
969}
970
Ady Abraham2139f732019-11-13 18:56:40 -0800971} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100972
973// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800974#pragma clang diagnostic pop // ignored "-Wextra"