blob: a48c92137885249bc30a69e110431cd621f8d5d9 [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;
Ady Abrahamae2e3c72022-08-13 05:12:13 +000043 float overallScore;
44 struct {
Ady Abraham62f51d92022-08-24 22:20:22 +000045 float modeBelowThreshold;
46 float modeAboveThreshold;
47 } fixedRateBelowThresholdLayersScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -080048};
49
50template <typename Iterator>
51const DisplayModePtr& getMaxScoreRefreshRate(Iterator begin, Iterator end) {
52 const auto it =
53 std::max_element(begin, end, [](RefreshRateScore max, RefreshRateScore current) {
Ady Abrahamae2e3c72022-08-13 05:12:13 +000054 const auto& [modeIt, overallScore, _] = current;
Dominik Laskowskib0054a22022-03-03 09:03:06 -080055
56 std::string name = to_string(modeIt->second->getFps());
Ady Abrahamae2e3c72022-08-13 05:12:13 +000057 ALOGV("%s scores %.2f", name.c_str(), overallScore);
Dominik Laskowskib0054a22022-03-03 09:03:06 -080058
Ady Abrahamae2e3c72022-08-13 05:12:13 +000059 ATRACE_INT(name.c_str(), static_cast<int>(std::round(overallScore * 100)));
Dominik Laskowskib0054a22022-03-03 09:03:06 -080060
61 constexpr float kEpsilon = 0.0001f;
Ady Abrahamae2e3c72022-08-13 05:12:13 +000062 return overallScore > max.overallScore * (1 + kEpsilon);
Dominik Laskowskib0054a22022-03-03 09:03:06 -080063 });
64
65 return it->modeIt->second;
66}
67
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080068constexpr RefreshRateConfigs::GlobalSignals kNoSignals;
69
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010070std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080071 return base::StringPrintf("%s (type=%s, weight=%.2f, seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070072 ftl::enum_string(layer.vote).c_str(), weight,
73 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010074 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010075}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010076
Marin Shalamanova7fe3042021-01-29 21:02:08 +010077std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070078 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010079 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010080
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070081 // Add all supported refresh rates.
Dominik Laskowskib0054a22022-03-03 09:03:06 -080082 for (const auto& [id, mode] : modes) {
83 knownFrameRates.push_back(mode->getFps());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010084 }
85
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070086 // Sort and remove duplicates.
87 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010088 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070089 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010090 knownFrameRates.end());
91 return knownFrameRates;
92}
93
Dominik Laskowskib0054a22022-03-03 09:03:06 -080094// The Filter is a `bool(const DisplayMode&)` predicate.
95template <typename Filter>
96std::vector<DisplayModeIterator> sortByRefreshRate(const DisplayModes& modes, Filter&& filter) {
97 std::vector<DisplayModeIterator> sortedModes;
98 sortedModes.reserve(modes.size());
Ady Abraham2139f732019-11-13 18:56:40 -080099
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800100 for (auto it = modes.begin(); it != modes.end(); ++it) {
101 const auto& [id, mode] = *it;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800102
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800103 if (filter(*mode)) {
104 ALOGV("%s: including mode %d", __func__, id.value());
105 sortedModes.push_back(it);
106 }
107 }
108
109 std::sort(sortedModes.begin(), sortedModes.end(), [](auto it1, auto it2) {
110 const auto& mode1 = it1->second;
111 const auto& mode2 = it2->second;
112
113 if (mode1->getVsyncPeriod() == mode2->getVsyncPeriod()) {
114 return mode1->getGroup() > mode2->getGroup();
115 }
116
117 return mode1->getVsyncPeriod() > mode2->getVsyncPeriod();
118 });
119
120 return sortedModes;
Marin Shalamanov46084422020-10-13 12:33:42 +0200121}
122
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800123bool canModesSupportFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
124 for (const auto it1 : sortedModes) {
125 const auto& mode1 = it1->second;
126 for (const auto it2 : sortedModes) {
127 const auto& mode2 = it2->second;
128
129 if (RefreshRateConfigs::getFrameRateDivisor(mode1->getFps(), mode2->getFps()) >= 2) {
130 return true;
131 }
132 }
133 }
134 return false;
135}
136
137} // namespace
138
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100139std::string RefreshRateConfigs::Policy::toString() const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700140 return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
141 ", primaryRange=%s, appRequestRange=%s}",
142 defaultMode.value(), allowGroupSwitching ? "true" : "false",
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800143 to_string(primaryRange).c_str(), to_string(appRequestRange).c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200144}
145
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800146std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
147 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800148 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
149 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
150 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
151 quotient++;
152 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800153 }
154
Ady Abraham62a0be22020-12-08 16:54:10 -0800155 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800156}
157
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800158float RefreshRateConfigs::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
159 Fps refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200160 constexpr float kScoreForFractionalPairs = .8f;
161
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800162 const auto displayPeriod = refreshRate.getPeriodNsecs();
Ady Abraham62a0be22020-12-08 16:54:10 -0800163 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
164 if (layer.vote == LayerVoteType::ExplicitDefault) {
165 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200166 // that layerPeriod is the minimal period to render a frame.
167 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
168 // then the actualLayerPeriod will be 32ms, because it is the
169 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800170 auto actualLayerPeriod = displayPeriod;
171 int multiplier = 1;
172 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
173 multiplier++;
174 actualLayerPeriod = displayPeriod * multiplier;
175 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200176
177 // Because of the threshold we used above it's possible that score is slightly
178 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800179 return std::min(1.0f,
180 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
181 }
182
183 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
184 layer.vote == LayerVoteType::Heuristic) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800185 if (isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700186 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200187 }
188
Ady Abraham62a0be22020-12-08 16:54:10 -0800189 // Calculate how many display vsyncs we need to present a single frame for this
190 // layer
191 const auto [displayFramesQuotient, displayFramesRemainder] =
192 getDisplayFrames(layerPeriod, displayPeriod);
193 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
194 if (displayFramesRemainder == 0) {
195 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700196 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800197 }
198
199 if (displayFramesQuotient == 0) {
200 // Layer desired refresh rate is higher than the display rate.
201 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
202 (1.0f / (MAX_FRAMES_TO_FIT + 1));
203 }
204
205 // Layer desired refresh rate is lower than the display rate. Check how well it fits
206 // the cadence.
207 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
208 int iter = 2;
209 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
210 diff = diff - (displayPeriod - diff);
211 iter++;
212 }
213
Ady Abraham05243be2021-09-16 15:58:52 -0700214 return (1.0f / iter);
215 }
216
217 return 0;
218}
219
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800220float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
Ady Abraham05243be2021-09-16 15:58:52 -0700221 bool isSeamlessSwitch) const {
Ady Abraham05243be2021-09-16 15:58:52 -0700222 // Slightly prefer seamless switches.
223 constexpr float kSeamedSwitchPenalty = 0.95f;
224 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
225
226 // If the layer wants Max, give higher score to the higher refresh rate
227 if (layer.vote == LayerVoteType::Max) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800228 const auto& maxRefreshRate = mAppRequestRefreshRates.back()->second;
229 const auto ratio = refreshRate.getValue() / maxRefreshRate->getFps().getValue();
Ady Abraham05243be2021-09-16 15:58:52 -0700230 // use ratio^2 to get a lower score the more we get further from peak
231 return ratio * ratio;
Ady Abraham62a0be22020-12-08 16:54:10 -0800232 }
233
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800234 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800235 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800236 if (mSupportsFrameRateOverrideByContent) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800237 // Since we support frame rate override, allow refresh rates which are
238 // multiples of the layer's request, as those apps would be throttled
239 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800240 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800241 }
242
Ady Abrahamcc315492022-02-17 17:06:39 -0800243 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800244 }
245
Ady Abrahamcc315492022-02-17 17:06:39 -0800246 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700247 // the highest score.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800248 if (getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700249 return 1.0f * seamlessness;
250 }
251
Ady Abrahamcc315492022-02-17 17:06:39 -0800252 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700253 // there is a small penalty attached to the score to favor the frame rates
254 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800255 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700256 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
257 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800258}
259
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800260auto RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
261 GlobalSignals signals) const
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800262 -> std::pair<DisplayModePtr, GlobalSignals> {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200263 std::lock_guard lock(mLock);
264
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800265 if (mGetBestRefreshRateCache &&
266 mGetBestRefreshRateCache->arguments == std::make_pair(layers, signals)) {
267 return mGetBestRefreshRateCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200268 }
269
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800270 const auto result = getBestRefreshRateLocked(layers, signals);
271 mGetBestRefreshRateCache = GetBestRefreshRateCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200272 return result;
273}
274
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800275auto RefreshRateConfigs::getBestRefreshRateLocked(const std::vector<LayerRequirement>& layers,
276 GlobalSignals signals) const
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800277 -> std::pair<DisplayModePtr, GlobalSignals> {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000278 using namespace fps_approx_ops;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800279 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800280 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700281
Ady Abraham8a82ba62020-01-17 12:43:17 -0800282 int noVoteLayers = 0;
283 int minVoteLayers = 0;
284 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800285 int explicitDefaultVoteLayers = 0;
286 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800287 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800288 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100289 int seamedFocusedLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800290
Ady Abraham8a82ba62020-01-17 12:43:17 -0800291 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800292 switch (layer.vote) {
293 case LayerVoteType::NoVote:
294 noVoteLayers++;
295 break;
296 case LayerVoteType::Min:
297 minVoteLayers++;
298 break;
299 case LayerVoteType::Max:
300 maxVoteLayers++;
301 break;
302 case LayerVoteType::ExplicitDefault:
303 explicitDefaultVoteLayers++;
304 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
305 break;
306 case LayerVoteType::ExplicitExactOrMultiple:
307 explicitExactOrMultipleVoteLayers++;
308 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
309 break;
310 case LayerVoteType::ExplicitExact:
311 explicitExact++;
312 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
313 break;
314 case LayerVoteType::Heuristic:
315 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800316 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200317
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100318 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
319 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200320 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800321 }
322
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800323 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
324 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700325
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200326 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800327 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200328 // If the default mode group is different from the group of current mode,
329 // this means a layer requesting a seamed mode switch just disappeared and
330 // we should switch back to the default group.
331 // However if a seamed layer is still present we anchor around the group
332 // of the current mode, in order to prevent unnecessary seamed mode switches
333 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800334 const auto anchorGroup =
335 seamedFocusedLayers > 0 ? mActiveModeIt->second->getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200336
Steven Thomasf734df42020-04-13 21:09:28 -0700337 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
338 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800339 if (signals.touch && !hasExplicitVoteLayers) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800340 const DisplayModePtr& max = getMaxRefreshRateByPolicyLocked(anchorGroup);
341 ALOGV("TouchBoost - choose %s", to_string(max->getFps()).c_str());
342 return {max, GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800343 }
344
Alec Mouri11232a22020-05-14 18:06:25 -0700345 // If the primary range consists of a single refresh rate then we can only
346 // move out the of range if layers explicitly request a different refresh
347 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100348 const bool primaryRangeIsSingleRate =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700349 isApproxEqual(policy->primaryRange.min, policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700350
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800351 if (!signals.touch && signals.idle && !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800352 const DisplayModePtr& min = getMinRefreshRateByPolicyLocked();
353 ALOGV("Idle - choose %s", to_string(min->getFps()).c_str());
354 return {min, GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700355 }
356
Steven Thomasdebafed2020-05-18 17:30:35 -0700357 if (layers.empty() || noVoteLayers == layers.size()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800358 const DisplayModePtr& max = getMaxRefreshRateByPolicyLocked(anchorGroup);
359 ALOGV("no layers with votes - choose %s", to_string(max->getFps()).c_str());
360 return {max, kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700361 }
362
Ady Abraham8a82ba62020-01-17 12:43:17 -0800363 // Only if all layers want Min we should return Min
364 if (noVoteLayers + minVoteLayers == layers.size()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800365 const DisplayModePtr& min = getMinRefreshRateByPolicyLocked();
366 ALOGV("all layers Min - choose %s", to_string(min->getFps()).c_str());
367 return {min, kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800368 }
369
Ady Abraham8a82ba62020-01-17 12:43:17 -0800370 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800371 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700372 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800373
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800374 for (const DisplayModeIterator modeIt : mAppRequestRefreshRates) {
375 scores.emplace_back(RefreshRateScore{modeIt, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800376 }
377
378 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700379 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700380 ftl::enum_string(layer.vote).c_str(), layer.weight,
rnlee3bd610662021-06-23 16:27:57 -0700381 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800382 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800383 continue;
384 }
385
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800386 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800387
Ady Abraham62f51d92022-08-24 22:20:22 +0000388 for (auto& [modeIt, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800389 const auto& [id, mode] = *modeIt;
390 const bool isSeamlessSwitch = mode->getGroup() == mActiveModeIt->second->getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200391
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100392 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100393 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800394 formatLayerInfo(layer, weight).c_str(), to_string(*mode).c_str(),
395 to_string(*mActiveModeIt->second).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200396 continue;
397 }
398
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100399 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
400 !layer.focused) {
401 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100402 " Current mode = %s",
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800403 formatLayerInfo(layer, weight).c_str(), to_string(*mode).c_str(),
404 to_string(*mActiveModeIt->second).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100405 continue;
406 }
407
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100408 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100409 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100410 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100411 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
412 // disappeared.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800413 const bool isInPolicyForDefault = mode->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100414 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100415 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800416 to_string(*mode).c_str(), to_string(*mActiveModeIt->second).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200417 continue;
418 }
419
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800420 const bool inPrimaryRange = policy->primaryRange.includes(mode->getFps());
Alec Mouri11232a22020-05-14 18:06:25 -0700421 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800422 !(layer.focused &&
423 (layer.vote == LayerVoteType::ExplicitDefault ||
424 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700425 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700426 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700427 continue;
428 }
429
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000430 const float layerScore =
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800431 calculateLayerScoreLocked(layer, mode->getFps(), isSeamlessSwitch);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000432 const float weightedLayerScore = weight * layerScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800433
Ady Abraham13cfb362022-08-13 05:12:13 +0000434 // Layer with fixed source has a special consideration which depends on the
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000435 // mConfig.frameRateMultipleThreshold. We don't want these layers to score
436 // refresh rates above the threshold, but we also don't want to favor the lower
437 // ones by having a greater number of layers scoring them. Instead, we calculate
438 // the score independently for these layers and later decide which
439 // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
440 // score 120 Hz, but desired 60 fps should contribute to the score.
441 const bool fixedSourceLayer = [](LayerVoteType vote) {
442 switch (vote) {
443 case LayerVoteType::ExplicitExactOrMultiple:
444 case LayerVoteType::Heuristic:
445 return true;
446 case LayerVoteType::NoVote:
447 case LayerVoteType::Min:
448 case LayerVoteType::Max:
449 case LayerVoteType::ExplicitDefault:
450 case LayerVoteType::ExplicitExact:
451 return false;
452 }
453 }(layer.vote);
Ady Abraham62f51d92022-08-24 22:20:22 +0000454 const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000455 layer.desiredRefreshRate <
456 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
Ady Abraham62f51d92022-08-24 22:20:22 +0000457 if (fixedSourceLayer && layerBelowThreshold) {
Ady Abraham13cfb362022-08-13 05:12:13 +0000458 const bool modeAboveThreshold =
459 mode->getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
Ady Abraham62f51d92022-08-24 22:20:22 +0000460 if (modeAboveThreshold) {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000461 ALOGV("%s gives %s fixed source (above threshold) score of %.4f",
462 formatLayerInfo(layer, weight).c_str(), to_string(mode->getFps()).c_str(),
463 layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000464 fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000465 } else {
466 ALOGV("%s gives %s fixed source (below threshold) score of %.4f",
467 formatLayerInfo(layer, weight).c_str(), to_string(mode->getFps()).c_str(),
468 layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000469 fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000470 }
471 } else {
472 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
473 to_string(mode->getFps()).c_str(), layerScore);
474 overallScore += weightedLayerScore;
475 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800476 }
477 }
478
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000479 // We want to find the best refresh rate without the fixed source layers,
Ady Abraham62f51d92022-08-24 22:20:22 +0000480 // so we could know whether we should add the modeAboveThreshold scores or not.
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000481 // If the best refresh rate is already above the threshold, it means that
482 // some non-fixed source layers already scored it, so we can just add the score
483 // for all fixed source layers, even the ones that are above the threshold.
484 const bool maxScoreAboveThreshold = [&] {
485 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
486 return false;
487 }
488
489 const auto maxScoreIt =
490 std::max_element(scores.begin(), scores.end(),
491 [](RefreshRateScore max, RefreshRateScore current) {
492 const auto& [modeIt, overallScore, _] = current;
493 return overallScore > max.overallScore;
494 });
495 ALOGV("%s is the best refresh rate without fixed source layers. It is %s the threshold for "
496 "refresh rate multiples",
497 to_string(maxScoreIt->modeIt->second->getFps()).c_str(),
498 maxScoreAboveThreshold ? "above" : "below");
499 return maxScoreIt->modeIt->second->getFps() >=
500 Fps::fromValue(mConfig.frameRateMultipleThreshold);
501 }();
502
503 // Now we can add the fixed rate layers score
Ady Abraham62f51d92022-08-24 22:20:22 +0000504 for (auto& [modeIt, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
505 overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000506 if (maxScoreAboveThreshold) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000507 overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000508 }
509 ALOGV("%s adjusted overallScore is %.4f", to_string(modeIt->second->getFps()).c_str(),
510 overallScore);
511 }
512
513 // Now that we scored all the refresh rates we need to pick the one that got the highest
514 // overallScore. In case of a tie we will pick the higher refresh rate if any of the layers
515 // wanted Max, or the lower otherwise.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800516 const DisplayModePtr& bestRefreshRate = maxVoteLayers > 0
517 ? getMaxScoreRefreshRate(scores.rbegin(), scores.rend())
518 : getMaxScoreRefreshRate(scores.begin(), scores.end());
Ady Abraham34702102020-02-10 14:12:05 -0800519
Alec Mouri11232a22020-05-14 18:06:25 -0700520 if (primaryRangeIsSingleRate) {
521 // If we never scored any layers, then choose the rate from the primary
522 // range instead of picking a random score from the app range.
523 if (std::all_of(scores.begin(), scores.end(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000524 [](RefreshRateScore score) { return score.overallScore == 0; })) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800525 const DisplayModePtr& max = getMaxRefreshRateByPolicyLocked(anchorGroup);
526 ALOGV("layers not scored - choose %s", to_string(max->getFps()).c_str());
527 return {max, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700528 } else {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800529 return {bestRefreshRate, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700530 }
531 }
532
Steven Thomasf734df42020-04-13 21:09:28 -0700533 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
534 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
535 // vote we should not change it if we get a touch event. Only apply touch boost if it will
536 // actually increase the refresh rate over the normal selection.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800537 const DisplayModePtr& touchRefreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
Alec Mouri11232a22020-05-14 18:06:25 -0700538
Ady Abraham5e4e9832021-06-14 13:40:56 -0700539 const bool touchBoostForExplicitExact = [&] {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800540 if (mSupportsFrameRateOverrideByContent) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700541 // Enable touch boost if there are other layers besides exact
542 return explicitExact + noVoteLayers != layers.size();
543 } else {
544 // Enable touch boost if there are no exact layers
545 return explicitExact == 0;
546 }
547 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700548
549 using fps_approx_ops::operator<;
550
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800551 if (signals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800552 bestRefreshRate->getFps() < touchRefreshRate->getFps()) {
553 ALOGV("TouchBoost - choose %s", to_string(touchRefreshRate->getFps()).c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800554 return {touchRefreshRate, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700555 }
556
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800557 return {bestRefreshRate, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800558}
559
Ady Abraham62a0be22020-12-08 16:54:10 -0800560std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
561groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
562 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
563 for (const auto& layer : layers) {
564 auto iter = layersByUid.emplace(layer.ownerUid,
565 std::vector<const RefreshRateConfigs::LayerRequirement*>());
566 auto& layersWithSameUid = iter.first->second;
567 layersWithSameUid.push_back(&layer);
568 }
569
570 // Remove uids that can't have a frame rate override
571 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
572 const auto& layersWithSameUid = iter->second;
573 bool skipUid = false;
574 for (const auto& layer : layersWithSameUid) {
575 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
576 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
577 skipUid = true;
578 break;
579 }
580 }
581 if (skipUid) {
582 iter = layersByUid.erase(iter);
583 } else {
584 ++iter;
585 }
586 }
587
588 return layersByUid;
589}
590
Ady Abraham62a0be22020-12-08 16:54:10 -0800591RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800592 const std::vector<LayerRequirement>& layers, Fps displayRefreshRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700593 GlobalSignals globalSignals) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800594 ATRACE_CALL();
Ady Abraham62a0be22020-12-08 16:54:10 -0800595
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800596 ALOGV("%s: %zu layers", __func__, layers.size());
597
Ady Abraham62a0be22020-12-08 16:54:10 -0800598 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800599
600 std::vector<RefreshRateScore> scores;
601 scores.reserve(mDisplayModes.size());
602
603 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
604 scores.emplace_back(RefreshRateScore{it, 0.0f});
605 }
606
607 std::sort(scores.begin(), scores.end(), [](const auto& lhs, const auto& rhs) {
608 const auto& mode1 = lhs.modeIt->second;
609 const auto& mode2 = rhs.modeIt->second;
610 return isStrictlyLess(mode1->getFps(), mode2->getFps());
611 });
612
Ady Abraham62a0be22020-12-08 16:54:10 -0800613 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
614 groupLayersByUid(layers);
615 UidToFrameRateOverride frameRateOverrides;
616 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800617 // Layers with ExplicitExactOrMultiple expect touch boost
618 const bool hasExplicitExactOrMultiple =
619 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
620 [](const auto& layer) {
621 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
622 });
623
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700624 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800625 continue;
626 }
627
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000628 for (auto& [_, score, _1] : scores) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800629 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -0800630 }
631
632 for (const auto& layer : layersWithSameUid) {
633 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
634 continue;
635 }
636
637 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800638 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
639 layer->vote != LayerVoteType::ExplicitExact);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000640 for (auto& [modeIt, score, _] : scores) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800641 constexpr bool isSeamlessSwitch = true;
642 const auto layerScore = calculateLayerScoreLocked(*layer, modeIt->second->getFps(),
643 isSeamlessSwitch);
644 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -0800645 }
646 }
647
Ady Abrahamcc315492022-02-17 17:06:39 -0800648 // We just care about the refresh rates which are a divisor of the
Ady Abraham62a0be22020-12-08 16:54:10 -0800649 // display refresh rate
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800650 const auto it = std::remove_if(scores.begin(), scores.end(), [&](RefreshRateScore score) {
651 const auto& [id, mode] = *score.modeIt;
652 return getFrameRateDivisor(displayRefreshRate, mode->getFps()) == 0;
653 });
654 scores.erase(it, scores.end());
Ady Abraham62a0be22020-12-08 16:54:10 -0800655
656 // If we never scored any layers, we don't have a preferred frame rate
657 if (std::all_of(scores.begin(), scores.end(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000658 [](RefreshRateScore score) { return score.overallScore == 0; })) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800659 continue;
660 }
661
662 // Now that we scored all the refresh rates we need to pick the one that got the highest
663 // score.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800664 const DisplayModePtr& bestRefreshRate =
665 getMaxScoreRefreshRate(scores.begin(), scores.end());
666
Ady Abraham5cc2e262021-03-25 13:09:17 -0700667 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800668 }
669
670 return frameRateOverrides;
671}
672
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100673std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800674 std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800675 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100676
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800677 const DisplayModePtr& current = desiredActiveModeId
678 ? mDisplayModes.get(*desiredActiveModeId)->get()
679 : mActiveModeIt->second;
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100680
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800681 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
682 if (current == min) {
683 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100684 }
685
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800686 const auto& mode = timerExpired ? min : current;
687 return mode->getFps();
Steven Thomasf734df42020-04-13 21:09:28 -0700688}
689
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800690const DisplayModePtr& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
691 for (const DisplayModeIterator modeIt : mPrimaryRefreshRates) {
692 const auto& mode = modeIt->second;
693 if (mActiveModeIt->second->getGroup() == mode->getGroup()) {
694 return mode;
Marin Shalamanov46084422020-10-13 12:33:42 +0200695 }
696 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800697
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100698 ALOGE("Can't find min refresh rate by policy with the same mode group"
699 " as the current mode %s",
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800700 to_string(*mActiveModeIt->second).c_str());
701
702 // Default to the lowest refresh rate.
703 return mPrimaryRefreshRates.front()->second;
Ady Abraham2139f732019-11-13 18:56:40 -0800704}
705
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800706DisplayModePtr RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800707 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700708 return getMaxRefreshRateByPolicyLocked();
709}
710
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800711const DisplayModePtr& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
712 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); ++it) {
713 const auto& mode = (*it)->second;
714 if (anchorGroup == mode->getGroup()) {
715 return mode;
Marin Shalamanov46084422020-10-13 12:33:42 +0200716 }
717 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800718
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100719 ALOGE("Can't find max refresh rate by policy with the same mode group"
720 " as the current mode %s",
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800721 to_string(*mActiveModeIt->second).c_str());
722
723 // Default to the highest refresh rate.
724 return mPrimaryRefreshRates.back()->second;
Ady Abraham2139f732019-11-13 18:56:40 -0800725}
726
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800727DisplayModePtr RefreshRateConfigs::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800728 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800729 return mActiveModeIt->second;
Ady Abraham2139f732019-11-13 18:56:40 -0800730}
731
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800732void RefreshRateConfigs::setActiveModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800733 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200734
735 // Invalidate the cached invocation to getBestRefreshRate. This forces
736 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800737 mGetBestRefreshRateCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200738
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800739 mActiveModeIt = mDisplayModes.find(modeId);
740 LOG_ALWAYS_FATAL_IF(mActiveModeIt == mDisplayModes.end());
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800741}
742
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800743RefreshRateConfigs::RefreshRateConfigs(DisplayModes modes, DisplayModeId activeModeId,
rnlee3bd610662021-06-23 16:27:57 -0700744 Config config)
745 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700746 initializeIdleTimer();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800747 updateDisplayModes(std::move(modes), activeModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100748}
749
Ady Abraham9a2ea342021-09-03 17:32:34 -0700750void RefreshRateConfigs::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +0000751 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700752 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +0000753 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800754 [this] {
755 std::scoped_lock lock(mIdleTimerCallbacksMutex);
756 if (const auto callbacks = getIdleTimerCallbacks()) {
757 callbacks->onReset();
758 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700759 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800760 [this] {
761 std::scoped_lock lock(mIdleTimerCallbacksMutex);
762 if (const auto callbacks = getIdleTimerCallbacks()) {
763 callbacks->onExpired();
764 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700765 });
Ady Abraham9a2ea342021-09-03 17:32:34 -0700766 }
767}
768
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800769void RefreshRateConfigs::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100770 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200771
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200772 // Invalidate the cached invocation to getBestRefreshRate. This forces
773 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800774 mGetBestRefreshRateCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200775
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800776 mDisplayModes = std::move(modes);
777 mActiveModeIt = mDisplayModes.find(activeModeId);
778 LOG_ALWAYS_FATAL_IF(mActiveModeIt == mDisplayModes.end());
Ady Abrahamabc27602020-04-08 17:20:29 -0700779
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800780 const auto sortedModes =
781 sortByRefreshRate(mDisplayModes, [](const DisplayMode&) { return true; });
782 mMinRefreshRateModeIt = sortedModes.front();
783 mMaxRefreshRateModeIt = sortedModes.back();
784
Marin Shalamanov75f37252021-02-10 21:43:57 +0100785 // Reset the policy because the old one may no longer be valid.
786 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800787 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -0800788
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800789 mSupportsFrameRateOverrideByContent =
790 mConfig.enableFrameRateOverride && canModesSupportFrameRateOverride(sortedModes);
Ady Abraham4899ff82021-01-06 13:53:29 -0800791
Ady Abrahamabc27602020-04-08 17:20:29 -0700792 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800793}
794
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100795bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100796 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800797 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
798 if (!policy.primaryRange.includes(mode->get()->getFps())) {
799 ALOGE("Default mode is not in the primary range.");
800 return false;
801 }
802 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100803 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700804 return false;
805 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700806
807 using namespace fps_approx_ops;
808 return policy.appRequestRange.min <= policy.primaryRange.min &&
809 policy.appRequestRange.max >= policy.primaryRange.max;
Steven Thomasd4071902020-03-24 16:02:53 -0700810}
811
812status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800813 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100814 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100815 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100816 return BAD_VALUE;
817 }
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800818 mGetBestRefreshRateCache.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700819 Policy previousPolicy = *getCurrentPolicyLocked();
820 mDisplayManagerPolicy = policy;
821 if (*getCurrentPolicyLocked() == previousPolicy) {
822 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100823 }
Ady Abraham2139f732019-11-13 18:56:40 -0800824 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100825 return NO_ERROR;
826}
827
Steven Thomasd4071902020-03-24 16:02:53 -0700828status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100829 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100830 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700831 return BAD_VALUE;
832 }
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800833 mGetBestRefreshRateCache.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700834 Policy previousPolicy = *getCurrentPolicyLocked();
835 mOverridePolicy = policy;
836 if (*getCurrentPolicyLocked() == previousPolicy) {
837 return CURRENT_POLICY_UNCHANGED;
838 }
839 constructAvailableRefreshRates();
840 return NO_ERROR;
841}
842
843const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
844 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
845}
846
847RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
848 std::lock_guard lock(mLock);
849 return *getCurrentPolicyLocked();
850}
851
852RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
853 std::lock_guard lock(mLock);
854 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100855}
856
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100857bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100858 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800859 return std::any_of(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
860 [modeId](DisplayModeIterator modeIt) {
861 return modeIt->second->getId() == modeId;
862 });
Ady Abraham2139f732019-11-13 18:56:40 -0800863}
864
865void RefreshRateConfigs::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800866 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -0700867 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800868 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700869
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800870 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800871
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800872 const auto filterRefreshRates = [&](FpsRange range, const char* rangeName) REQUIRES(mLock) {
873 const auto filter = [&](const DisplayMode& mode) {
874 return mode.getResolution() == defaultMode->getResolution() &&
875 mode.getDpi() == defaultMode->getDpi() &&
876 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
877 range.includes(mode.getFps());
878 };
Ady Abraham8a82ba62020-01-17 12:43:17 -0800879
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800880 const auto modes = sortByRefreshRate(mDisplayModes, filter);
881 LOG_ALWAYS_FATAL_IF(modes.empty(), "No matching modes for %s range %s", rangeName,
882 to_string(range).c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800883
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800884 const auto stringifyModes = [&] {
885 std::string str;
886 for (const auto modeIt : modes) {
887 str += to_string(modeIt->second->getFps());
888 str.push_back(' ');
889 }
890 return str;
891 };
892 ALOGV("%s refresh rates: %s", rangeName, stringifyModes().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700893
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800894 return modes;
895 };
896
897 mPrimaryRefreshRates = filterRefreshRates(policy->primaryRange, "primary");
898 mAppRequestRefreshRates = filterRefreshRates(policy->appRequestRange, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -0800899}
900
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100901Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700902 using namespace fps_approx_ops;
903
904 if (frameRate <= mKnownFrameRates.front()) {
905 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700906 }
907
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700908 if (frameRate >= mKnownFrameRates.back()) {
909 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700910 }
911
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100912 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700913 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700914
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700915 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
916 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700917 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
918}
919
Ana Krulecb9afd792020-06-11 13:16:15 -0700920RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
921 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800922
923 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getFps();
924 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700925
926 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
927 // the min allowed refresh rate is higher than the device min, we do not want to enable the
928 // timer.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800929 if (isStrictlyLess(deviceMinFps, minByPolicy->getFps())) {
930 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -0700931 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800932
933 const DisplayModePtr& maxByPolicy = getMaxRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700934 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800935 // Turn on the timer when the min of the primary range is below the device min.
936 if (const Policy* currentPolicy = getCurrentPolicyLocked();
937 isApproxLess(currentPolicy->primaryRange.min, deviceMinFps)) {
938 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700939 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800940 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -0700941 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800942
Ana Krulecb9afd792020-06-11 13:16:15 -0700943 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800944 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700945}
946
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800947int RefreshRateConfigs::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700948 // This calculation needs to be in sync with the java code
949 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200950
951 // The threshold must be smaller than 0.001 in order to differentiate
952 // between the fractional pairs (e.g. 59.94 and 60).
953 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800954 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700955 const auto numPeriodsRounded = std::round(numPeriods);
956 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800957 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700958 }
959
Ady Abraham62f216c2020-10-13 19:07:23 -0700960 return static_cast<int>(numPeriodsRounded);
961}
962
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200963bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700964 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200965 return isFractionalPairOrMultiple(bigger, smaller);
966 }
967
968 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
969 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700970 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
971 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200972}
973
Marin Shalamanovba421a82020-11-10 21:49:26 +0100974void RefreshRateConfigs::dump(std::string& result) const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700975 using namespace std::string_literals;
976
Marin Shalamanovba421a82020-11-10 21:49:26 +0100977 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +0100978
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700979 const auto activeModeId = mActiveModeIt->first;
980 result += " activeModeId="s;
981 result += std::to_string(activeModeId.value());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100982
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700983 result += "\n displayModes=\n"s;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800984 for (const auto& [id, mode] : mDisplayModes) {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700985 result += " "s;
986 result += to_string(*mode);
987 result += '\n';
Marin Shalamanovba421a82020-11-10 21:49:26 +0100988 }
989
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700990 base::StringAppendF(&result, " displayManagerPolicy=%s\n",
991 mDisplayManagerPolicy.toString().c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800992
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700993 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
994 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
995 base::StringAppendF(&result, " overridePolicy=%s\n", currentPolicy.toString().c_str());
ramindani32cf0602022-03-02 02:30:29 +0000996 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800997
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700998 base::StringAppendF(&result, " supportsFrameRateOverrideByContent=%s\n",
999 mSupportsFrameRateOverrideByContent ? "true" : "false");
1000
1001 result += " idleTimer="s;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001002 if (mIdleTimer) {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001003 result += mIdleTimer->dump();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001004 } else {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001005 result += "off"s;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001006 }
1007
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001008 if (const auto controller = mConfig.kernelIdleTimerController) {
1009 base::StringAppendF(&result, " (kernel via %s)", ftl::enum_string(*controller).c_str());
1010 } else {
1011 result += " (platform)"s;
1012 }
1013
1014 result += '\n';
Marin Shalamanovba421a82020-11-10 21:49:26 +01001015}
1016
ramindani32cf0602022-03-02 02:30:29 +00001017std::chrono::milliseconds RefreshRateConfigs::getIdleTimerTimeout() {
1018 return mConfig.idleTimerTimeout;
1019}
1020
Ady Abraham2139f732019-11-13 18:56:40 -08001021} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001022
1023// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001024#pragma clang diagnostic pop // ignored "-Wextra"