blob: 04c2d4177f5119258662d96c201ce729d083d3cb [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/;
Ady Abraham08048ce2022-11-30 18:08:00 -0800110 // use signed type as `fps / range.max` might be 0
111 const auto start = std::max(1, static_cast<int>(fps / range.max) - 1);
Ady Abraham68636062022-11-16 17:07:25 -0800112 const auto end = fps /
113 std::max(range.min, RefreshRateSelector::kMinSupportedFrameRate,
114 fps_approx_ops::operator<);
115
116 return {start, end};
117}
118
Ady Abraham8ca643a2022-10-18 18:26:47 -0700119bool shouldEnableFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800120 for (const auto it1 : sortedModes) {
121 const auto& mode1 = it1->second;
122 for (const auto it2 : sortedModes) {
123 const auto& mode2 = it2->second;
124
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400125 if (RefreshRateSelector::getFrameRateDivisor(mode1->getFps(), mode2->getFps()) >= 2) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800126 return true;
127 }
128 }
129 }
130 return false;
131}
132
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400133std::string toString(const RefreshRateSelector::PolicyVariant& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700134 using namespace std::string_literals;
135
136 return ftl::match(
137 policy,
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400138 [](const RefreshRateSelector::DisplayManagerPolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700139 return "DisplayManagerPolicy"s + policy.toString();
140 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400141 [](const RefreshRateSelector::OverridePolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700142 return "OverridePolicy"s + policy.toString();
143 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400144 [](RefreshRateSelector::NoOverridePolicy) { return "NoOverridePolicy"s; });
Dominik Laskowski36dced82022-09-02 09:24:00 -0700145}
146
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800147} // namespace
148
Ady Abraham68636062022-11-16 17:07:25 -0800149auto RefreshRateSelector::createFrameRateModes(
150 std::function<bool(const DisplayMode&)>&& filterModes, const FpsRange& renderRange) const
151 -> std::vector<FrameRateMode> {
152 struct Key {
153 Fps fps;
154 int32_t group;
155 };
156
157 struct KeyLess {
158 bool operator()(const Key& a, const Key& b) const {
159 using namespace fps_approx_ops;
160 if (a.fps != b.fps) {
161 return a.fps < b.fps;
162 }
163
164 // For the same fps the order doesn't really matter, but we still
165 // want the behaviour of a strictly less operator.
166 // We use the group id as the secondary ordering for that.
167 return a.group < b.group;
168 }
169 };
170
171 std::map<Key, DisplayModeIterator, KeyLess> ratesMap;
172 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
173 const auto& [id, mode] = *it;
174
175 if (!filterModes(*mode)) {
176 continue;
177 }
178 const auto [start, end] =
179 divisorRange(mode->getFps(), renderRange, mConfig.enableFrameRateOverride);
180 for (auto divisor = start; divisor <= end; divisor++) {
181 const auto fps = mode->getFps() / divisor;
182 using fps_approx_ops::operator<;
Ady Abrahamdc0b3a72023-01-04 16:58:27 -0800183 if (divisor > 1 && fps < kMinSupportedFrameRate) {
Ady Abraham68636062022-11-16 17:07:25 -0800184 break;
185 }
186
187 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Enabled &&
188 !renderRange.includes(fps)) {
189 continue;
190 }
191
192 if (mConfig.enableFrameRateOverride ==
193 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
194 !isNativeRefreshRate(fps)) {
195 continue;
196 }
197
198 const auto [existingIter, emplaceHappened] =
199 ratesMap.try_emplace(Key{fps, mode->getGroup()}, it);
200 if (emplaceHappened) {
201 ALOGV("%s: including %s (%s)", __func__, to_string(fps).c_str(),
202 to_string(mode->getFps()).c_str());
203 } else {
204 // We might need to update the map as we found a lower refresh rate
205 if (isStrictlyLess(mode->getFps(), existingIter->second->second->getFps())) {
206 existingIter->second = it;
207 ALOGV("%s: changing %s (%s)", __func__, to_string(fps).c_str(),
208 to_string(mode->getFps()).c_str());
209 }
210 }
211 }
212 }
213
214 std::vector<FrameRateMode> frameRateModes;
215 frameRateModes.reserve(ratesMap.size());
216 for (const auto& [key, mode] : ratesMap) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800217 frameRateModes.emplace_back(FrameRateMode{key.fps, ftl::as_non_null(mode->second)});
Ady Abraham68636062022-11-16 17:07:25 -0800218 }
219
220 // We always want that the lowest frame rate will be corresponding to the
221 // lowest mode for power saving.
222 const auto lowestRefreshRateIt =
223 std::min_element(frameRateModes.begin(), frameRateModes.end(),
224 [](const FrameRateMode& lhs, const FrameRateMode& rhs) {
225 return isStrictlyLess(lhs.modePtr->getFps(),
226 rhs.modePtr->getFps());
227 });
228 frameRateModes.erase(frameRateModes.begin(), lowestRefreshRateIt);
229
230 return frameRateModes;
231}
232
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400233struct RefreshRateSelector::RefreshRateScoreComparator {
ramindanid72ba162022-09-09 21:33:40 +0000234 bool operator()(const RefreshRateScore& lhs, const RefreshRateScore& rhs) const {
Ady Abraham68636062022-11-16 17:07:25 -0800235 const auto& [frameRateMode, overallScore, _] = lhs;
ramindanid72ba162022-09-09 21:33:40 +0000236
Ady Abraham68636062022-11-16 17:07:25 -0800237 std::string name = to_string(frameRateMode);
238
ramindanid72ba162022-09-09 21:33:40 +0000239 ALOGV("%s sorting scores %.2f", name.c_str(), overallScore);
ramindanid72ba162022-09-09 21:33:40 +0000240 ATRACE_INT(name.c_str(), static_cast<int>(std::round(overallScore * 100)));
241
Ady Abraham68636062022-11-16 17:07:25 -0800242 if (!ScoredFrameRate::scoresEqual(overallScore, rhs.overallScore)) {
ramindanid72ba162022-09-09 21:33:40 +0000243 return overallScore > rhs.overallScore;
244 }
245
ramindanid72ba162022-09-09 21:33:40 +0000246 if (refreshRateOrder == RefreshRateOrder::Descending) {
247 using fps_approx_ops::operator>;
Ady Abraham68636062022-11-16 17:07:25 -0800248 return frameRateMode.fps > rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000249 } else {
250 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -0800251 return frameRateMode.fps < rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000252 }
253 }
254
255 const RefreshRateOrder refreshRateOrder;
256};
257
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400258std::string RefreshRateSelector::Policy::toString() const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700259 return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
Ady Abraham285f8c12022-10-11 17:12:14 -0700260 ", primaryRanges=%s, appRequestRanges=%s}",
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700261 defaultMode.value(), allowGroupSwitching ? "true" : "false",
Ady Abraham285f8c12022-10-11 17:12:14 -0700262 to_string(primaryRanges).c_str(),
263 to_string(appRequestRanges).c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200264}
265
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400266std::pair<nsecs_t, nsecs_t> RefreshRateSelector::getDisplayFrames(nsecs_t layerPeriod,
267 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800268 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
269 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
270 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
271 quotient++;
272 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800273 }
274
Ady Abraham62a0be22020-12-08 16:54:10 -0800275 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800276}
277
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400278float RefreshRateSelector::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
279 Fps refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200280 constexpr float kScoreForFractionalPairs = .8f;
281
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800282 const auto displayPeriod = refreshRate.getPeriodNsecs();
Ady Abraham62a0be22020-12-08 16:54:10 -0800283 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
284 if (layer.vote == LayerVoteType::ExplicitDefault) {
285 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200286 // that layerPeriod is the minimal period to render a frame.
287 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
288 // then the actualLayerPeriod will be 32ms, because it is the
289 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800290 auto actualLayerPeriod = displayPeriod;
291 int multiplier = 1;
292 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
293 multiplier++;
294 actualLayerPeriod = displayPeriod * multiplier;
295 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200296
297 // Because of the threshold we used above it's possible that score is slightly
298 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800299 return std::min(1.0f,
300 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
301 }
302
303 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
304 layer.vote == LayerVoteType::Heuristic) {
Ady Abraham68636062022-11-16 17:07:25 -0800305 const float multiplier = refreshRate.getValue() / layer.desiredRefreshRate.getValue();
306
307 // We only want to score this layer as a fractional pair if the content is not
308 // significantly faster than the display rate, at it would cause a significant frame drop.
309 // It is more appropriate to choose a higher display rate even if
310 // a pull-down will be required.
311 constexpr float kMinMultiplier = 0.25f;
312 if (multiplier >= kMinMultiplier &&
313 isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700314 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200315 }
316
Ady Abraham62a0be22020-12-08 16:54:10 -0800317 // Calculate how many display vsyncs we need to present a single frame for this
318 // layer
319 const auto [displayFramesQuotient, displayFramesRemainder] =
320 getDisplayFrames(layerPeriod, displayPeriod);
321 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
322 if (displayFramesRemainder == 0) {
323 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700324 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800325 }
326
327 if (displayFramesQuotient == 0) {
328 // Layer desired refresh rate is higher than the display rate.
329 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
330 (1.0f / (MAX_FRAMES_TO_FIT + 1));
331 }
332
333 // Layer desired refresh rate is lower than the display rate. Check how well it fits
334 // the cadence.
335 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
336 int iter = 2;
337 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
338 diff = diff - (displayPeriod - diff);
339 iter++;
340 }
341
Ady Abraham05243be2021-09-16 15:58:52 -0700342 return (1.0f / iter);
343 }
344
345 return 0;
346}
347
Ady Abraham68636062022-11-16 17:07:25 -0800348float RefreshRateSelector::calculateDistanceScoreFromMax(Fps refreshRate) const {
349 const auto& maxFps = mAppRequestFrameRates.back().fps;
350 const float ratio = refreshRate.getValue() / maxFps.getValue();
ramindanid72ba162022-09-09 21:33:40 +0000351 // Use ratio^2 to get a lower score the more we get further from peak
352 return ratio * ratio;
353}
354
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400355float RefreshRateSelector::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
356 bool isSeamlessSwitch) const {
Ady Abraham73c3df52023-01-12 18:09:31 -0800357 ATRACE_CALL();
Ady Abraham05243be2021-09-16 15:58:52 -0700358 // Slightly prefer seamless switches.
359 constexpr float kSeamedSwitchPenalty = 0.95f;
360 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
361
362 // If the layer wants Max, give higher score to the higher refresh rate
363 if (layer.vote == LayerVoteType::Max) {
Ady Abraham68636062022-11-16 17:07:25 -0800364 return calculateDistanceScoreFromMax(refreshRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800365 }
366
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800367 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800368 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Ady Abraham68636062022-11-16 17:07:25 -0800369 if (supportsAppFrameRateOverrideByContent()) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800370 // Since we support frame rate override, allow refresh rates which are
371 // multiples of the layer's request, as those apps would be throttled
372 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800373 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800374 }
375
Ady Abrahamcc315492022-02-17 17:06:39 -0800376 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800377 }
378
Ady Abrahamcc315492022-02-17 17:06:39 -0800379 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700380 // the highest score.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800381 if (getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700382 return 1.0f * seamlessness;
383 }
384
Ady Abrahamcc315492022-02-17 17:06:39 -0800385 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700386 // there is a small penalty attached to the score to favor the frame rates
387 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800388 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700389 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
390 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800391}
392
Ady Abraham68636062022-11-16 17:07:25 -0800393auto RefreshRateSelector::getRankedFrameRates(const std::vector<LayerRequirement>& layers,
394 GlobalSignals signals) const -> RankedFrameRates {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200395 std::lock_guard lock(mLock);
396
Ady Abraham68636062022-11-16 17:07:25 -0800397 if (mGetRankedFrameRatesCache &&
398 mGetRankedFrameRatesCache->arguments == std::make_pair(layers, signals)) {
399 return mGetRankedFrameRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200400 }
401
Ady Abraham68636062022-11-16 17:07:25 -0800402 const auto result = getRankedFrameRatesLocked(layers, signals);
403 mGetRankedFrameRatesCache = GetRankedFrameRatesCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200404 return result;
405}
406
Ady Abraham68636062022-11-16 17:07:25 -0800407auto RefreshRateSelector::getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
408 GlobalSignals signals) const
409 -> RankedFrameRates {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000410 using namespace fps_approx_ops;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800411 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800412 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700413
Ady Abrahamace3d052022-11-17 16:25:05 -0800414 const auto& activeMode = *getActiveModeLocked().modePtr;
ramindani38c84982022-08-29 18:02:57 +0000415
Ady Abraham68636062022-11-16 17:07:25 -0800416 // Keep the display at max frame rate for the duration of powering on the display.
ramindani38c84982022-08-29 18:02:57 +0000417 if (signals.powerOnImminent) {
418 ALOGV("Power On Imminent");
Ady Abraham68636062022-11-16 17:07:25 -0800419 return {rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Descending),
ramindanid72ba162022-09-09 21:33:40 +0000420 GlobalSignals{.powerOnImminent = true}};
ramindani38c84982022-08-29 18:02:57 +0000421 }
422
Ady Abraham8a82ba62020-01-17 12:43:17 -0800423 int noVoteLayers = 0;
424 int minVoteLayers = 0;
425 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800426 int explicitDefaultVoteLayers = 0;
427 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800428 int explicitExact = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100429 int seamedFocusedLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800430
Ady Abraham8a82ba62020-01-17 12:43:17 -0800431 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800432 switch (layer.vote) {
433 case LayerVoteType::NoVote:
434 noVoteLayers++;
435 break;
436 case LayerVoteType::Min:
437 minVoteLayers++;
438 break;
439 case LayerVoteType::Max:
440 maxVoteLayers++;
441 break;
442 case LayerVoteType::ExplicitDefault:
443 explicitDefaultVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800444 break;
445 case LayerVoteType::ExplicitExactOrMultiple:
446 explicitExactOrMultipleVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800447 break;
448 case LayerVoteType::ExplicitExact:
449 explicitExact++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800450 break;
451 case LayerVoteType::Heuristic:
452 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800453 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200454
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100455 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
456 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200457 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800458 }
459
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800460 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
461 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700462
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200463 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800464 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700465
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200466 // If the default mode group is different from the group of current mode,
467 // this means a layer requesting a seamed mode switch just disappeared and
468 // we should switch back to the default group.
469 // However if a seamed layer is still present we anchor around the group
470 // of the current mode, in order to prevent unnecessary seamed mode switches
471 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800472 const auto anchorGroup =
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700473 seamedFocusedLayers > 0 ? activeMode.getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200474
Steven Thomasf734df42020-04-13 21:09:28 -0700475 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
476 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800477 if (signals.touch && !hasExplicitVoteLayers) {
ramindanid72ba162022-09-09 21:33:40 +0000478 ALOGV("Touch Boost");
Ady Abraham68636062022-11-16 17:07:25 -0800479 return {rankFrameRates(anchorGroup, RefreshRateOrder::Descending),
ramindanid72ba162022-09-09 21:33:40 +0000480 GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800481 }
482
Alec Mouri11232a22020-05-14 18:06:25 -0700483 // If the primary range consists of a single refresh rate then we can only
484 // move out the of range if layers explicitly request a different refresh
485 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100486 const bool primaryRangeIsSingleRate =
Ady Abraham285f8c12022-10-11 17:12:14 -0700487 isApproxEqual(policy->primaryRanges.physical.min, policy->primaryRanges.physical.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700488
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800489 if (!signals.touch && signals.idle && !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
ramindanid72ba162022-09-09 21:33:40 +0000490 ALOGV("Idle");
Ady Abraham68636062022-11-16 17:07:25 -0800491 return {rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending),
ramindanid72ba162022-09-09 21:33:40 +0000492 GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700493 }
494
Steven Thomasdebafed2020-05-18 17:30:35 -0700495 if (layers.empty() || noVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000496 ALOGV("No layers with votes");
Ady Abraham68636062022-11-16 17:07:25 -0800497 return {rankFrameRates(anchorGroup, RefreshRateOrder::Descending), kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700498 }
499
Ady Abraham8a82ba62020-01-17 12:43:17 -0800500 // Only if all layers want Min we should return Min
501 if (noVoteLayers + minVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000502 ALOGV("All layers Min");
Ady Abraham68636062022-11-16 17:07:25 -0800503 return {rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending), kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800504 }
505
Ady Abraham8a82ba62020-01-17 12:43:17 -0800506 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800507 std::vector<RefreshRateScore> scores;
Ady Abraham68636062022-11-16 17:07:25 -0800508 scores.reserve(mAppRequestFrameRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800509
Ady Abraham68636062022-11-16 17:07:25 -0800510 for (const FrameRateMode& it : mAppRequestFrameRates) {
511 scores.emplace_back(RefreshRateScore{it, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800512 }
513
514 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700515 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700516 ftl::enum_string(layer.vote).c_str(), layer.weight,
rnlee3bd610662021-06-23 16:27:57 -0700517 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800518 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800519 continue;
520 }
521
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800522 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800523
Ady Abraham68636062022-11-16 17:07:25 -0800524 for (auto& [mode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
525 const auto& [fps, modePtr] = mode;
526 const bool isSeamlessSwitch = modePtr->getGroup() == activeMode.getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200527
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100528 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100529 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800530 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700531 to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200532 continue;
533 }
534
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100535 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
536 !layer.focused) {
537 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100538 " Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800539 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700540 to_string(activeMode).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100541 continue;
542 }
543
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100544 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100545 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100546 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100547 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
548 // disappeared.
Ady Abraham68636062022-11-16 17:07:25 -0800549 const bool isInPolicyForDefault = modePtr->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100550 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100551 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham68636062022-11-16 17:07:25 -0800552 to_string(*modePtr).c_str(), to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200553 continue;
554 }
555
Ady Abraham68636062022-11-16 17:07:25 -0800556 const bool inPrimaryRange = policy->primaryRanges.physical.includes(modePtr->getFps());
Alec Mouri11232a22020-05-14 18:06:25 -0700557 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800558 !(layer.focused &&
559 (layer.vote == LayerVoteType::ExplicitDefault ||
560 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700561 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700562 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700563 continue;
564 }
565
Ady Abraham68636062022-11-16 17:07:25 -0800566 const float layerScore = calculateLayerScoreLocked(layer, fps, isSeamlessSwitch);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000567 const float weightedLayerScore = weight * layerScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800568
Ady Abraham13cfb362022-08-13 05:12:13 +0000569 // Layer with fixed source has a special consideration which depends on the
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000570 // mConfig.frameRateMultipleThreshold. We don't want these layers to score
571 // refresh rates above the threshold, but we also don't want to favor the lower
572 // ones by having a greater number of layers scoring them. Instead, we calculate
573 // the score independently for these layers and later decide which
574 // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
575 // score 120 Hz, but desired 60 fps should contribute to the score.
576 const bool fixedSourceLayer = [](LayerVoteType vote) {
577 switch (vote) {
578 case LayerVoteType::ExplicitExactOrMultiple:
579 case LayerVoteType::Heuristic:
580 return true;
581 case LayerVoteType::NoVote:
582 case LayerVoteType::Min:
583 case LayerVoteType::Max:
584 case LayerVoteType::ExplicitDefault:
585 case LayerVoteType::ExplicitExact:
586 return false;
587 }
588 }(layer.vote);
Ady Abraham62f51d92022-08-24 22:20:22 +0000589 const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000590 layer.desiredRefreshRate <
591 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
Ady Abraham62f51d92022-08-24 22:20:22 +0000592 if (fixedSourceLayer && layerBelowThreshold) {
Ady Abraham13cfb362022-08-13 05:12:13 +0000593 const bool modeAboveThreshold =
Ady Abraham68636062022-11-16 17:07:25 -0800594 modePtr->getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
Ady Abraham62f51d92022-08-24 22:20:22 +0000595 if (modeAboveThreshold) {
Ady Abraham68636062022-11-16 17:07:25 -0800596 ALOGV("%s gives %s (%s) fixed source (above threshold) score of %.4f",
597 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
598 to_string(modePtr->getFps()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000599 fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000600 } else {
Ady Abraham68636062022-11-16 17:07:25 -0800601 ALOGV("%s gives %s (%s) fixed source (below threshold) score of %.4f",
602 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
603 to_string(modePtr->getFps()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000604 fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000605 }
606 } else {
Ady Abraham68636062022-11-16 17:07:25 -0800607 ALOGV("%s gives %s (%s) score of %.4f", formatLayerInfo(layer, weight).c_str(),
608 to_string(fps).c_str(), to_string(modePtr->getFps()).c_str(), layerScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000609 overallScore += weightedLayerScore;
610 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800611 }
612 }
613
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000614 // We want to find the best refresh rate without the fixed source layers,
Ady Abraham62f51d92022-08-24 22:20:22 +0000615 // so we could know whether we should add the modeAboveThreshold scores or not.
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000616 // If the best refresh rate is already above the threshold, it means that
617 // some non-fixed source layers already scored it, so we can just add the score
618 // for all fixed source layers, even the ones that are above the threshold.
619 const bool maxScoreAboveThreshold = [&] {
620 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
621 return false;
622 }
623
624 const auto maxScoreIt =
625 std::max_element(scores.begin(), scores.end(),
626 [](RefreshRateScore max, RefreshRateScore current) {
Ady Abraham68636062022-11-16 17:07:25 -0800627 return current.overallScore > max.overallScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000628 });
Ady Abraham68636062022-11-16 17:07:25 -0800629 ALOGV("%s (%s) is the best refresh rate without fixed source layers. It is %s the "
630 "threshold for "
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000631 "refresh rate multiples",
Ady Abraham68636062022-11-16 17:07:25 -0800632 to_string(maxScoreIt->frameRateMode.fps).c_str(),
633 to_string(maxScoreIt->frameRateMode.modePtr->getFps()).c_str(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000634 maxScoreAboveThreshold ? "above" : "below");
Ady Abraham68636062022-11-16 17:07:25 -0800635 return maxScoreIt->frameRateMode.modePtr->getFps() >=
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000636 Fps::fromValue(mConfig.frameRateMultipleThreshold);
637 }();
638
639 // Now we can add the fixed rate layers score
Ady Abraham68636062022-11-16 17:07:25 -0800640 for (auto& [frameRateMode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000641 overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000642 if (maxScoreAboveThreshold) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000643 overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000644 }
Ady Abraham68636062022-11-16 17:07:25 -0800645 ALOGV("%s (%s) adjusted overallScore is %.4f", to_string(frameRateMode.fps).c_str(),
646 to_string(frameRateMode.modePtr->getFps()).c_str(), overallScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000647 }
648
649 // Now that we scored all the refresh rates we need to pick the one that got the highest
ramindanid72ba162022-09-09 21:33:40 +0000650 // overallScore. Sort the scores based on their overallScore in descending order of priority.
651 const RefreshRateOrder refreshRateOrder =
652 maxVoteLayers > 0 ? RefreshRateOrder::Descending : RefreshRateOrder::Ascending;
653 std::sort(scores.begin(), scores.end(),
654 RefreshRateScoreComparator{.refreshRateOrder = refreshRateOrder});
ramindanid72ba162022-09-09 21:33:40 +0000655
Ady Abraham68636062022-11-16 17:07:25 -0800656 FrameRateRanking ranking;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400657 ranking.reserve(scores.size());
658
659 std::transform(scores.begin(), scores.end(), back_inserter(ranking),
ramindanid72ba162022-09-09 21:33:40 +0000660 [](const RefreshRateScore& score) {
Ady Abraham68636062022-11-16 17:07:25 -0800661 return ScoredFrameRate{score.frameRateMode, score.overallScore};
ramindanid72ba162022-09-09 21:33:40 +0000662 });
Ady Abraham34702102020-02-10 14:12:05 -0800663
Ady Abraham37d46922022-10-05 13:08:51 -0700664 const bool noLayerScore = std::all_of(scores.begin(), scores.end(), [](RefreshRateScore score) {
665 return score.overallScore == 0;
666 });
667
Alec Mouri11232a22020-05-14 18:06:25 -0700668 if (primaryRangeIsSingleRate) {
669 // If we never scored any layers, then choose the rate from the primary
670 // range instead of picking a random score from the app range.
Ady Abraham37d46922022-10-05 13:08:51 -0700671 if (noLayerScore) {
ramindanid72ba162022-09-09 21:33:40 +0000672 ALOGV("Layers not scored");
Ady Abraham68636062022-11-16 17:07:25 -0800673 return {rankFrameRates(anchorGroup, RefreshRateOrder::Descending), kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700674 } else {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400675 return {ranking, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700676 }
677 }
678
Steven Thomasf734df42020-04-13 21:09:28 -0700679 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
680 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
681 // vote we should not change it if we get a touch event. Only apply touch boost if it will
682 // actually increase the refresh rate over the normal selection.
Ady Abraham5e4e9832021-06-14 13:40:56 -0700683 const bool touchBoostForExplicitExact = [&] {
Ady Abraham68636062022-11-16 17:07:25 -0800684 if (supportsAppFrameRateOverrideByContent()) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700685 // Enable touch boost if there are other layers besides exact
686 return explicitExact + noVoteLayers != layers.size();
687 } else {
688 // Enable touch boost if there are no exact layers
689 return explicitExact == 0;
690 }
691 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700692
Ady Abraham68636062022-11-16 17:07:25 -0800693 const auto touchRefreshRates = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700694 using fps_approx_ops::operator<;
695
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800696 if (signals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Ady Abraham68636062022-11-16 17:07:25 -0800697 scores.front().frameRateMode.fps < touchRefreshRates.front().frameRateMode.fps) {
ramindanid72ba162022-09-09 21:33:40 +0000698 ALOGV("Touch Boost");
699 return {touchRefreshRates, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700700 }
701
Ady Abraham37d46922022-10-05 13:08:51 -0700702 // If we never scored any layers, and we don't favor high refresh rates, prefer to stay with the
703 // current config
704 if (noLayerScore && refreshRateOrder == RefreshRateOrder::Ascending) {
705 const auto preferredDisplayMode = activeMode.getId();
Ady Abraham68636062022-11-16 17:07:25 -0800706 return {rankFrameRates(anchorGroup, RefreshRateOrder::Ascending, preferredDisplayMode),
Ady Abraham37d46922022-10-05 13:08:51 -0700707 kNoSignals};
708 }
709
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400710 return {ranking, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800711}
712
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400713using LayerRequirementPtrs = std::vector<const RefreshRateSelector::LayerRequirement*>;
714using PerUidLayerRequirements = std::unordered_map<uid_t, LayerRequirementPtrs>;
715
716PerUidLayerRequirements groupLayersByUid(
717 const std::vector<RefreshRateSelector::LayerRequirement>& layers) {
718 PerUidLayerRequirements layersByUid;
Ady Abraham62a0be22020-12-08 16:54:10 -0800719 for (const auto& layer : layers) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400720 const auto it = layersByUid.emplace(layer.ownerUid, LayerRequirementPtrs()).first;
721 auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800722 layersWithSameUid.push_back(&layer);
723 }
724
725 // Remove uids that can't have a frame rate override
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400726 for (auto it = layersByUid.begin(); it != layersByUid.end();) {
727 const auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800728 bool skipUid = false;
729 for (const auto& layer : layersWithSameUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400730 using LayerVoteType = RefreshRateSelector::LayerVoteType;
731
732 if (layer->vote == LayerVoteType::Max || layer->vote == LayerVoteType::Heuristic) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800733 skipUid = true;
734 break;
735 }
736 }
737 if (skipUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400738 it = layersByUid.erase(it);
Ady Abraham62a0be22020-12-08 16:54:10 -0800739 } else {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400740 ++it;
Ady Abraham62a0be22020-12-08 16:54:10 -0800741 }
742 }
743
744 return layersByUid;
745}
746
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400747auto RefreshRateSelector::getFrameRateOverrides(const std::vector<LayerRequirement>& layers,
748 Fps displayRefreshRate,
749 GlobalSignals globalSignals) const
750 -> UidToFrameRateOverride {
Ady Abraham62a0be22020-12-08 16:54:10 -0800751 ATRACE_CALL();
Ady Abraham68636062022-11-16 17:07:25 -0800752 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Disabled) {
753 return {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800754 }
755
Ady Abraham68636062022-11-16 17:07:25 -0800756 ALOGV("%s: %zu layers", __func__, layers.size());
757 std::lock_guard lock(mLock);
758
Ady Abraham8ca643a2022-10-18 18:26:47 -0700759 const auto* policyPtr = getCurrentPolicyLocked();
760 // We don't want to run lower than 30fps
761 const Fps minFrameRate = std::max(policyPtr->appRequestRanges.render.min, 30_Hz, isApproxLess);
762
763 using fps_approx_ops::operator/;
764 const unsigned numMultiples = displayRefreshRate / minFrameRate;
765
766 std::vector<std::pair<Fps, float>> scoredFrameRates;
767 scoredFrameRates.reserve(numMultiples);
768
769 for (unsigned n = numMultiples; n > 0; n--) {
770 const Fps divisor = displayRefreshRate / n;
771 if (mConfig.enableFrameRateOverride ==
Ady Abraham68636062022-11-16 17:07:25 -0800772 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
773 !isNativeRefreshRate(divisor)) {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700774 continue;
775 }
776
777 if (policyPtr->appRequestRanges.render.includes(divisor)) {
778 ALOGV("%s: adding %s as a potential frame rate", __func__, to_string(divisor).c_str());
779 scoredFrameRates.emplace_back(divisor, 0);
780 }
781 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800782
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400783 const auto layersByUid = groupLayersByUid(layers);
Ady Abraham62a0be22020-12-08 16:54:10 -0800784 UidToFrameRateOverride frameRateOverrides;
785 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800786 // Layers with ExplicitExactOrMultiple expect touch boost
787 const bool hasExplicitExactOrMultiple =
788 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
789 [](const auto& layer) {
790 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
791 });
792
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700793 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800794 continue;
795 }
796
Ady Abraham8ca643a2022-10-18 18:26:47 -0700797 for (auto& [_, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800798 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -0800799 }
800
801 for (const auto& layer : layersWithSameUid) {
802 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
803 continue;
804 }
805
806 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800807 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
808 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700809 for (auto& [fps, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800810 constexpr bool isSeamlessSwitch = true;
Ady Abraham8ca643a2022-10-18 18:26:47 -0700811 const auto layerScore = calculateLayerScoreLocked(*layer, fps, isSeamlessSwitch);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800812 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -0800813 }
814 }
815
Ady Abraham62a0be22020-12-08 16:54:10 -0800816 // If we never scored any layers, we don't have a preferred frame rate
Ady Abraham8ca643a2022-10-18 18:26:47 -0700817 if (std::all_of(scoredFrameRates.begin(), scoredFrameRates.end(),
818 [](const auto& scoredFrameRate) {
819 const auto [_, score] = scoredFrameRate;
820 return score == 0;
821 })) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800822 continue;
823 }
824
ramindanid72ba162022-09-09 21:33:40 +0000825 // Now that we scored all the refresh rates we need to pick the lowest refresh rate
826 // that got the highest score.
Ady Abraham8ca643a2022-10-18 18:26:47 -0700827 const auto [overrideFps, _] =
828 *std::max_element(scoredFrameRates.begin(), scoredFrameRates.end(),
829 [](const auto& lhsPair, const auto& rhsPair) {
830 const float lhs = lhsPair.second;
831 const float rhs = rhsPair.second;
Ady Abraham68636062022-11-16 17:07:25 -0800832 return lhs < rhs && !ScoredFrameRate::scoresEqual(lhs, rhs);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700833 });
834 ALOGV("%s: overriding to %s for uid=%d", __func__, to_string(overrideFps).c_str(), uid);
835 frameRateOverrides.emplace(uid, overrideFps);
Ady Abraham62a0be22020-12-08 16:54:10 -0800836 }
837
838 return frameRateOverrides;
839}
840
Ady Abraham0aa373a2022-11-22 13:56:50 -0800841ftl::Optional<FrameRateMode> RefreshRateSelector::onKernelTimerChanged(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800842 std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800843 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100844
Ady Abraham0aa373a2022-11-22 13:56:50 -0800845 const auto current = [&]() REQUIRES(mLock) -> FrameRateMode {
846 if (desiredActiveModeId) {
847 const auto& modePtr = mDisplayModes.get(*desiredActiveModeId)->get();
848 return FrameRateMode{modePtr->getFps(), ftl::as_non_null(modePtr)};
849 }
850
851 return getActiveModeLocked();
852 }();
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100853
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800854 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
Ady Abraham0aa373a2022-11-22 13:56:50 -0800855 if (current.modePtr->getId() == min->getId()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800856 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100857 }
858
Ady Abraham0aa373a2022-11-22 13:56:50 -0800859 return timerExpired ? FrameRateMode{min->getFps(), ftl::as_non_null(min)} : current;
Steven Thomasf734df42020-04-13 21:09:28 -0700860}
861
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400862const DisplayModePtr& RefreshRateSelector::getMinRefreshRateByPolicyLocked() const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800863 const auto& activeMode = *getActiveModeLocked().modePtr;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700864
Ady Abraham68636062022-11-16 17:07:25 -0800865 for (const FrameRateMode& mode : mPrimaryFrameRates) {
866 if (activeMode.getGroup() == mode.modePtr->getGroup()) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800867 return mode.modePtr.get();
Marin Shalamanov46084422020-10-13 12:33:42 +0200868 }
869 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800870
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700871 ALOGE("Can't find min refresh rate by policy with the same mode group as the current mode %s",
872 to_string(activeMode).c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800873
874 // Default to the lowest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -0800875 return mPrimaryFrameRates.front().modePtr.get();
Ady Abraham2139f732019-11-13 18:56:40 -0800876}
877
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400878const DisplayModePtr& RefreshRateSelector::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800879 const ftl::NonNull<DisplayModePtr>* maxByAnchor = &mPrimaryFrameRates.back().modePtr;
880 const ftl::NonNull<DisplayModePtr>* max = &mPrimaryFrameRates.back().modePtr;
Ady Abraham68636062022-11-16 17:07:25 -0800881
882 bool maxByAnchorFound = false;
883 for (auto it = mPrimaryFrameRates.rbegin(); it != mPrimaryFrameRates.rend(); ++it) {
884 using namespace fps_approx_ops;
885 if (it->modePtr->getFps() > (*max)->getFps()) {
886 max = &it->modePtr;
Marin Shalamanov46084422020-10-13 12:33:42 +0200887 }
Ady Abraham68636062022-11-16 17:07:25 -0800888
889 if (anchorGroup == it->modePtr->getGroup() &&
890 it->modePtr->getFps() >= (*maxByAnchor)->getFps()) {
891 maxByAnchorFound = true;
892 maxByAnchor = &it->modePtr;
893 }
894 }
895
896 if (maxByAnchorFound) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800897 return maxByAnchor->get();
Marin Shalamanov46084422020-10-13 12:33:42 +0200898 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800899
ramindanid72ba162022-09-09 21:33:40 +0000900 ALOGE("Can't find max refresh rate by policy with the same group %d", anchorGroup);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800901
902 // Default to the highest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -0800903 return max->get();
Ady Abraham2139f732019-11-13 18:56:40 -0800904}
905
Ady Abraham68636062022-11-16 17:07:25 -0800906auto RefreshRateSelector::rankFrameRates(std::optional<int> anchorGroupOpt,
907 RefreshRateOrder refreshRateOrder,
908 std::optional<DisplayModeId> preferredDisplayModeOpt) const
909 -> FrameRateRanking {
910 const char* const whence = __func__;
911 std::deque<ScoredFrameRate> ranking;
912 const auto rankFrameRate = [&](const FrameRateMode& frameRateMode) REQUIRES(mLock) {
913 const auto& modePtr = frameRateMode.modePtr;
914 if (anchorGroupOpt && modePtr->getGroup() != anchorGroupOpt) {
Ady Abraham37d46922022-10-05 13:08:51 -0700915 return;
ramindanid72ba162022-09-09 21:33:40 +0000916 }
Ady Abraham37d46922022-10-05 13:08:51 -0700917
Ady Abraham68636062022-11-16 17:07:25 -0800918 float score = calculateDistanceScoreFromMax(frameRateMode.fps);
Ady Abraham37d46922022-10-05 13:08:51 -0700919 const bool inverseScore = (refreshRateOrder == RefreshRateOrder::Ascending);
920 if (inverseScore) {
921 score = 1.0f / score;
922 }
923 if (preferredDisplayModeOpt) {
Ady Abraham68636062022-11-16 17:07:25 -0800924 if (*preferredDisplayModeOpt == modePtr->getId()) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400925 constexpr float kScore = std::numeric_limits<float>::max();
Ady Abraham68636062022-11-16 17:07:25 -0800926 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
Ady Abraham37d46922022-10-05 13:08:51 -0700927 return;
928 }
929 constexpr float kNonPreferredModePenalty = 0.95f;
930 score *= kNonPreferredModePenalty;
931 }
Ady Abraham68636062022-11-16 17:07:25 -0800932 ALOGV("%s(%s) %s (%s) scored %.2f", whence, ftl::enum_string(refreshRateOrder).c_str(),
933 to_string(frameRateMode.fps).c_str(), to_string(modePtr->getFps()).c_str(), score);
934 ranking.emplace_back(ScoredFrameRate{frameRateMode, score});
ramindanid72ba162022-09-09 21:33:40 +0000935 };
936
937 if (refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abraham68636062022-11-16 17:07:25 -0800938 std::for_each(mPrimaryFrameRates.begin(), mPrimaryFrameRates.end(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +0000939 } else {
Ady Abraham68636062022-11-16 17:07:25 -0800940 std::for_each(mPrimaryFrameRates.rbegin(), mPrimaryFrameRates.rend(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +0000941 }
942
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400943 if (!ranking.empty() || !anchorGroupOpt) {
944 return {ranking.begin(), ranking.end()};
ramindanid72ba162022-09-09 21:33:40 +0000945 }
946
947 ALOGW("Can't find %s refresh rate by policy with the same mode group"
948 " as the mode group %d",
949 refreshRateOrder == RefreshRateOrder::Ascending ? "min" : "max", anchorGroupOpt.value());
950
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400951 constexpr std::optional<int> kNoAnchorGroup = std::nullopt;
Ady Abraham68636062022-11-16 17:07:25 -0800952 return rankFrameRates(kNoAnchorGroup, refreshRateOrder, preferredDisplayModeOpt);
ramindanid72ba162022-09-09 21:33:40 +0000953}
954
Ady Abrahamace3d052022-11-17 16:25:05 -0800955FrameRateMode RefreshRateSelector::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800956 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -0800957 return getActiveModeLocked();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700958}
959
Ady Abrahamace3d052022-11-17 16:25:05 -0800960const FrameRateMode& RefreshRateSelector::getActiveModeLocked() const {
961 return *mActiveModeOpt;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700962}
963
Ady Abrahamace3d052022-11-17 16:25:05 -0800964void RefreshRateSelector::setActiveMode(DisplayModeId modeId, Fps renderFrameRate) {
Ady Abraham2139f732019-11-13 18:56:40 -0800965 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200966
Ady Abraham68636062022-11-16 17:07:25 -0800967 // Invalidate the cached invocation to getRankedFrameRates. This forces
968 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
969 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200970
Ady Abrahamace3d052022-11-17 16:25:05 -0800971 const auto activeModeOpt = mDisplayModes.get(modeId);
972 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
973
974 mActiveModeOpt.emplace(FrameRateMode{renderFrameRate, ftl::as_non_null(activeModeOpt->get())});
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800975}
976
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400977RefreshRateSelector::RefreshRateSelector(DisplayModes modes, DisplayModeId activeModeId,
978 Config config)
rnlee3bd610662021-06-23 16:27:57 -0700979 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700980 initializeIdleTimer();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700981 FTL_FAKE_GUARD(kMainThreadContext, updateDisplayModes(std::move(modes), activeModeId));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100982}
983
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400984void RefreshRateSelector::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +0000985 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700986 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +0000987 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800988 [this] {
989 std::scoped_lock lock(mIdleTimerCallbacksMutex);
990 if (const auto callbacks = getIdleTimerCallbacks()) {
991 callbacks->onReset();
992 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700993 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800994 [this] {
995 std::scoped_lock lock(mIdleTimerCallbacksMutex);
996 if (const auto callbacks = getIdleTimerCallbacks()) {
997 callbacks->onExpired();
998 }
Ady Abraham9a2ea342021-09-03 17:32:34 -0700999 });
Ady Abraham9a2ea342021-09-03 17:32:34 -07001000 }
1001}
1002
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001003void RefreshRateSelector::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001004 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001005
Ady Abraham68636062022-11-16 17:07:25 -08001006 // Invalidate the cached invocation to getRankedFrameRates. This forces
1007 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1008 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001009
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001010 mDisplayModes = std::move(modes);
Ady Abrahamace3d052022-11-17 16:25:05 -08001011 const auto activeModeOpt = mDisplayModes.get(activeModeId);
1012 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1013 mActiveModeOpt =
1014 FrameRateMode{activeModeOpt->get()->getFps(), ftl::as_non_null(activeModeOpt->get())};
Ady Abrahamabc27602020-04-08 17:20:29 -07001015
Ady Abraham68636062022-11-16 17:07:25 -08001016 const auto sortedModes = sortByRefreshRate(mDisplayModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001017 mMinRefreshRateModeIt = sortedModes.front();
1018 mMaxRefreshRateModeIt = sortedModes.back();
1019
Marin Shalamanov75f37252021-02-10 21:43:57 +01001020 // Reset the policy because the old one may no longer be valid.
1021 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001022 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -08001023
Ady Abraham8ca643a2022-10-18 18:26:47 -07001024 mFrameRateOverrideConfig = [&] {
1025 switch (mConfig.enableFrameRateOverride) {
1026 case Config::FrameRateOverride::Disabled:
Ady Abraham68636062022-11-16 17:07:25 -08001027 case Config::FrameRateOverride::AppOverride:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001028 case Config::FrameRateOverride::Enabled:
1029 return mConfig.enableFrameRateOverride;
Ady Abraham68636062022-11-16 17:07:25 -08001030 case Config::FrameRateOverride::AppOverrideNativeRefreshRates:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001031 return shouldEnableFrameRateOverride(sortedModes)
Ady Abraham68636062022-11-16 17:07:25 -08001032 ? Config::FrameRateOverride::AppOverrideNativeRefreshRates
Ady Abraham8ca643a2022-10-18 18:26:47 -07001033 : Config::FrameRateOverride::Disabled;
1034 }
1035 }();
Ady Abraham4899ff82021-01-06 13:53:29 -08001036
Ady Abraham68636062022-11-16 17:07:25 -08001037 if (mConfig.enableFrameRateOverride ==
1038 Config::FrameRateOverride::AppOverrideNativeRefreshRates) {
1039 for (const auto& [_, mode] : mDisplayModes) {
1040 mAppOverrideNativeRefreshRates.try_emplace(mode->getFps(), ftl::unit);
1041 }
1042 }
1043
Ady Abrahamabc27602020-04-08 17:20:29 -07001044 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001045}
1046
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001047bool RefreshRateSelector::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001048 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001049 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
Ady Abraham285f8c12022-10-11 17:12:14 -07001050 if (!policy.primaryRanges.physical.includes(mode->get()->getFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001051 ALOGE("Default mode is not in the primary range.");
1052 return false;
1053 }
1054 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001055 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -07001056 return false;
1057 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001058
Ady Abraham68636062022-11-16 17:07:25 -08001059 const auto& primaryRanges = policy.primaryRanges;
1060 const auto& appRequestRanges = policy.appRequestRanges;
1061 ALOGE_IF(!appRequestRanges.physical.includes(primaryRanges.physical),
Ady Abraham08048ce2022-11-30 18:08:00 -08001062 "Physical range is invalid: primary: %s appRequest: %s",
1063 to_string(primaryRanges.physical).c_str(),
1064 to_string(appRequestRanges.physical).c_str());
1065 ALOGE_IF(!appRequestRanges.render.includes(primaryRanges.render),
1066 "Render range is invalid: primary: %s appRequest: %s",
1067 to_string(primaryRanges.render).c_str(), to_string(appRequestRanges.render).c_str());
Ady Abraham68636062022-11-16 17:07:25 -08001068
1069 return primaryRanges.valid() && appRequestRanges.valid();
Steven Thomasd4071902020-03-24 16:02:53 -07001070}
1071
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001072auto RefreshRateSelector::setPolicy(const PolicyVariant& policy) -> SetPolicyResult {
Dominik Laskowski36dced82022-09-02 09:24:00 -07001073 Policy oldPolicy;
Ady Abrahamace3d052022-11-17 16:25:05 -08001074 PhysicalDisplayId displayId;
Dominik Laskowski36dced82022-09-02 09:24:00 -07001075 {
1076 std::lock_guard lock(mLock);
1077 oldPolicy = *getCurrentPolicyLocked();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001078
Dominik Laskowski36dced82022-09-02 09:24:00 -07001079 const bool valid = ftl::match(
1080 policy,
1081 [this](const auto& policy) {
1082 ftl::FakeGuard guard(mLock);
1083 if (!isPolicyValidLocked(policy)) {
1084 ALOGE("Invalid policy: %s", policy.toString().c_str());
1085 return false;
1086 }
1087
1088 using T = std::decay_t<decltype(policy)>;
1089
1090 if constexpr (std::is_same_v<T, DisplayManagerPolicy>) {
1091 mDisplayManagerPolicy = policy;
1092 } else {
1093 static_assert(std::is_same_v<T, OverridePolicy>);
1094 mOverridePolicy = policy;
1095 }
1096 return true;
1097 },
1098 [this](NoOverridePolicy) {
1099 ftl::FakeGuard guard(mLock);
1100 mOverridePolicy.reset();
1101 return true;
1102 });
1103
1104 if (!valid) {
1105 return SetPolicyResult::Invalid;
1106 }
1107
Ady Abraham68636062022-11-16 17:07:25 -08001108 mGetRankedFrameRatesCache.reset();
Dominik Laskowski36dced82022-09-02 09:24:00 -07001109
1110 if (*getCurrentPolicyLocked() == oldPolicy) {
1111 return SetPolicyResult::Unchanged;
1112 }
1113 constructAvailableRefreshRates();
Ady Abrahamace3d052022-11-17 16:25:05 -08001114
1115 displayId = getActiveModeLocked().modePtr->getPhysicalDisplayId();
Steven Thomasd4071902020-03-24 16:02:53 -07001116 }
Dominik Laskowski36dced82022-09-02 09:24:00 -07001117
Dominik Laskowski36dced82022-09-02 09:24:00 -07001118 const unsigned numModeChanges = std::exchange(mNumModeSwitchesInPolicy, 0u);
1119
1120 ALOGI("Display %s policy changed\n"
1121 "Previous: %s\n"
1122 "Current: %s\n"
1123 "%u mode changes were performed under the previous policy",
1124 to_string(displayId).c_str(), oldPolicy.toString().c_str(), toString(policy).c_str(),
1125 numModeChanges);
1126
1127 return SetPolicyResult::Changed;
Steven Thomasd4071902020-03-24 16:02:53 -07001128}
1129
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001130auto RefreshRateSelector::getCurrentPolicyLocked() const -> const Policy* {
Steven Thomasd4071902020-03-24 16:02:53 -07001131 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
1132}
1133
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001134auto RefreshRateSelector::getCurrentPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001135 std::lock_guard lock(mLock);
1136 return *getCurrentPolicyLocked();
1137}
1138
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001139auto RefreshRateSelector::getDisplayManagerPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001140 std::lock_guard lock(mLock);
1141 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001142}
1143
Ady Abrahamace3d052022-11-17 16:25:05 -08001144bool RefreshRateSelector::isModeAllowed(const FrameRateMode& mode) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001145 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001146 return std::find(mAppRequestFrameRates.begin(), mAppRequestFrameRates.end(), mode) !=
1147 mAppRequestFrameRates.end();
Ady Abraham2139f732019-11-13 18:56:40 -08001148}
1149
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001150void RefreshRateSelector::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001151 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -07001152 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001153 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -07001154
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001155 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -08001156
Ady Abraham68636062022-11-16 17:07:25 -08001157 const auto filterRefreshRates = [&](const FpsRanges& ranges,
1158 const char* rangeName) REQUIRES(mLock) {
1159 const auto filterModes = [&](const DisplayMode& mode) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001160 return mode.getResolution() == defaultMode->getResolution() &&
1161 mode.getDpi() == defaultMode->getDpi() &&
1162 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
Ady Abraham68636062022-11-16 17:07:25 -08001163 ranges.physical.includes(mode.getFps()) &&
1164 (supportsFrameRateOverride() || ranges.render.includes(mode.getFps()));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001165 };
Ady Abraham8a82ba62020-01-17 12:43:17 -08001166
Ady Abraham68636062022-11-16 17:07:25 -08001167 const auto frameRateModes = createFrameRateModes(filterModes, ranges.render);
1168 LOG_ALWAYS_FATAL_IF(frameRateModes.empty(),
Ady Abraham08048ce2022-11-30 18:08:00 -08001169 "No matching frame rate modes for %s range. policy: %s", rangeName,
1170 policy->toString().c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -08001171
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001172 const auto stringifyModes = [&] {
1173 std::string str;
Ady Abraham68636062022-11-16 17:07:25 -08001174 for (const auto& frameRateMode : frameRateModes) {
1175 str += to_string(frameRateMode) + " ";
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001176 }
1177 return str;
1178 };
Ady Abraham68636062022-11-16 17:07:25 -08001179 ALOGV("%s render rates: %s", rangeName, stringifyModes().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -07001180
Ady Abraham68636062022-11-16 17:07:25 -08001181 return frameRateModes;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001182 };
1183
Ady Abraham68636062022-11-16 17:07:25 -08001184 mPrimaryFrameRates = filterRefreshRates(policy->primaryRanges, "primary");
1185 mAppRequestFrameRates = filterRefreshRates(policy->appRequestRanges, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -08001186}
1187
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001188Fps RefreshRateSelector::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001189 using namespace fps_approx_ops;
1190
1191 if (frameRate <= mKnownFrameRates.front()) {
1192 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001193 }
1194
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001195 if (frameRate >= mKnownFrameRates.back()) {
1196 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001197 }
1198
Marin Shalamanove8a663d2020-11-24 17:48:00 +01001199 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001200 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001201
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001202 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
1203 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001204 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
1205}
1206
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001207auto RefreshRateSelector::getIdleTimerAction() const -> KernelIdleTimerAction {
Ana Krulecb9afd792020-06-11 13:16:15 -07001208 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001209
1210 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getFps();
1211 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -07001212
1213 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
1214 // the min allowed refresh rate is higher than the device min, we do not want to enable the
1215 // timer.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001216 if (isStrictlyLess(deviceMinFps, minByPolicy->getFps())) {
1217 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001218 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001219
ramindanid72ba162022-09-09 21:33:40 +00001220 const DisplayModePtr& maxByPolicy =
Ady Abrahamace3d052022-11-17 16:25:05 -08001221 getMaxRefreshRateByPolicyLocked(getActiveModeLocked().modePtr->getGroup());
Ana Krulecb9afd792020-06-11 13:16:15 -07001222 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001223 // Turn on the timer when the min of the primary range is below the device min.
1224 if (const Policy* currentPolicy = getCurrentPolicyLocked();
Ady Abraham285f8c12022-10-11 17:12:14 -07001225 isApproxLess(currentPolicy->primaryRanges.physical.min, deviceMinFps)) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001226 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001227 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001228 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001229 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001230
Ana Krulecb9afd792020-06-11 13:16:15 -07001231 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001232 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001233}
1234
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001235int RefreshRateSelector::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -07001236 // This calculation needs to be in sync with the java code
1237 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001238
1239 // The threshold must be smaller than 0.001 in order to differentiate
1240 // between the fractional pairs (e.g. 59.94 and 60).
1241 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001242 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -07001243 const auto numPeriodsRounded = std::round(numPeriods);
1244 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001245 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -07001246 }
1247
Ady Abraham62f216c2020-10-13 19:07:23 -07001248 return static_cast<int>(numPeriodsRounded);
1249}
1250
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001251bool RefreshRateSelector::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001252 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001253 return isFractionalPairOrMultiple(bigger, smaller);
1254 }
1255
1256 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
1257 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001258 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
1259 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001260}
1261
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001262void RefreshRateSelector::dump(utils::Dumper& dumper) const {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001263 using namespace std::string_view_literals;
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001264
Marin Shalamanovba421a82020-11-10 21:49:26 +01001265 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +01001266
Ady Abrahamace3d052022-11-17 16:25:05 -08001267 const auto activeMode = getActiveModeLocked();
1268 dumper.dump("activeMode"sv, to_string(activeMode));
Marin Shalamanovba421a82020-11-10 21:49:26 +01001269
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001270 dumper.dump("displayModes"sv);
1271 {
1272 utils::Dumper::Indent indent(dumper);
1273 for (const auto& [id, mode] : mDisplayModes) {
1274 dumper.dump({}, to_string(*mode));
1275 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001276 }
1277
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001278 dumper.dump("displayManagerPolicy"sv, mDisplayManagerPolicy.toString());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001279
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001280 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
1281 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001282 dumper.dump("overridePolicy"sv, currentPolicy.toString());
ramindani32cf0602022-03-02 02:30:29 +00001283 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001284
Ady Abraham8ca643a2022-10-18 18:26:47 -07001285 dumper.dump("frameRateOverrideConfig"sv, *ftl::enum_name(mFrameRateOverrideConfig));
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001286
Dominik Laskowski03cfce82022-11-02 12:13:29 -04001287 dumper.dump("idleTimer"sv);
1288 {
1289 utils::Dumper::Indent indent(dumper);
1290 dumper.dump("interval"sv, mIdleTimer.transform(&OneShotTimer::interval));
1291 dumper.dump("controller"sv,
1292 mConfig.kernelIdleTimerController
1293 .and_then(&ftl::enum_name<KernelIdleTimerController>)
1294 .value_or("Platform"sv));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001295 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001296}
1297
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001298std::chrono::milliseconds RefreshRateSelector::getIdleTimerTimeout() {
ramindani32cf0602022-03-02 02:30:29 +00001299 return mConfig.idleTimerTimeout;
1300}
1301
Ady Abraham2139f732019-11-13 18:56:40 -08001302} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001303
1304// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001305#pragma clang diagnostic pop // ignored "-Wextra"