blob: 803eb4f91fd0004b9ff6cae987e752bda5f59985 [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 {
45 float belowThreshold;
46 float aboveThreshold;
47 } fixedRateLayersScore;
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 Abrahamae2e3c72022-08-13 05:12:13 +0000388 for (auto& [modeIt, overallScore, fixedRateScore] : 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 Abrahamae2e3c72022-08-13 05:12:13 +0000434 // Layer with fixed source has a special consideration depends on the
435 // 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);
454 const bool layerAboveThreshold = mConfig.frameRateMultipleThreshold != 0 &&
455 mode->getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold) &&
456 layer.desiredRefreshRate <
457 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
458 if (fixedSourceLayer) {
459 if (layerAboveThreshold) {
460 ALOGV("%s gives %s fixed source (above threshold) score of %.4f",
461 formatLayerInfo(layer, weight).c_str(), to_string(mode->getFps()).c_str(),
462 layerScore);
463 fixedRateScore.aboveThreshold += weightedLayerScore;
464 } else {
465 ALOGV("%s gives %s fixed source (below threshold) score of %.4f",
466 formatLayerInfo(layer, weight).c_str(), to_string(mode->getFps()).c_str(),
467 layerScore);
468 fixedRateScore.belowThreshold += weightedLayerScore;
469 }
470 } else {
471 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
472 to_string(mode->getFps()).c_str(), layerScore);
473 overallScore += weightedLayerScore;
474 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800475 }
476 }
477
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000478 // We want to find the best refresh rate without the fixed source layers,
479 // so we could know whether we should add the aboveThreshold scores or not.
480 // If the best refresh rate is already above the threshold, it means that
481 // some non-fixed source layers already scored it, so we can just add the score
482 // for all fixed source layers, even the ones that are above the threshold.
483 const bool maxScoreAboveThreshold = [&] {
484 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
485 return false;
486 }
487
488 const auto maxScoreIt =
489 std::max_element(scores.begin(), scores.end(),
490 [](RefreshRateScore max, RefreshRateScore current) {
491 const auto& [modeIt, overallScore, _] = current;
492 return overallScore > max.overallScore;
493 });
494 ALOGV("%s is the best refresh rate without fixed source layers. It is %s the threshold for "
495 "refresh rate multiples",
496 to_string(maxScoreIt->modeIt->second->getFps()).c_str(),
497 maxScoreAboveThreshold ? "above" : "below");
498 return maxScoreIt->modeIt->second->getFps() >=
499 Fps::fromValue(mConfig.frameRateMultipleThreshold);
500 }();
501
502 // Now we can add the fixed rate layers score
503 for (auto& [modeIt, overallScore, fixedRateScore] : scores) {
504 overallScore += fixedRateScore.belowThreshold;
505 if (maxScoreAboveThreshold) {
506 overallScore += fixedRateScore.aboveThreshold;
507 }
508 ALOGV("%s adjusted overallScore is %.4f", to_string(modeIt->second->getFps()).c_str(),
509 overallScore);
510 }
511
512 // Now that we scored all the refresh rates we need to pick the one that got the highest
513 // overallScore. In case of a tie we will pick the higher refresh rate if any of the layers
514 // wanted Max, or the lower otherwise.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800515 const DisplayModePtr& bestRefreshRate = maxVoteLayers > 0
516 ? getMaxScoreRefreshRate(scores.rbegin(), scores.rend())
517 : getMaxScoreRefreshRate(scores.begin(), scores.end());
Ady Abraham34702102020-02-10 14:12:05 -0800518
Alec Mouri11232a22020-05-14 18:06:25 -0700519 if (primaryRangeIsSingleRate) {
520 // If we never scored any layers, then choose the rate from the primary
521 // range instead of picking a random score from the app range.
522 if (std::all_of(scores.begin(), scores.end(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000523 [](RefreshRateScore score) { return score.overallScore == 0; })) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800524 const DisplayModePtr& max = getMaxRefreshRateByPolicyLocked(anchorGroup);
525 ALOGV("layers not scored - choose %s", to_string(max->getFps()).c_str());
526 return {max, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700527 } else {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800528 return {bestRefreshRate, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700529 }
530 }
531
Steven Thomasf734df42020-04-13 21:09:28 -0700532 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
533 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
534 // vote we should not change it if we get a touch event. Only apply touch boost if it will
535 // actually increase the refresh rate over the normal selection.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800536 const DisplayModePtr& touchRefreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
Alec Mouri11232a22020-05-14 18:06:25 -0700537
Ady Abraham5e4e9832021-06-14 13:40:56 -0700538 const bool touchBoostForExplicitExact = [&] {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800539 if (mSupportsFrameRateOverrideByContent) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700540 // Enable touch boost if there are other layers besides exact
541 return explicitExact + noVoteLayers != layers.size();
542 } else {
543 // Enable touch boost if there are no exact layers
544 return explicitExact == 0;
545 }
546 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700547
548 using fps_approx_ops::operator<;
549
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800550 if (signals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800551 bestRefreshRate->getFps() < touchRefreshRate->getFps()) {
552 ALOGV("TouchBoost - choose %s", to_string(touchRefreshRate->getFps()).c_str());
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800553 return {touchRefreshRate, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700554 }
555
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800556 return {bestRefreshRate, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800557}
558
Ady Abraham62a0be22020-12-08 16:54:10 -0800559std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
560groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
561 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
562 for (const auto& layer : layers) {
563 auto iter = layersByUid.emplace(layer.ownerUid,
564 std::vector<const RefreshRateConfigs::LayerRequirement*>());
565 auto& layersWithSameUid = iter.first->second;
566 layersWithSameUid.push_back(&layer);
567 }
568
569 // Remove uids that can't have a frame rate override
570 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
571 const auto& layersWithSameUid = iter->second;
572 bool skipUid = false;
573 for (const auto& layer : layersWithSameUid) {
574 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
575 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
576 skipUid = true;
577 break;
578 }
579 }
580 if (skipUid) {
581 iter = layersByUid.erase(iter);
582 } else {
583 ++iter;
584 }
585 }
586
587 return layersByUid;
588}
589
Ady Abraham62a0be22020-12-08 16:54:10 -0800590RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800591 const std::vector<LayerRequirement>& layers, Fps displayRefreshRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700592 GlobalSignals globalSignals) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800593 ATRACE_CALL();
Ady Abraham62a0be22020-12-08 16:54:10 -0800594
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800595 ALOGV("%s: %zu layers", __func__, layers.size());
596
Ady Abraham62a0be22020-12-08 16:54:10 -0800597 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800598
599 std::vector<RefreshRateScore> scores;
600 scores.reserve(mDisplayModes.size());
601
602 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
603 scores.emplace_back(RefreshRateScore{it, 0.0f});
604 }
605
606 std::sort(scores.begin(), scores.end(), [](const auto& lhs, const auto& rhs) {
607 const auto& mode1 = lhs.modeIt->second;
608 const auto& mode2 = rhs.modeIt->second;
609 return isStrictlyLess(mode1->getFps(), mode2->getFps());
610 });
611
Ady Abraham62a0be22020-12-08 16:54:10 -0800612 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
613 groupLayersByUid(layers);
614 UidToFrameRateOverride frameRateOverrides;
615 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800616 // Layers with ExplicitExactOrMultiple expect touch boost
617 const bool hasExplicitExactOrMultiple =
618 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
619 [](const auto& layer) {
620 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
621 });
622
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700623 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800624 continue;
625 }
626
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000627 for (auto& [_, score, _1] : scores) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800628 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -0800629 }
630
631 for (const auto& layer : layersWithSameUid) {
632 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
633 continue;
634 }
635
636 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800637 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
638 layer->vote != LayerVoteType::ExplicitExact);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000639 for (auto& [modeIt, score, _] : scores) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800640 constexpr bool isSeamlessSwitch = true;
641 const auto layerScore = calculateLayerScoreLocked(*layer, modeIt->second->getFps(),
642 isSeamlessSwitch);
643 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -0800644 }
645 }
646
Ady Abrahamcc315492022-02-17 17:06:39 -0800647 // We just care about the refresh rates which are a divisor of the
Ady Abraham62a0be22020-12-08 16:54:10 -0800648 // display refresh rate
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800649 const auto it = std::remove_if(scores.begin(), scores.end(), [&](RefreshRateScore score) {
650 const auto& [id, mode] = *score.modeIt;
651 return getFrameRateDivisor(displayRefreshRate, mode->getFps()) == 0;
652 });
653 scores.erase(it, scores.end());
Ady Abraham62a0be22020-12-08 16:54:10 -0800654
655 // If we never scored any layers, we don't have a preferred frame rate
656 if (std::all_of(scores.begin(), scores.end(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000657 [](RefreshRateScore score) { return score.overallScore == 0; })) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800658 continue;
659 }
660
661 // Now that we scored all the refresh rates we need to pick the one that got the highest
662 // score.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800663 const DisplayModePtr& bestRefreshRate =
664 getMaxScoreRefreshRate(scores.begin(), scores.end());
665
Ady Abraham5cc2e262021-03-25 13:09:17 -0700666 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800667 }
668
669 return frameRateOverrides;
670}
671
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100672std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800673 std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800674 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100675
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800676 const DisplayModePtr& current = desiredActiveModeId
677 ? mDisplayModes.get(*desiredActiveModeId)->get()
678 : mActiveModeIt->second;
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100679
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800680 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
681 if (current == min) {
682 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100683 }
684
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800685 const auto& mode = timerExpired ? min : current;
686 return mode->getFps();
Steven Thomasf734df42020-04-13 21:09:28 -0700687}
688
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800689const DisplayModePtr& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
690 for (const DisplayModeIterator modeIt : mPrimaryRefreshRates) {
691 const auto& mode = modeIt->second;
692 if (mActiveModeIt->second->getGroup() == mode->getGroup()) {
693 return mode;
Marin Shalamanov46084422020-10-13 12:33:42 +0200694 }
695 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800696
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100697 ALOGE("Can't find min refresh rate by policy with the same mode group"
698 " as the current mode %s",
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800699 to_string(*mActiveModeIt->second).c_str());
700
701 // Default to the lowest refresh rate.
702 return mPrimaryRefreshRates.front()->second;
Ady Abraham2139f732019-11-13 18:56:40 -0800703}
704
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800705DisplayModePtr RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800706 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700707 return getMaxRefreshRateByPolicyLocked();
708}
709
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800710const DisplayModePtr& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
711 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); ++it) {
712 const auto& mode = (*it)->second;
713 if (anchorGroup == mode->getGroup()) {
714 return mode;
Marin Shalamanov46084422020-10-13 12:33:42 +0200715 }
716 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800717
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100718 ALOGE("Can't find max refresh rate by policy with the same mode group"
719 " as the current mode %s",
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800720 to_string(*mActiveModeIt->second).c_str());
721
722 // Default to the highest refresh rate.
723 return mPrimaryRefreshRates.back()->second;
Ady Abraham2139f732019-11-13 18:56:40 -0800724}
725
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800726DisplayModePtr RefreshRateConfigs::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800727 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800728 return mActiveModeIt->second;
Ady Abraham2139f732019-11-13 18:56:40 -0800729}
730
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800731void RefreshRateConfigs::setActiveModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800732 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200733
734 // Invalidate the cached invocation to getBestRefreshRate. This forces
735 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800736 mGetBestRefreshRateCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200737
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800738 mActiveModeIt = mDisplayModes.find(modeId);
739 LOG_ALWAYS_FATAL_IF(mActiveModeIt == mDisplayModes.end());
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800740}
741
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800742RefreshRateConfigs::RefreshRateConfigs(DisplayModes modes, DisplayModeId activeModeId,
rnlee3bd610662021-06-23 16:27:57 -0700743 Config config)
744 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700745 initializeIdleTimer();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800746 updateDisplayModes(std::move(modes), activeModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100747}
748
Ady Abraham9a2ea342021-09-03 17:32:34 -0700749void RefreshRateConfigs::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +0000750 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700751 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +0000752 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800753 [this] {
754 std::scoped_lock lock(mIdleTimerCallbacksMutex);
755 if (const auto callbacks = getIdleTimerCallbacks()) {
756 callbacks->onReset();
757 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700758 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800759 [this] {
760 std::scoped_lock lock(mIdleTimerCallbacksMutex);
761 if (const auto callbacks = getIdleTimerCallbacks()) {
762 callbacks->onExpired();
763 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700764 });
Ady Abraham9a2ea342021-09-03 17:32:34 -0700765 }
766}
767
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800768void RefreshRateConfigs::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100769 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200770
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200771 // Invalidate the cached invocation to getBestRefreshRate. This forces
772 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800773 mGetBestRefreshRateCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200774
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800775 mDisplayModes = std::move(modes);
776 mActiveModeIt = mDisplayModes.find(activeModeId);
777 LOG_ALWAYS_FATAL_IF(mActiveModeIt == mDisplayModes.end());
Ady Abrahamabc27602020-04-08 17:20:29 -0700778
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800779 const auto sortedModes =
780 sortByRefreshRate(mDisplayModes, [](const DisplayMode&) { return true; });
781 mMinRefreshRateModeIt = sortedModes.front();
782 mMaxRefreshRateModeIt = sortedModes.back();
783
Marin Shalamanov75f37252021-02-10 21:43:57 +0100784 // Reset the policy because the old one may no longer be valid.
785 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800786 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -0800787
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800788 mSupportsFrameRateOverrideByContent =
789 mConfig.enableFrameRateOverride && canModesSupportFrameRateOverride(sortedModes);
Ady Abraham4899ff82021-01-06 13:53:29 -0800790
Ady Abrahamabc27602020-04-08 17:20:29 -0700791 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800792}
793
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100794bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100795 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800796 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
797 if (!policy.primaryRange.includes(mode->get()->getFps())) {
798 ALOGE("Default mode is not in the primary range.");
799 return false;
800 }
801 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100802 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700803 return false;
804 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700805
806 using namespace fps_approx_ops;
807 return policy.appRequestRange.min <= policy.primaryRange.min &&
808 policy.appRequestRange.max >= policy.primaryRange.max;
Steven Thomasd4071902020-03-24 16:02:53 -0700809}
810
811status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800812 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100813 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100814 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100815 return BAD_VALUE;
816 }
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800817 mGetBestRefreshRateCache.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700818 Policy previousPolicy = *getCurrentPolicyLocked();
819 mDisplayManagerPolicy = policy;
820 if (*getCurrentPolicyLocked() == previousPolicy) {
821 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100822 }
Ady Abraham2139f732019-11-13 18:56:40 -0800823 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100824 return NO_ERROR;
825}
826
Steven Thomasd4071902020-03-24 16:02:53 -0700827status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100828 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100829 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700830 return BAD_VALUE;
831 }
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800832 mGetBestRefreshRateCache.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700833 Policy previousPolicy = *getCurrentPolicyLocked();
834 mOverridePolicy = policy;
835 if (*getCurrentPolicyLocked() == previousPolicy) {
836 return CURRENT_POLICY_UNCHANGED;
837 }
838 constructAvailableRefreshRates();
839 return NO_ERROR;
840}
841
842const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
843 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
844}
845
846RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
847 std::lock_guard lock(mLock);
848 return *getCurrentPolicyLocked();
849}
850
851RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
852 std::lock_guard lock(mLock);
853 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100854}
855
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100856bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100857 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800858 return std::any_of(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
859 [modeId](DisplayModeIterator modeIt) {
860 return modeIt->second->getId() == modeId;
861 });
Ady Abraham2139f732019-11-13 18:56:40 -0800862}
863
864void RefreshRateConfigs::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800865 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -0700866 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800867 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700868
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800869 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800870
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800871 const auto filterRefreshRates = [&](FpsRange range, const char* rangeName) REQUIRES(mLock) {
872 const auto filter = [&](const DisplayMode& mode) {
873 return mode.getResolution() == defaultMode->getResolution() &&
874 mode.getDpi() == defaultMode->getDpi() &&
875 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
876 range.includes(mode.getFps());
877 };
Ady Abraham8a82ba62020-01-17 12:43:17 -0800878
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800879 const auto modes = sortByRefreshRate(mDisplayModes, filter);
880 LOG_ALWAYS_FATAL_IF(modes.empty(), "No matching modes for %s range %s", rangeName,
881 to_string(range).c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -0800882
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800883 const auto stringifyModes = [&] {
884 std::string str;
885 for (const auto modeIt : modes) {
886 str += to_string(modeIt->second->getFps());
887 str.push_back(' ');
888 }
889 return str;
890 };
891 ALOGV("%s refresh rates: %s", rangeName, stringifyModes().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700892
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800893 return modes;
894 };
895
896 mPrimaryRefreshRates = filterRefreshRates(policy->primaryRange, "primary");
897 mAppRequestRefreshRates = filterRefreshRates(policy->appRequestRange, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -0800898}
899
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100900Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700901 using namespace fps_approx_ops;
902
903 if (frameRate <= mKnownFrameRates.front()) {
904 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700905 }
906
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700907 if (frameRate >= mKnownFrameRates.back()) {
908 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700909 }
910
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100911 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700912 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700913
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700914 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
915 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700916 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
917}
918
Ana Krulecb9afd792020-06-11 13:16:15 -0700919RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
920 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800921
922 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getFps();
923 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700924
925 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
926 // the min allowed refresh rate is higher than the device min, we do not want to enable the
927 // timer.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800928 if (isStrictlyLess(deviceMinFps, minByPolicy->getFps())) {
929 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -0700930 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800931
932 const DisplayModePtr& maxByPolicy = getMaxRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700933 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800934 // Turn on the timer when the min of the primary range is below the device min.
935 if (const Policy* currentPolicy = getCurrentPolicyLocked();
936 isApproxLess(currentPolicy->primaryRange.min, deviceMinFps)) {
937 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700938 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800939 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -0700940 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800941
Ana Krulecb9afd792020-06-11 13:16:15 -0700942 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800943 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700944}
945
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800946int RefreshRateConfigs::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700947 // This calculation needs to be in sync with the java code
948 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200949
950 // The threshold must be smaller than 0.001 in order to differentiate
951 // between the fractional pairs (e.g. 59.94 and 60).
952 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800953 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700954 const auto numPeriodsRounded = std::round(numPeriods);
955 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800956 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700957 }
958
Ady Abraham62f216c2020-10-13 19:07:23 -0700959 return static_cast<int>(numPeriodsRounded);
960}
961
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200962bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700963 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200964 return isFractionalPairOrMultiple(bigger, smaller);
965 }
966
967 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
968 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700969 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
970 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200971}
972
Marin Shalamanovba421a82020-11-10 21:49:26 +0100973void RefreshRateConfigs::dump(std::string& result) const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700974 using namespace std::string_literals;
975
Marin Shalamanovba421a82020-11-10 21:49:26 +0100976 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +0100977
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700978 const auto activeModeId = mActiveModeIt->first;
979 result += " activeModeId="s;
980 result += std::to_string(activeModeId.value());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100981
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700982 result += "\n displayModes=\n"s;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800983 for (const auto& [id, mode] : mDisplayModes) {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700984 result += " "s;
985 result += to_string(*mode);
986 result += '\n';
Marin Shalamanovba421a82020-11-10 21:49:26 +0100987 }
988
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700989 base::StringAppendF(&result, " displayManagerPolicy=%s\n",
990 mDisplayManagerPolicy.toString().c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800991
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700992 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
993 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
994 base::StringAppendF(&result, " overridePolicy=%s\n", currentPolicy.toString().c_str());
ramindani32cf0602022-03-02 02:30:29 +0000995 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800996
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700997 base::StringAppendF(&result, " supportsFrameRateOverrideByContent=%s\n",
998 mSupportsFrameRateOverrideByContent ? "true" : "false");
999
1000 result += " idleTimer="s;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001001 if (mIdleTimer) {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001002 result += mIdleTimer->dump();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001003 } else {
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001004 result += "off"s;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001005 }
1006
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001007 if (const auto controller = mConfig.kernelIdleTimerController) {
1008 base::StringAppendF(&result, " (kernel via %s)", ftl::enum_string(*controller).c_str());
1009 } else {
1010 result += " (platform)"s;
1011 }
1012
1013 result += '\n';
Marin Shalamanovba421a82020-11-10 21:49:26 +01001014}
1015
ramindani32cf0602022-03-02 02:30:29 +00001016std::chrono::milliseconds RefreshRateConfigs::getIdleTimerTimeout() {
1017 return mConfig.idleTimerTimeout;
1018}
1019
Ady Abraham2139f732019-11-13 18:56:40 -08001020} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001021
1022// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001023#pragma clang diagnostic pop // ignored "-Wextra"