blob: 4be1ac7c6f2a1981df4024386a128c7fe49343e9 [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 Laskowski530d6bd2022-10-10 16:55:54 -040026#include <deque>
Ady Abraham68636062022-11-16 17:07:25 -080027#include <map>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070028
29#include <android-base/properties.h>
30#include <android-base/stringprintf.h>
31#include <ftl/enum.h>
Dominik Laskowskif8734e02022-08-26 09:06:59 -070032#include <ftl/fake_guard.h>
Dominik Laskowski36dced82022-09-02 09:24:00 -070033#include <ftl/match.h>
Ady Abraham8ca643a2022-10-18 18:26:47 -070034#include <ftl/unit.h>
Ady Abraham68636062022-11-16 17:07:25 -080035#include <scheduler/FrameRateMode.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070036#include <utils/Trace.h>
37
Ady Abraham4899ff82021-01-06 13:53:29 -080038#include "../SurfaceFlingerProperties.h"
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040039#include "RefreshRateSelector.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080040
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080041#undef LOG_TAG
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040042#define LOG_TAG "RefreshRateSelector"
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080043
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080044namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010045namespace {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070046
Dominik Laskowskib0054a22022-03-03 09:03:06 -080047struct RefreshRateScore {
Ady Abraham68636062022-11-16 17:07:25 -080048 FrameRateMode frameRateMode;
Ady Abrahamae2e3c72022-08-13 05:12:13 +000049 float overallScore;
50 struct {
Ady Abraham62f51d92022-08-24 22:20:22 +000051 float modeBelowThreshold;
52 float modeAboveThreshold;
53 } fixedRateBelowThresholdLayersScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -080054};
55
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040056constexpr RefreshRateSelector::GlobalSignals kNoSignals;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080057
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040058std::string formatLayerInfo(const RefreshRateSelector::LayerRequirement& layer, float weight) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080059 return base::StringPrintf("%s (type=%s, weight=%.2f, seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070060 ftl::enum_string(layer.vote).c_str(), weight,
61 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010062 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010063}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010064
Marin Shalamanova7fe3042021-01-29 21:02:08 +010065std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070066 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010067 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010068
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070069 // Add all supported refresh rates.
Dominik Laskowskib0054a22022-03-03 09:03:06 -080070 for (const auto& [id, mode] : modes) {
71 knownFrameRates.push_back(mode->getFps());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010072 }
73
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070074 // Sort and remove duplicates.
75 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010076 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070077 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010078 knownFrameRates.end());
79 return knownFrameRates;
80}
81
Ady Abraham68636062022-11-16 17:07:25 -080082std::vector<DisplayModeIterator> sortByRefreshRate(const DisplayModes& modes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080083 std::vector<DisplayModeIterator> sortedModes;
84 sortedModes.reserve(modes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -080085 for (auto it = modes.begin(); it != modes.end(); ++it) {
Ady Abraham68636062022-11-16 17:07:25 -080086 sortedModes.push_back(it);
Dominik Laskowskib0054a22022-03-03 09:03:06 -080087 }
88
89 std::sort(sortedModes.begin(), sortedModes.end(), [](auto it1, auto it2) {
90 const auto& mode1 = it1->second;
91 const auto& mode2 = it2->second;
92
93 if (mode1->getVsyncPeriod() == mode2->getVsyncPeriod()) {
94 return mode1->getGroup() > mode2->getGroup();
95 }
96
97 return mode1->getVsyncPeriod() > mode2->getVsyncPeriod();
98 });
99
100 return sortedModes;
Marin Shalamanov46084422020-10-13 12:33:42 +0200101}
102
Ady Abraham68636062022-11-16 17:07:25 -0800103std::pair<unsigned, unsigned> divisorRange(Fps fps, FpsRange range,
104 RefreshRateSelector::Config::FrameRateOverride config) {
105 if (config != RefreshRateSelector::Config::FrameRateOverride::Enabled) {
106 return {1, 1};
107 }
108
109 using fps_approx_ops::operator/;
110 const auto start = std::max(1u, fps / range.max - 1);
111 const auto end = fps /
112 std::max(range.min, RefreshRateSelector::kMinSupportedFrameRate,
113 fps_approx_ops::operator<);
114
115 return {start, end};
116}
117
Ady Abraham8ca643a2022-10-18 18:26:47 -0700118bool shouldEnableFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800119 for (const auto it1 : sortedModes) {
120 const auto& mode1 = it1->second;
121 for (const auto it2 : sortedModes) {
122 const auto& mode2 = it2->second;
123
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400124 if (RefreshRateSelector::getFrameRateDivisor(mode1->getFps(), mode2->getFps()) >= 2) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800125 return true;
126 }
127 }
128 }
129 return false;
130}
131
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400132std::string toString(const RefreshRateSelector::PolicyVariant& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700133 using namespace std::string_literals;
134
135 return ftl::match(
136 policy,
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400137 [](const RefreshRateSelector::DisplayManagerPolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700138 return "DisplayManagerPolicy"s + policy.toString();
139 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400140 [](const RefreshRateSelector::OverridePolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700141 return "OverridePolicy"s + policy.toString();
142 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400143 [](RefreshRateSelector::NoOverridePolicy) { return "NoOverridePolicy"s; });
Dominik Laskowski36dced82022-09-02 09:24:00 -0700144}
145
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800146} // namespace
147
Ady Abraham68636062022-11-16 17:07:25 -0800148auto RefreshRateSelector::createFrameRateModes(
149 std::function<bool(const DisplayMode&)>&& filterModes, const FpsRange& renderRange) const
150 -> std::vector<FrameRateMode> {
151 struct Key {
152 Fps fps;
153 int32_t group;
154 };
155
156 struct KeyLess {
157 bool operator()(const Key& a, const Key& b) const {
158 using namespace fps_approx_ops;
159 if (a.fps != b.fps) {
160 return a.fps < b.fps;
161 }
162
163 // For the same fps the order doesn't really matter, but we still
164 // want the behaviour of a strictly less operator.
165 // We use the group id as the secondary ordering for that.
166 return a.group < b.group;
167 }
168 };
169
170 std::map<Key, DisplayModeIterator, KeyLess> ratesMap;
171 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
172 const auto& [id, mode] = *it;
173
174 if (!filterModes(*mode)) {
175 continue;
176 }
177 const auto [start, end] =
178 divisorRange(mode->getFps(), renderRange, mConfig.enableFrameRateOverride);
179 for (auto divisor = start; divisor <= end; divisor++) {
180 const auto fps = mode->getFps() / divisor;
181 using fps_approx_ops::operator<;
182 if (fps < kMinSupportedFrameRate) {
183 break;
184 }
185
186 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Enabled &&
187 !renderRange.includes(fps)) {
188 continue;
189 }
190
191 if (mConfig.enableFrameRateOverride ==
192 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
193 !isNativeRefreshRate(fps)) {
194 continue;
195 }
196
197 const auto [existingIter, emplaceHappened] =
198 ratesMap.try_emplace(Key{fps, mode->getGroup()}, it);
199 if (emplaceHappened) {
200 ALOGV("%s: including %s (%s)", __func__, to_string(fps).c_str(),
201 to_string(mode->getFps()).c_str());
202 } else {
203 // We might need to update the map as we found a lower refresh rate
204 if (isStrictlyLess(mode->getFps(), existingIter->second->second->getFps())) {
205 existingIter->second = it;
206 ALOGV("%s: changing %s (%s)", __func__, to_string(fps).c_str(),
207 to_string(mode->getFps()).c_str());
208 }
209 }
210 }
211 }
212
213 std::vector<FrameRateMode> frameRateModes;
214 frameRateModes.reserve(ratesMap.size());
215 for (const auto& [key, mode] : ratesMap) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800216 frameRateModes.emplace_back(FrameRateMode{key.fps, ftl::as_non_null(mode->second)});
Ady Abraham68636062022-11-16 17:07:25 -0800217 }
218
219 // We always want that the lowest frame rate will be corresponding to the
220 // lowest mode for power saving.
221 const auto lowestRefreshRateIt =
222 std::min_element(frameRateModes.begin(), frameRateModes.end(),
223 [](const FrameRateMode& lhs, const FrameRateMode& rhs) {
224 return isStrictlyLess(lhs.modePtr->getFps(),
225 rhs.modePtr->getFps());
226 });
227 frameRateModes.erase(frameRateModes.begin(), lowestRefreshRateIt);
228
229 return frameRateModes;
230}
231
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400232struct RefreshRateSelector::RefreshRateScoreComparator {
ramindanid72ba162022-09-09 21:33:40 +0000233 bool operator()(const RefreshRateScore& lhs, const RefreshRateScore& rhs) const {
Ady Abraham68636062022-11-16 17:07:25 -0800234 const auto& [frameRateMode, overallScore, _] = lhs;
ramindanid72ba162022-09-09 21:33:40 +0000235
Ady Abraham68636062022-11-16 17:07:25 -0800236 std::string name = to_string(frameRateMode);
237
ramindanid72ba162022-09-09 21:33:40 +0000238 ALOGV("%s sorting scores %.2f", name.c_str(), overallScore);
ramindanid72ba162022-09-09 21:33:40 +0000239 ATRACE_INT(name.c_str(), static_cast<int>(std::round(overallScore * 100)));
240
Ady Abraham68636062022-11-16 17:07:25 -0800241 if (!ScoredFrameRate::scoresEqual(overallScore, rhs.overallScore)) {
ramindanid72ba162022-09-09 21:33:40 +0000242 return overallScore > rhs.overallScore;
243 }
244
ramindanid72ba162022-09-09 21:33:40 +0000245 if (refreshRateOrder == RefreshRateOrder::Descending) {
246 using fps_approx_ops::operator>;
Ady Abraham68636062022-11-16 17:07:25 -0800247 return frameRateMode.fps > rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000248 } else {
249 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -0800250 return frameRateMode.fps < rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000251 }
252 }
253
254 const RefreshRateOrder refreshRateOrder;
255};
256
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400257std::string RefreshRateSelector::Policy::toString() const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700258 return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
Ady Abraham285f8c12022-10-11 17:12:14 -0700259 ", primaryRanges=%s, appRequestRanges=%s}",
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700260 defaultMode.value(), allowGroupSwitching ? "true" : "false",
Ady Abraham285f8c12022-10-11 17:12:14 -0700261 to_string(primaryRanges).c_str(),
262 to_string(appRequestRanges).c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200263}
264
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400265std::pair<nsecs_t, nsecs_t> RefreshRateSelector::getDisplayFrames(nsecs_t layerPeriod,
266 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800267 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
268 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
269 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
270 quotient++;
271 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800272 }
273
Ady Abraham62a0be22020-12-08 16:54:10 -0800274 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800275}
276
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400277float RefreshRateSelector::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
278 Fps refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200279 constexpr float kScoreForFractionalPairs = .8f;
280
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800281 const auto displayPeriod = refreshRate.getPeriodNsecs();
Ady Abraham62a0be22020-12-08 16:54:10 -0800282 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
283 if (layer.vote == LayerVoteType::ExplicitDefault) {
284 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200285 // that layerPeriod is the minimal period to render a frame.
286 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
287 // then the actualLayerPeriod will be 32ms, because it is the
288 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800289 auto actualLayerPeriod = displayPeriod;
290 int multiplier = 1;
291 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
292 multiplier++;
293 actualLayerPeriod = displayPeriod * multiplier;
294 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200295
296 // Because of the threshold we used above it's possible that score is slightly
297 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800298 return std::min(1.0f,
299 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
300 }
301
302 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
303 layer.vote == LayerVoteType::Heuristic) {
Ady Abraham68636062022-11-16 17:07:25 -0800304 const float multiplier = refreshRate.getValue() / layer.desiredRefreshRate.getValue();
305
306 // We only want to score this layer as a fractional pair if the content is not
307 // significantly faster than the display rate, at it would cause a significant frame drop.
308 // It is more appropriate to choose a higher display rate even if
309 // a pull-down will be required.
310 constexpr float kMinMultiplier = 0.25f;
311 if (multiplier >= kMinMultiplier &&
312 isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700313 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200314 }
315
Ady Abraham62a0be22020-12-08 16:54:10 -0800316 // Calculate how many display vsyncs we need to present a single frame for this
317 // layer
318 const auto [displayFramesQuotient, displayFramesRemainder] =
319 getDisplayFrames(layerPeriod, displayPeriod);
320 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
321 if (displayFramesRemainder == 0) {
322 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700323 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800324 }
325
326 if (displayFramesQuotient == 0) {
327 // Layer desired refresh rate is higher than the display rate.
328 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
329 (1.0f / (MAX_FRAMES_TO_FIT + 1));
330 }
331
332 // Layer desired refresh rate is lower than the display rate. Check how well it fits
333 // the cadence.
334 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
335 int iter = 2;
336 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
337 diff = diff - (displayPeriod - diff);
338 iter++;
339 }
340
Ady Abraham05243be2021-09-16 15:58:52 -0700341 return (1.0f / iter);
342 }
343
344 return 0;
345}
346
Ady Abraham68636062022-11-16 17:07:25 -0800347float RefreshRateSelector::calculateDistanceScoreFromMax(Fps refreshRate) const {
348 const auto& maxFps = mAppRequestFrameRates.back().fps;
349 const float ratio = refreshRate.getValue() / maxFps.getValue();
ramindanid72ba162022-09-09 21:33:40 +0000350 // Use ratio^2 to get a lower score the more we get further from peak
351 return ratio * ratio;
352}
353
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400354float RefreshRateSelector::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
355 bool isSeamlessSwitch) const {
Ady Abraham05243be2021-09-16 15:58:52 -0700356 // Slightly prefer seamless switches.
357 constexpr float kSeamedSwitchPenalty = 0.95f;
358 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
359
360 // If the layer wants Max, give higher score to the higher refresh rate
361 if (layer.vote == LayerVoteType::Max) {
Ady Abraham68636062022-11-16 17:07:25 -0800362 return calculateDistanceScoreFromMax(refreshRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800363 }
364
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800365 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800366 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Ady Abraham68636062022-11-16 17:07:25 -0800367 if (supportsAppFrameRateOverrideByContent()) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800368 // Since we support frame rate override, allow refresh rates which are
369 // multiples of the layer's request, as those apps would be throttled
370 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800371 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800372 }
373
Ady Abrahamcc315492022-02-17 17:06:39 -0800374 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800375 }
376
Ady Abrahamcc315492022-02-17 17:06:39 -0800377 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700378 // the highest score.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800379 if (getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700380 return 1.0f * seamlessness;
381 }
382
Ady Abrahamcc315492022-02-17 17:06:39 -0800383 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700384 // there is a small penalty attached to the score to favor the frame rates
385 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800386 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700387 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
388 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800389}
390
Ady Abraham68636062022-11-16 17:07:25 -0800391auto RefreshRateSelector::getRankedFrameRates(const std::vector<LayerRequirement>& layers,
392 GlobalSignals signals) const -> RankedFrameRates {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200393 std::lock_guard lock(mLock);
394
Ady Abraham68636062022-11-16 17:07:25 -0800395 if (mGetRankedFrameRatesCache &&
396 mGetRankedFrameRatesCache->arguments == std::make_pair(layers, signals)) {
397 return mGetRankedFrameRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200398 }
399
Ady Abraham68636062022-11-16 17:07:25 -0800400 const auto result = getRankedFrameRatesLocked(layers, signals);
401 mGetRankedFrameRatesCache = GetRankedFrameRatesCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200402 return result;
403}
404
Ady Abraham68636062022-11-16 17:07:25 -0800405auto RefreshRateSelector::getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
406 GlobalSignals signals) const
407 -> RankedFrameRates {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000408 using namespace fps_approx_ops;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800409 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800410 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700411
Ady Abrahamace3d052022-11-17 16:25:05 -0800412 const auto& activeMode = *getActiveModeLocked().modePtr;
ramindani38c84982022-08-29 18:02:57 +0000413
Ady Abraham68636062022-11-16 17:07:25 -0800414 // Keep the display at max frame rate for the duration of powering on the display.
ramindani38c84982022-08-29 18:02:57 +0000415 if (signals.powerOnImminent) {
416 ALOGV("Power On Imminent");
Ady Abraham68636062022-11-16 17:07:25 -0800417 return {rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Descending),
ramindanid72ba162022-09-09 21:33:40 +0000418 GlobalSignals{.powerOnImminent = true}};
ramindani38c84982022-08-29 18:02:57 +0000419 }
420
Ady Abraham8a82ba62020-01-17 12:43:17 -0800421 int noVoteLayers = 0;
422 int minVoteLayers = 0;
423 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800424 int explicitDefaultVoteLayers = 0;
425 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800426 int explicitExact = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100427 int seamedFocusedLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800428
Ady Abraham8a82ba62020-01-17 12:43:17 -0800429 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800430 switch (layer.vote) {
431 case LayerVoteType::NoVote:
432 noVoteLayers++;
433 break;
434 case LayerVoteType::Min:
435 minVoteLayers++;
436 break;
437 case LayerVoteType::Max:
438 maxVoteLayers++;
439 break;
440 case LayerVoteType::ExplicitDefault:
441 explicitDefaultVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800442 break;
443 case LayerVoteType::ExplicitExactOrMultiple:
444 explicitExactOrMultipleVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800445 break;
446 case LayerVoteType::ExplicitExact:
447 explicitExact++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800448 break;
449 case LayerVoteType::Heuristic:
450 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800451 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200452
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100453 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
454 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200455 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800456 }
457
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800458 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
459 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700460
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200461 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800462 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700463
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200464 // If the default mode group is different from the group of current mode,
465 // this means a layer requesting a seamed mode switch just disappeared and
466 // we should switch back to the default group.
467 // However if a seamed layer is still present we anchor around the group
468 // of the current mode, in order to prevent unnecessary seamed mode switches
469 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800470 const auto anchorGroup =
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700471 seamedFocusedLayers > 0 ? activeMode.getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200472
Steven Thomasf734df42020-04-13 21:09:28 -0700473 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
474 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800475 if (signals.touch && !hasExplicitVoteLayers) {
ramindanid72ba162022-09-09 21:33:40 +0000476 ALOGV("Touch Boost");
Ady Abraham68636062022-11-16 17:07:25 -0800477 return {rankFrameRates(anchorGroup, RefreshRateOrder::Descending),
ramindanid72ba162022-09-09 21:33:40 +0000478 GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800479 }
480
Alec Mouri11232a22020-05-14 18:06:25 -0700481 // If the primary range consists of a single refresh rate then we can only
482 // move out the of range if layers explicitly request a different refresh
483 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100484 const bool primaryRangeIsSingleRate =
Ady Abraham285f8c12022-10-11 17:12:14 -0700485 isApproxEqual(policy->primaryRanges.physical.min, policy->primaryRanges.physical.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700486
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800487 if (!signals.touch && signals.idle && !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
ramindanid72ba162022-09-09 21:33:40 +0000488 ALOGV("Idle");
Ady Abraham68636062022-11-16 17:07:25 -0800489 return {rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending),
ramindanid72ba162022-09-09 21:33:40 +0000490 GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700491 }
492
Steven Thomasdebafed2020-05-18 17:30:35 -0700493 if (layers.empty() || noVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000494 ALOGV("No layers with votes");
Ady Abraham68636062022-11-16 17:07:25 -0800495 return {rankFrameRates(anchorGroup, RefreshRateOrder::Descending), kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700496 }
497
Ady Abraham8a82ba62020-01-17 12:43:17 -0800498 // Only if all layers want Min we should return Min
499 if (noVoteLayers + minVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000500 ALOGV("All layers Min");
Ady Abraham68636062022-11-16 17:07:25 -0800501 return {rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending), kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800502 }
503
Ady Abraham8a82ba62020-01-17 12:43:17 -0800504 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800505 std::vector<RefreshRateScore> scores;
Ady Abraham68636062022-11-16 17:07:25 -0800506 scores.reserve(mAppRequestFrameRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800507
Ady Abraham68636062022-11-16 17:07:25 -0800508 for (const FrameRateMode& it : mAppRequestFrameRates) {
509 scores.emplace_back(RefreshRateScore{it, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800510 }
511
512 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700513 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700514 ftl::enum_string(layer.vote).c_str(), layer.weight,
rnlee3bd610662021-06-23 16:27:57 -0700515 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800516 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800517 continue;
518 }
519
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800520 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800521
Ady Abraham68636062022-11-16 17:07:25 -0800522 for (auto& [mode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
523 const auto& [fps, modePtr] = mode;
524 const bool isSeamlessSwitch = modePtr->getGroup() == activeMode.getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200525
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100526 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100527 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800528 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700529 to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200530 continue;
531 }
532
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100533 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
534 !layer.focused) {
535 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100536 " Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800537 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700538 to_string(activeMode).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100539 continue;
540 }
541
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100542 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100543 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100544 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100545 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
546 // disappeared.
Ady Abraham68636062022-11-16 17:07:25 -0800547 const bool isInPolicyForDefault = modePtr->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100548 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100549 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham68636062022-11-16 17:07:25 -0800550 to_string(*modePtr).c_str(), to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200551 continue;
552 }
553
Ady Abraham68636062022-11-16 17:07:25 -0800554 const bool inPrimaryRange = policy->primaryRanges.physical.includes(modePtr->getFps());
Alec Mouri11232a22020-05-14 18:06:25 -0700555 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800556 !(layer.focused &&
557 (layer.vote == LayerVoteType::ExplicitDefault ||
558 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700559 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700560 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700561 continue;
562 }
563
Ady Abraham68636062022-11-16 17:07:25 -0800564 const float layerScore = calculateLayerScoreLocked(layer, fps, isSeamlessSwitch);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000565 const float weightedLayerScore = weight * layerScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800566
Ady Abraham13cfb362022-08-13 05:12:13 +0000567 // Layer with fixed source has a special consideration which depends on the
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000568 // mConfig.frameRateMultipleThreshold. We don't want these layers to score
569 // refresh rates above the threshold, but we also don't want to favor the lower
570 // ones by having a greater number of layers scoring them. Instead, we calculate
571 // the score independently for these layers and later decide which
572 // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
573 // score 120 Hz, but desired 60 fps should contribute to the score.
574 const bool fixedSourceLayer = [](LayerVoteType vote) {
575 switch (vote) {
576 case LayerVoteType::ExplicitExactOrMultiple:
577 case LayerVoteType::Heuristic:
578 return true;
579 case LayerVoteType::NoVote:
580 case LayerVoteType::Min:
581 case LayerVoteType::Max:
582 case LayerVoteType::ExplicitDefault:
583 case LayerVoteType::ExplicitExact:
584 return false;
585 }
586 }(layer.vote);
Ady Abraham62f51d92022-08-24 22:20:22 +0000587 const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000588 layer.desiredRefreshRate <
589 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
Ady Abraham62f51d92022-08-24 22:20:22 +0000590 if (fixedSourceLayer && layerBelowThreshold) {
Ady Abraham13cfb362022-08-13 05:12:13 +0000591 const bool modeAboveThreshold =
Ady Abraham68636062022-11-16 17:07:25 -0800592 modePtr->getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
Ady Abraham62f51d92022-08-24 22:20:22 +0000593 if (modeAboveThreshold) {
Ady Abraham68636062022-11-16 17:07:25 -0800594 ALOGV("%s gives %s (%s) fixed source (above threshold) score of %.4f",
595 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
596 to_string(modePtr->getFps()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000597 fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000598 } else {
Ady Abraham68636062022-11-16 17:07:25 -0800599 ALOGV("%s gives %s (%s) fixed source (below threshold) score of %.4f",
600 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
601 to_string(modePtr->getFps()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000602 fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000603 }
604 } else {
Ady Abraham68636062022-11-16 17:07:25 -0800605 ALOGV("%s gives %s (%s) score of %.4f", formatLayerInfo(layer, weight).c_str(),
606 to_string(fps).c_str(), to_string(modePtr->getFps()).c_str(), layerScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000607 overallScore += weightedLayerScore;
608 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800609 }
610 }
611
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000612 // We want to find the best refresh rate without the fixed source layers,
Ady Abraham62f51d92022-08-24 22:20:22 +0000613 // so we could know whether we should add the modeAboveThreshold scores or not.
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000614 // If the best refresh rate is already above the threshold, it means that
615 // some non-fixed source layers already scored it, so we can just add the score
616 // for all fixed source layers, even the ones that are above the threshold.
617 const bool maxScoreAboveThreshold = [&] {
618 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
619 return false;
620 }
621
622 const auto maxScoreIt =
623 std::max_element(scores.begin(), scores.end(),
624 [](RefreshRateScore max, RefreshRateScore current) {
Ady Abraham68636062022-11-16 17:07:25 -0800625 return current.overallScore > max.overallScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000626 });
Ady Abraham68636062022-11-16 17:07:25 -0800627 ALOGV("%s (%s) is the best refresh rate without fixed source layers. It is %s the "
628 "threshold for "
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000629 "refresh rate multiples",
Ady Abraham68636062022-11-16 17:07:25 -0800630 to_string(maxScoreIt->frameRateMode.fps).c_str(),
631 to_string(maxScoreIt->frameRateMode.modePtr->getFps()).c_str(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000632 maxScoreAboveThreshold ? "above" : "below");
Ady Abraham68636062022-11-16 17:07:25 -0800633 return maxScoreIt->frameRateMode.modePtr->getFps() >=
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000634 Fps::fromValue(mConfig.frameRateMultipleThreshold);
635 }();
636
637 // Now we can add the fixed rate layers score
Ady Abraham68636062022-11-16 17:07:25 -0800638 for (auto& [frameRateMode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000639 overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000640 if (maxScoreAboveThreshold) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000641 overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000642 }
Ady Abraham68636062022-11-16 17:07:25 -0800643 ALOGV("%s (%s) adjusted overallScore is %.4f", to_string(frameRateMode.fps).c_str(),
644 to_string(frameRateMode.modePtr->getFps()).c_str(), overallScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000645 }
646
647 // Now that we scored all the refresh rates we need to pick the one that got the highest
ramindanid72ba162022-09-09 21:33:40 +0000648 // overallScore. Sort the scores based on their overallScore in descending order of priority.
649 const RefreshRateOrder refreshRateOrder =
650 maxVoteLayers > 0 ? RefreshRateOrder::Descending : RefreshRateOrder::Ascending;
651 std::sort(scores.begin(), scores.end(),
652 RefreshRateScoreComparator{.refreshRateOrder = refreshRateOrder});
ramindanid72ba162022-09-09 21:33:40 +0000653
Ady Abraham68636062022-11-16 17:07:25 -0800654 FrameRateRanking ranking;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400655 ranking.reserve(scores.size());
656
657 std::transform(scores.begin(), scores.end(), back_inserter(ranking),
ramindanid72ba162022-09-09 21:33:40 +0000658 [](const RefreshRateScore& score) {
Ady Abraham68636062022-11-16 17:07:25 -0800659 return ScoredFrameRate{score.frameRateMode, score.overallScore};
ramindanid72ba162022-09-09 21:33:40 +0000660 });
Ady Abraham34702102020-02-10 14:12:05 -0800661
Ady Abraham37d46922022-10-05 13:08:51 -0700662 const bool noLayerScore = std::all_of(scores.begin(), scores.end(), [](RefreshRateScore score) {
663 return score.overallScore == 0;
664 });
665
Alec Mouri11232a22020-05-14 18:06:25 -0700666 if (primaryRangeIsSingleRate) {
667 // If we never scored any layers, then choose the rate from the primary
668 // range instead of picking a random score from the app range.
Ady Abraham37d46922022-10-05 13:08:51 -0700669 if (noLayerScore) {
ramindanid72ba162022-09-09 21:33:40 +0000670 ALOGV("Layers not scored");
Ady Abraham68636062022-11-16 17:07:25 -0800671 return {rankFrameRates(anchorGroup, RefreshRateOrder::Descending), kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700672 } else {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400673 return {ranking, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700674 }
675 }
676
Steven Thomasf734df42020-04-13 21:09:28 -0700677 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
678 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
679 // vote we should not change it if we get a touch event. Only apply touch boost if it will
680 // actually increase the refresh rate over the normal selection.
Ady Abraham5e4e9832021-06-14 13:40:56 -0700681 const bool touchBoostForExplicitExact = [&] {
Ady Abraham68636062022-11-16 17:07:25 -0800682 if (supportsAppFrameRateOverrideByContent()) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700683 // Enable touch boost if there are other layers besides exact
684 return explicitExact + noVoteLayers != layers.size();
685 } else {
686 // Enable touch boost if there are no exact layers
687 return explicitExact == 0;
688 }
689 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700690
Ady Abraham68636062022-11-16 17:07:25 -0800691 const auto touchRefreshRates = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700692 using fps_approx_ops::operator<;
693
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800694 if (signals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Ady Abraham68636062022-11-16 17:07:25 -0800695 scores.front().frameRateMode.fps < touchRefreshRates.front().frameRateMode.fps) {
ramindanid72ba162022-09-09 21:33:40 +0000696 ALOGV("Touch Boost");
697 return {touchRefreshRates, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700698 }
699
Ady Abraham37d46922022-10-05 13:08:51 -0700700 // If we never scored any layers, and we don't favor high refresh rates, prefer to stay with the
701 // current config
702 if (noLayerScore && refreshRateOrder == RefreshRateOrder::Ascending) {
703 const auto preferredDisplayMode = activeMode.getId();
Ady Abraham68636062022-11-16 17:07:25 -0800704 return {rankFrameRates(anchorGroup, RefreshRateOrder::Ascending, preferredDisplayMode),
Ady Abraham37d46922022-10-05 13:08:51 -0700705 kNoSignals};
706 }
707
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400708 return {ranking, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800709}
710
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400711using LayerRequirementPtrs = std::vector<const RefreshRateSelector::LayerRequirement*>;
712using PerUidLayerRequirements = std::unordered_map<uid_t, LayerRequirementPtrs>;
713
714PerUidLayerRequirements groupLayersByUid(
715 const std::vector<RefreshRateSelector::LayerRequirement>& layers) {
716 PerUidLayerRequirements layersByUid;
Ady Abraham62a0be22020-12-08 16:54:10 -0800717 for (const auto& layer : layers) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400718 const auto it = layersByUid.emplace(layer.ownerUid, LayerRequirementPtrs()).first;
719 auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800720 layersWithSameUid.push_back(&layer);
721 }
722
723 // Remove uids that can't have a frame rate override
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400724 for (auto it = layersByUid.begin(); it != layersByUid.end();) {
725 const auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800726 bool skipUid = false;
727 for (const auto& layer : layersWithSameUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400728 using LayerVoteType = RefreshRateSelector::LayerVoteType;
729
730 if (layer->vote == LayerVoteType::Max || layer->vote == LayerVoteType::Heuristic) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800731 skipUid = true;
732 break;
733 }
734 }
735 if (skipUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400736 it = layersByUid.erase(it);
Ady Abraham62a0be22020-12-08 16:54:10 -0800737 } else {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400738 ++it;
Ady Abraham62a0be22020-12-08 16:54:10 -0800739 }
740 }
741
742 return layersByUid;
743}
744
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400745auto RefreshRateSelector::getFrameRateOverrides(const std::vector<LayerRequirement>& layers,
746 Fps displayRefreshRate,
747 GlobalSignals globalSignals) const
748 -> UidToFrameRateOverride {
Ady Abraham62a0be22020-12-08 16:54:10 -0800749 ATRACE_CALL();
Ady Abraham68636062022-11-16 17:07:25 -0800750 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Disabled) {
751 return {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800752 }
753
Ady Abraham68636062022-11-16 17:07:25 -0800754 ALOGV("%s: %zu layers", __func__, layers.size());
755 std::lock_guard lock(mLock);
756
Ady Abraham8ca643a2022-10-18 18:26:47 -0700757 const auto* policyPtr = getCurrentPolicyLocked();
758 // We don't want to run lower than 30fps
759 const Fps minFrameRate = std::max(policyPtr->appRequestRanges.render.min, 30_Hz, isApproxLess);
760
761 using fps_approx_ops::operator/;
762 const unsigned numMultiples = displayRefreshRate / minFrameRate;
763
764 std::vector<std::pair<Fps, float>> scoredFrameRates;
765 scoredFrameRates.reserve(numMultiples);
766
767 for (unsigned n = numMultiples; n > 0; n--) {
768 const Fps divisor = displayRefreshRate / n;
769 if (mConfig.enableFrameRateOverride ==
Ady Abraham68636062022-11-16 17:07:25 -0800770 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
771 !isNativeRefreshRate(divisor)) {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700772 continue;
773 }
774
775 if (policyPtr->appRequestRanges.render.includes(divisor)) {
776 ALOGV("%s: adding %s as a potential frame rate", __func__, to_string(divisor).c_str());
777 scoredFrameRates.emplace_back(divisor, 0);
778 }
779 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800780
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400781 const auto layersByUid = groupLayersByUid(layers);
Ady Abraham62a0be22020-12-08 16:54:10 -0800782 UidToFrameRateOverride frameRateOverrides;
783 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800784 // Layers with ExplicitExactOrMultiple expect touch boost
785 const bool hasExplicitExactOrMultiple =
786 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
787 [](const auto& layer) {
788 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
789 });
790
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700791 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800792 continue;
793 }
794
Ady Abraham8ca643a2022-10-18 18:26:47 -0700795 for (auto& [_, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800796 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -0800797 }
798
799 for (const auto& layer : layersWithSameUid) {
800 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
801 continue;
802 }
803
804 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800805 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
806 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700807 for (auto& [fps, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800808 constexpr bool isSeamlessSwitch = true;
Ady Abraham8ca643a2022-10-18 18:26:47 -0700809 const auto layerScore = calculateLayerScoreLocked(*layer, fps, isSeamlessSwitch);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800810 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -0800811 }
812 }
813
Ady Abraham62a0be22020-12-08 16:54:10 -0800814 // If we never scored any layers, we don't have a preferred frame rate
Ady Abraham8ca643a2022-10-18 18:26:47 -0700815 if (std::all_of(scoredFrameRates.begin(), scoredFrameRates.end(),
816 [](const auto& scoredFrameRate) {
817 const auto [_, score] = scoredFrameRate;
818 return score == 0;
819 })) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800820 continue;
821 }
822
ramindanid72ba162022-09-09 21:33:40 +0000823 // Now that we scored all the refresh rates we need to pick the lowest refresh rate
824 // that got the highest score.
Ady Abraham8ca643a2022-10-18 18:26:47 -0700825 const auto [overrideFps, _] =
826 *std::max_element(scoredFrameRates.begin(), scoredFrameRates.end(),
827 [](const auto& lhsPair, const auto& rhsPair) {
828 const float lhs = lhsPair.second;
829 const float rhs = rhsPair.second;
Ady Abraham68636062022-11-16 17:07:25 -0800830 return lhs < rhs && !ScoredFrameRate::scoresEqual(lhs, rhs);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700831 });
832 ALOGV("%s: overriding to %s for uid=%d", __func__, to_string(overrideFps).c_str(), uid);
833 frameRateOverrides.emplace(uid, overrideFps);
Ady Abraham62a0be22020-12-08 16:54:10 -0800834 }
835
836 return frameRateOverrides;
837}
838
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400839std::optional<Fps> RefreshRateSelector::onKernelTimerChanged(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800840 std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800841 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100842
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800843 const DisplayModePtr& current = desiredActiveModeId
844 ? mDisplayModes.get(*desiredActiveModeId)->get()
Ady Abrahamace3d052022-11-17 16:25:05 -0800845 : getActiveModeLocked().modePtr.get();
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100846
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800847 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
848 if (current == min) {
849 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100850 }
851
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800852 const auto& mode = timerExpired ? min : current;
853 return mode->getFps();
Steven Thomasf734df42020-04-13 21:09:28 -0700854}
855
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400856const DisplayModePtr& RefreshRateSelector::getMinRefreshRateByPolicyLocked() const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800857 const auto& activeMode = *getActiveModeLocked().modePtr;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700858
Ady Abraham68636062022-11-16 17:07:25 -0800859 for (const FrameRateMode& mode : mPrimaryFrameRates) {
860 if (activeMode.getGroup() == mode.modePtr->getGroup()) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800861 return mode.modePtr.get();
Marin Shalamanov46084422020-10-13 12:33:42 +0200862 }
863 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800864
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700865 ALOGE("Can't find min refresh rate by policy with the same mode group as the current mode %s",
866 to_string(activeMode).c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800867
868 // Default to the lowest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -0800869 return mPrimaryFrameRates.front().modePtr.get();
Ady Abraham2139f732019-11-13 18:56:40 -0800870}
871
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400872const DisplayModePtr& RefreshRateSelector::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800873 const ftl::NonNull<DisplayModePtr>* maxByAnchor = &mPrimaryFrameRates.back().modePtr;
874 const ftl::NonNull<DisplayModePtr>* max = &mPrimaryFrameRates.back().modePtr;
Ady Abraham68636062022-11-16 17:07:25 -0800875
876 bool maxByAnchorFound = false;
877 for (auto it = mPrimaryFrameRates.rbegin(); it != mPrimaryFrameRates.rend(); ++it) {
878 using namespace fps_approx_ops;
879 if (it->modePtr->getFps() > (*max)->getFps()) {
880 max = &it->modePtr;
Marin Shalamanov46084422020-10-13 12:33:42 +0200881 }
Ady Abraham68636062022-11-16 17:07:25 -0800882
883 if (anchorGroup == it->modePtr->getGroup() &&
884 it->modePtr->getFps() >= (*maxByAnchor)->getFps()) {
885 maxByAnchorFound = true;
886 maxByAnchor = &it->modePtr;
887 }
888 }
889
890 if (maxByAnchorFound) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800891 return maxByAnchor->get();
Marin Shalamanov46084422020-10-13 12:33:42 +0200892 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800893
ramindanid72ba162022-09-09 21:33:40 +0000894 ALOGE("Can't find max refresh rate by policy with the same group %d", anchorGroup);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800895
896 // Default to the highest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -0800897 return max->get();
Ady Abraham2139f732019-11-13 18:56:40 -0800898}
899
Ady Abraham68636062022-11-16 17:07:25 -0800900auto RefreshRateSelector::rankFrameRates(std::optional<int> anchorGroupOpt,
901 RefreshRateOrder refreshRateOrder,
902 std::optional<DisplayModeId> preferredDisplayModeOpt) const
903 -> FrameRateRanking {
904 const char* const whence = __func__;
905 std::deque<ScoredFrameRate> ranking;
906 const auto rankFrameRate = [&](const FrameRateMode& frameRateMode) REQUIRES(mLock) {
907 const auto& modePtr = frameRateMode.modePtr;
908 if (anchorGroupOpt && modePtr->getGroup() != anchorGroupOpt) {
Ady Abraham37d46922022-10-05 13:08:51 -0700909 return;
ramindanid72ba162022-09-09 21:33:40 +0000910 }
Ady Abraham37d46922022-10-05 13:08:51 -0700911
Ady Abraham68636062022-11-16 17:07:25 -0800912 float score = calculateDistanceScoreFromMax(frameRateMode.fps);
Ady Abraham37d46922022-10-05 13:08:51 -0700913 const bool inverseScore = (refreshRateOrder == RefreshRateOrder::Ascending);
914 if (inverseScore) {
915 score = 1.0f / score;
916 }
917 if (preferredDisplayModeOpt) {
Ady Abraham68636062022-11-16 17:07:25 -0800918 if (*preferredDisplayModeOpt == modePtr->getId()) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400919 constexpr float kScore = std::numeric_limits<float>::max();
Ady Abraham68636062022-11-16 17:07:25 -0800920 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
Ady Abraham37d46922022-10-05 13:08:51 -0700921 return;
922 }
923 constexpr float kNonPreferredModePenalty = 0.95f;
924 score *= kNonPreferredModePenalty;
925 }
Ady Abraham68636062022-11-16 17:07:25 -0800926 ALOGV("%s(%s) %s (%s) scored %.2f", whence, ftl::enum_string(refreshRateOrder).c_str(),
927 to_string(frameRateMode.fps).c_str(), to_string(modePtr->getFps()).c_str(), score);
928 ranking.emplace_back(ScoredFrameRate{frameRateMode, score});
ramindanid72ba162022-09-09 21:33:40 +0000929 };
930
931 if (refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abraham68636062022-11-16 17:07:25 -0800932 std::for_each(mPrimaryFrameRates.begin(), mPrimaryFrameRates.end(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +0000933 } else {
Ady Abraham68636062022-11-16 17:07:25 -0800934 std::for_each(mPrimaryFrameRates.rbegin(), mPrimaryFrameRates.rend(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +0000935 }
936
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400937 if (!ranking.empty() || !anchorGroupOpt) {
938 return {ranking.begin(), ranking.end()};
ramindanid72ba162022-09-09 21:33:40 +0000939 }
940
941 ALOGW("Can't find %s refresh rate by policy with the same mode group"
942 " as the mode group %d",
943 refreshRateOrder == RefreshRateOrder::Ascending ? "min" : "max", anchorGroupOpt.value());
944
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400945 constexpr std::optional<int> kNoAnchorGroup = std::nullopt;
Ady Abraham68636062022-11-16 17:07:25 -0800946 return rankFrameRates(kNoAnchorGroup, refreshRateOrder, preferredDisplayModeOpt);
ramindanid72ba162022-09-09 21:33:40 +0000947}
948
Ady Abrahamace3d052022-11-17 16:25:05 -0800949FrameRateMode RefreshRateSelector::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800950 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -0800951 return getActiveModeLocked();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700952}
953
Ady Abrahamace3d052022-11-17 16:25:05 -0800954const FrameRateMode& RefreshRateSelector::getActiveModeLocked() const {
955 return *mActiveModeOpt;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700956}
957
Ady Abrahamace3d052022-11-17 16:25:05 -0800958void RefreshRateSelector::setActiveMode(DisplayModeId modeId, Fps renderFrameRate) {
Ady Abraham2139f732019-11-13 18:56:40 -0800959 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200960
Ady Abraham68636062022-11-16 17:07:25 -0800961 // Invalidate the cached invocation to getRankedFrameRates. This forces
962 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
963 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200964
Ady Abrahamace3d052022-11-17 16:25:05 -0800965 const auto activeModeOpt = mDisplayModes.get(modeId);
966 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
967
968 mActiveModeOpt.emplace(FrameRateMode{renderFrameRate, ftl::as_non_null(activeModeOpt->get())});
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800969}
970
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400971RefreshRateSelector::RefreshRateSelector(DisplayModes modes, DisplayModeId activeModeId,
972 Config config)
rnlee3bd610662021-06-23 16:27:57 -0700973 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700974 initializeIdleTimer();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700975 FTL_FAKE_GUARD(kMainThreadContext, updateDisplayModes(std::move(modes), activeModeId));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100976}
977
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400978void RefreshRateSelector::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +0000979 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700980 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +0000981 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800982 [this] {
983 std::scoped_lock lock(mIdleTimerCallbacksMutex);
984 if (const auto callbacks = getIdleTimerCallbacks()) {
985 callbacks->onReset();
986 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700987 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800988 [this] {
989 std::scoped_lock lock(mIdleTimerCallbacksMutex);
990 if (const auto callbacks = getIdleTimerCallbacks()) {
991 callbacks->onExpired();
992 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700993 });
Ady Abraham9a2ea342021-09-03 17:32:34 -0700994 }
995}
996
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400997void RefreshRateSelector::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100998 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200999
Ady Abraham68636062022-11-16 17:07:25 -08001000 // Invalidate the cached invocation to getRankedFrameRates. This forces
1001 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1002 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001003
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001004 mDisplayModes = std::move(modes);
Ady Abrahamace3d052022-11-17 16:25:05 -08001005 const auto activeModeOpt = mDisplayModes.get(activeModeId);
1006 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1007 mActiveModeOpt =
1008 FrameRateMode{activeModeOpt->get()->getFps(), ftl::as_non_null(activeModeOpt->get())};
Ady Abrahamabc27602020-04-08 17:20:29 -07001009
Ady Abraham68636062022-11-16 17:07:25 -08001010 const auto sortedModes = sortByRefreshRate(mDisplayModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001011 mMinRefreshRateModeIt = sortedModes.front();
1012 mMaxRefreshRateModeIt = sortedModes.back();
1013
Marin Shalamanov75f37252021-02-10 21:43:57 +01001014 // Reset the policy because the old one may no longer be valid.
1015 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001016 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -08001017
Ady Abraham8ca643a2022-10-18 18:26:47 -07001018 mFrameRateOverrideConfig = [&] {
1019 switch (mConfig.enableFrameRateOverride) {
1020 case Config::FrameRateOverride::Disabled:
Ady Abraham68636062022-11-16 17:07:25 -08001021 case Config::FrameRateOverride::AppOverride:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001022 case Config::FrameRateOverride::Enabled:
1023 return mConfig.enableFrameRateOverride;
Ady Abraham68636062022-11-16 17:07:25 -08001024 case Config::FrameRateOverride::AppOverrideNativeRefreshRates:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001025 return shouldEnableFrameRateOverride(sortedModes)
Ady Abraham68636062022-11-16 17:07:25 -08001026 ? Config::FrameRateOverride::AppOverrideNativeRefreshRates
Ady Abraham8ca643a2022-10-18 18:26:47 -07001027 : Config::FrameRateOverride::Disabled;
1028 }
1029 }();
Ady Abraham4899ff82021-01-06 13:53:29 -08001030
Ady Abraham68636062022-11-16 17:07:25 -08001031 if (mConfig.enableFrameRateOverride ==
1032 Config::FrameRateOverride::AppOverrideNativeRefreshRates) {
1033 for (const auto& [_, mode] : mDisplayModes) {
1034 mAppOverrideNativeRefreshRates.try_emplace(mode->getFps(), ftl::unit);
1035 }
1036 }
1037
Ady Abrahamabc27602020-04-08 17:20:29 -07001038 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001039}
1040
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001041bool RefreshRateSelector::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001042 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001043 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
Ady Abraham285f8c12022-10-11 17:12:14 -07001044 if (!policy.primaryRanges.physical.includes(mode->get()->getFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001045 ALOGE("Default mode is not in the primary range.");
1046 return false;
1047 }
1048 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001049 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -07001050 return false;
1051 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001052
Ady Abraham68636062022-11-16 17:07:25 -08001053 const auto& primaryRanges = policy.primaryRanges;
1054 const auto& appRequestRanges = policy.appRequestRanges;
1055 ALOGE_IF(!appRequestRanges.physical.includes(primaryRanges.physical),
1056 "Physical range is invalid");
1057 ALOGE_IF(!appRequestRanges.render.includes(primaryRanges.render), "Render range is invalid");
1058
1059 return primaryRanges.valid() && appRequestRanges.valid();
Steven Thomasd4071902020-03-24 16:02:53 -07001060}
1061
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001062auto RefreshRateSelector::setPolicy(const PolicyVariant& policy) -> SetPolicyResult {
Dominik Laskowski36dced82022-09-02 09:24:00 -07001063 Policy oldPolicy;
Ady Abrahamace3d052022-11-17 16:25:05 -08001064 PhysicalDisplayId displayId;
Dominik Laskowski36dced82022-09-02 09:24:00 -07001065 {
1066 std::lock_guard lock(mLock);
1067 oldPolicy = *getCurrentPolicyLocked();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001068
Dominik Laskowski36dced82022-09-02 09:24:00 -07001069 const bool valid = ftl::match(
1070 policy,
1071 [this](const auto& policy) {
1072 ftl::FakeGuard guard(mLock);
1073 if (!isPolicyValidLocked(policy)) {
1074 ALOGE("Invalid policy: %s", policy.toString().c_str());
1075 return false;
1076 }
1077
1078 using T = std::decay_t<decltype(policy)>;
1079
1080 if constexpr (std::is_same_v<T, DisplayManagerPolicy>) {
1081 mDisplayManagerPolicy = policy;
1082 } else {
1083 static_assert(std::is_same_v<T, OverridePolicy>);
1084 mOverridePolicy = policy;
1085 }
1086 return true;
1087 },
1088 [this](NoOverridePolicy) {
1089 ftl::FakeGuard guard(mLock);
1090 mOverridePolicy.reset();
1091 return true;
1092 });
1093
1094 if (!valid) {
1095 return SetPolicyResult::Invalid;
1096 }
1097
Ady Abraham68636062022-11-16 17:07:25 -08001098 mGetRankedFrameRatesCache.reset();
Dominik Laskowski36dced82022-09-02 09:24:00 -07001099
1100 if (*getCurrentPolicyLocked() == oldPolicy) {
1101 return SetPolicyResult::Unchanged;
1102 }
1103 constructAvailableRefreshRates();
Ady Abrahamace3d052022-11-17 16:25:05 -08001104
1105 displayId = getActiveModeLocked().modePtr->getPhysicalDisplayId();
Steven Thomasd4071902020-03-24 16:02:53 -07001106 }
Dominik Laskowski36dced82022-09-02 09:24:00 -07001107
Dominik Laskowski36dced82022-09-02 09:24:00 -07001108 const unsigned numModeChanges = std::exchange(mNumModeSwitchesInPolicy, 0u);
1109
1110 ALOGI("Display %s policy changed\n"
1111 "Previous: %s\n"
1112 "Current: %s\n"
1113 "%u mode changes were performed under the previous policy",
1114 to_string(displayId).c_str(), oldPolicy.toString().c_str(), toString(policy).c_str(),
1115 numModeChanges);
1116
1117 return SetPolicyResult::Changed;
Steven Thomasd4071902020-03-24 16:02:53 -07001118}
1119
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001120auto RefreshRateSelector::getCurrentPolicyLocked() const -> const Policy* {
Steven Thomasd4071902020-03-24 16:02:53 -07001121 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
1122}
1123
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001124auto RefreshRateSelector::getCurrentPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001125 std::lock_guard lock(mLock);
1126 return *getCurrentPolicyLocked();
1127}
1128
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001129auto RefreshRateSelector::getDisplayManagerPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001130 std::lock_guard lock(mLock);
1131 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001132}
1133
Ady Abrahamace3d052022-11-17 16:25:05 -08001134bool RefreshRateSelector::isModeAllowed(const FrameRateMode& mode) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001135 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001136 return std::find(mAppRequestFrameRates.begin(), mAppRequestFrameRates.end(), mode) !=
1137 mAppRequestFrameRates.end();
Ady Abraham2139f732019-11-13 18:56:40 -08001138}
1139
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001140void RefreshRateSelector::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001141 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -07001142 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001143 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -07001144
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001145 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -08001146
Ady Abraham68636062022-11-16 17:07:25 -08001147 const auto filterRefreshRates = [&](const FpsRanges& ranges,
1148 const char* rangeName) REQUIRES(mLock) {
1149 const auto filterModes = [&](const DisplayMode& mode) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001150 return mode.getResolution() == defaultMode->getResolution() &&
1151 mode.getDpi() == defaultMode->getDpi() &&
1152 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
Ady Abraham68636062022-11-16 17:07:25 -08001153 ranges.physical.includes(mode.getFps()) &&
1154 (supportsFrameRateOverride() || ranges.render.includes(mode.getFps()));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001155 };
Ady Abraham8a82ba62020-01-17 12:43:17 -08001156
Ady Abraham68636062022-11-16 17:07:25 -08001157 const auto frameRateModes = createFrameRateModes(filterModes, ranges.render);
1158 LOG_ALWAYS_FATAL_IF(frameRateModes.empty(),
1159 "No matching frame rate modes for %s physicalRange %s", rangeName,
1160 to_string(ranges.physical).c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -08001161
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001162 const auto stringifyModes = [&] {
1163 std::string str;
Ady Abraham68636062022-11-16 17:07:25 -08001164 for (const auto& frameRateMode : frameRateModes) {
1165 str += to_string(frameRateMode) + " ";
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001166 }
1167 return str;
1168 };
Ady Abraham68636062022-11-16 17:07:25 -08001169 ALOGV("%s render rates: %s", rangeName, stringifyModes().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -07001170
Ady Abraham68636062022-11-16 17:07:25 -08001171 return frameRateModes;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001172 };
1173
Ady Abraham68636062022-11-16 17:07:25 -08001174 mPrimaryFrameRates = filterRefreshRates(policy->primaryRanges, "primary");
1175 mAppRequestFrameRates = filterRefreshRates(policy->appRequestRanges, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -08001176}
1177
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001178Fps RefreshRateSelector::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001179 using namespace fps_approx_ops;
1180
1181 if (frameRate <= mKnownFrameRates.front()) {
1182 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001183 }
1184
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001185 if (frameRate >= mKnownFrameRates.back()) {
1186 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001187 }
1188
Marin Shalamanove8a663d2020-11-24 17:48:00 +01001189 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001190 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001191
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001192 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
1193 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001194 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
1195}
1196
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001197auto RefreshRateSelector::getIdleTimerAction() const -> KernelIdleTimerAction {
Ana Krulecb9afd792020-06-11 13:16:15 -07001198 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001199
1200 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getFps();
1201 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -07001202
1203 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
1204 // the min allowed refresh rate is higher than the device min, we do not want to enable the
1205 // timer.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001206 if (isStrictlyLess(deviceMinFps, minByPolicy->getFps())) {
1207 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001208 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001209
ramindanid72ba162022-09-09 21:33:40 +00001210 const DisplayModePtr& maxByPolicy =
Ady Abrahamace3d052022-11-17 16:25:05 -08001211 getMaxRefreshRateByPolicyLocked(getActiveModeLocked().modePtr->getGroup());
Ana Krulecb9afd792020-06-11 13:16:15 -07001212 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001213 // Turn on the timer when the min of the primary range is below the device min.
1214 if (const Policy* currentPolicy = getCurrentPolicyLocked();
Ady Abraham285f8c12022-10-11 17:12:14 -07001215 isApproxLess(currentPolicy->primaryRanges.physical.min, deviceMinFps)) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001216 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001217 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001218 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001219 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001220
Ana Krulecb9afd792020-06-11 13:16:15 -07001221 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001222 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001223}
1224
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001225int RefreshRateSelector::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -07001226 // This calculation needs to be in sync with the java code
1227 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001228
1229 // The threshold must be smaller than 0.001 in order to differentiate
1230 // between the fractional pairs (e.g. 59.94 and 60).
1231 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001232 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -07001233 const auto numPeriodsRounded = std::round(numPeriods);
1234 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001235 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -07001236 }
1237
Ady Abraham62f216c2020-10-13 19:07:23 -07001238 return static_cast<int>(numPeriodsRounded);
1239}
1240
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001241bool RefreshRateSelector::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001242 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001243 return isFractionalPairOrMultiple(bigger, smaller);
1244 }
1245
1246 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
1247 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001248 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
1249 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001250}
1251
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001252void RefreshRateSelector::dump(utils::Dumper& dumper) const {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001253 using namespace std::string_view_literals;
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001254
Marin Shalamanovba421a82020-11-10 21:49:26 +01001255 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +01001256
Ady Abrahamace3d052022-11-17 16:25:05 -08001257 const auto activeMode = getActiveModeLocked();
1258 dumper.dump("activeMode"sv, to_string(activeMode));
Marin Shalamanovba421a82020-11-10 21:49:26 +01001259
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001260 dumper.dump("displayModes"sv);
1261 {
1262 utils::Dumper::Indent indent(dumper);
1263 for (const auto& [id, mode] : mDisplayModes) {
1264 dumper.dump({}, to_string(*mode));
1265 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001266 }
1267
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001268 dumper.dump("displayManagerPolicy"sv, mDisplayManagerPolicy.toString());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001269
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001270 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
1271 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001272 dumper.dump("overridePolicy"sv, currentPolicy.toString());
ramindani32cf0602022-03-02 02:30:29 +00001273 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001274
Ady Abraham8ca643a2022-10-18 18:26:47 -07001275 dumper.dump("frameRateOverrideConfig"sv, *ftl::enum_name(mFrameRateOverrideConfig));
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001276
Dominik Laskowski03cfce82022-11-02 12:13:29 -04001277 dumper.dump("idleTimer"sv);
1278 {
1279 utils::Dumper::Indent indent(dumper);
1280 dumper.dump("interval"sv, mIdleTimer.transform(&OneShotTimer::interval));
1281 dumper.dump("controller"sv,
1282 mConfig.kernelIdleTimerController
1283 .and_then(&ftl::enum_name<KernelIdleTimerController>)
1284 .value_or("Platform"sv));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001285 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001286}
1287
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001288std::chrono::milliseconds RefreshRateSelector::getIdleTimerTimeout() {
ramindani32cf0602022-03-02 02:30:29 +00001289 return mConfig.idleTimerTimeout;
1290}
1291
Ady Abraham2139f732019-11-13 18:56:40 -08001292} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001293
1294// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001295#pragma clang diagnostic pop // ignored "-Wextra"