blob: 1d27cfcecef92d1c4b28b93d88f0a5ee2e0039ce [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 Abrahamccf63862023-01-19 11:44:01 -080035#include <gui/TraceUtils.h>
Ady Abraham68636062022-11-16 17:07:25 -080036#include <scheduler/FrameRateMode.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070037#include <utils/Trace.h>
38
Ady Abraham4899ff82021-01-06 13:53:29 -080039#include "../SurfaceFlingerProperties.h"
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040040#include "RefreshRateSelector.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080041
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080042#undef LOG_TAG
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040043#define LOG_TAG "RefreshRateSelector"
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080044
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080045namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010046namespace {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070047
Dominik Laskowskib0054a22022-03-03 09:03:06 -080048struct RefreshRateScore {
Ady Abraham68636062022-11-16 17:07:25 -080049 FrameRateMode frameRateMode;
Ady Abrahamae2e3c72022-08-13 05:12:13 +000050 float overallScore;
51 struct {
Ady Abraham62f51d92022-08-24 22:20:22 +000052 float modeBelowThreshold;
53 float modeAboveThreshold;
54 } fixedRateBelowThresholdLayersScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -080055};
56
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040057constexpr RefreshRateSelector::GlobalSignals kNoSignals;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080058
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040059std::string formatLayerInfo(const RefreshRateSelector::LayerRequirement& layer, float weight) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080060 return base::StringPrintf("%s (type=%s, weight=%.2f, seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070061 ftl::enum_string(layer.vote).c_str(), weight,
62 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010063 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010064}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010065
Marin Shalamanova7fe3042021-01-29 21:02:08 +010066std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070067 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010068 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010069
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070070 // Add all supported refresh rates.
Dominik Laskowskib0054a22022-03-03 09:03:06 -080071 for (const auto& [id, mode] : modes) {
72 knownFrameRates.push_back(mode->getFps());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010073 }
74
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070075 // Sort and remove duplicates.
76 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010077 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070078 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010079 knownFrameRates.end());
80 return knownFrameRates;
81}
82
Ady Abraham68636062022-11-16 17:07:25 -080083std::vector<DisplayModeIterator> sortByRefreshRate(const DisplayModes& modes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080084 std::vector<DisplayModeIterator> sortedModes;
85 sortedModes.reserve(modes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -080086 for (auto it = modes.begin(); it != modes.end(); ++it) {
Ady Abraham68636062022-11-16 17:07:25 -080087 sortedModes.push_back(it);
Dominik Laskowskib0054a22022-03-03 09:03:06 -080088 }
89
90 std::sort(sortedModes.begin(), sortedModes.end(), [](auto it1, auto it2) {
91 const auto& mode1 = it1->second;
92 const auto& mode2 = it2->second;
93
94 if (mode1->getVsyncPeriod() == mode2->getVsyncPeriod()) {
95 return mode1->getGroup() > mode2->getGroup();
96 }
97
98 return mode1->getVsyncPeriod() > mode2->getVsyncPeriod();
99 });
100
101 return sortedModes;
Marin Shalamanov46084422020-10-13 12:33:42 +0200102}
103
Ady Abraham68636062022-11-16 17:07:25 -0800104std::pair<unsigned, unsigned> divisorRange(Fps fps, FpsRange range,
105 RefreshRateSelector::Config::FrameRateOverride config) {
106 if (config != RefreshRateSelector::Config::FrameRateOverride::Enabled) {
107 return {1, 1};
108 }
109
110 using fps_approx_ops::operator/;
Ady Abraham08048ce2022-11-30 18:08:00 -0800111 // use signed type as `fps / range.max` might be 0
112 const auto start = std::max(1, static_cast<int>(fps / range.max) - 1);
Ady Abraham68636062022-11-16 17:07:25 -0800113 const auto end = fps /
114 std::max(range.min, RefreshRateSelector::kMinSupportedFrameRate,
115 fps_approx_ops::operator<);
116
117 return {start, end};
118}
119
Ady Abraham8ca643a2022-10-18 18:26:47 -0700120bool shouldEnableFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800121 for (const auto it1 : sortedModes) {
122 const auto& mode1 = it1->second;
123 for (const auto it2 : sortedModes) {
124 const auto& mode2 = it2->second;
125
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400126 if (RefreshRateSelector::getFrameRateDivisor(mode1->getFps(), mode2->getFps()) >= 2) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800127 return true;
128 }
129 }
130 }
131 return false;
132}
133
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400134std::string toString(const RefreshRateSelector::PolicyVariant& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700135 using namespace std::string_literals;
136
137 return ftl::match(
138 policy,
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400139 [](const RefreshRateSelector::DisplayManagerPolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700140 return "DisplayManagerPolicy"s + policy.toString();
141 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400142 [](const RefreshRateSelector::OverridePolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700143 return "OverridePolicy"s + policy.toString();
144 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400145 [](RefreshRateSelector::NoOverridePolicy) { return "NoOverridePolicy"s; });
Dominik Laskowski36dced82022-09-02 09:24:00 -0700146}
147
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800148} // namespace
149
Ady Abraham68636062022-11-16 17:07:25 -0800150auto RefreshRateSelector::createFrameRateModes(
151 std::function<bool(const DisplayMode&)>&& filterModes, const FpsRange& renderRange) const
152 -> std::vector<FrameRateMode> {
153 struct Key {
154 Fps fps;
155 int32_t group;
156 };
157
158 struct KeyLess {
159 bool operator()(const Key& a, const Key& b) const {
160 using namespace fps_approx_ops;
161 if (a.fps != b.fps) {
162 return a.fps < b.fps;
163 }
164
165 // For the same fps the order doesn't really matter, but we still
166 // want the behaviour of a strictly less operator.
167 // We use the group id as the secondary ordering for that.
168 return a.group < b.group;
169 }
170 };
171
172 std::map<Key, DisplayModeIterator, KeyLess> ratesMap;
173 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
174 const auto& [id, mode] = *it;
175
176 if (!filterModes(*mode)) {
177 continue;
178 }
179 const auto [start, end] =
180 divisorRange(mode->getFps(), renderRange, mConfig.enableFrameRateOverride);
181 for (auto divisor = start; divisor <= end; divisor++) {
182 const auto fps = mode->getFps() / divisor;
183 using fps_approx_ops::operator<;
Ady Abrahamdc0b3a72023-01-04 16:58:27 -0800184 if (divisor > 1 && fps < kMinSupportedFrameRate) {
Ady Abraham68636062022-11-16 17:07:25 -0800185 break;
186 }
187
188 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Enabled &&
189 !renderRange.includes(fps)) {
190 continue;
191 }
192
193 if (mConfig.enableFrameRateOverride ==
194 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
195 !isNativeRefreshRate(fps)) {
196 continue;
197 }
198
199 const auto [existingIter, emplaceHappened] =
200 ratesMap.try_emplace(Key{fps, mode->getGroup()}, it);
201 if (emplaceHappened) {
202 ALOGV("%s: including %s (%s)", __func__, to_string(fps).c_str(),
203 to_string(mode->getFps()).c_str());
204 } else {
205 // We might need to update the map as we found a lower refresh rate
206 if (isStrictlyLess(mode->getFps(), existingIter->second->second->getFps())) {
207 existingIter->second = it;
208 ALOGV("%s: changing %s (%s)", __func__, to_string(fps).c_str(),
209 to_string(mode->getFps()).c_str());
210 }
211 }
212 }
213 }
214
215 std::vector<FrameRateMode> frameRateModes;
216 frameRateModes.reserve(ratesMap.size());
217 for (const auto& [key, mode] : ratesMap) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800218 frameRateModes.emplace_back(FrameRateMode{key.fps, ftl::as_non_null(mode->second)});
Ady Abraham68636062022-11-16 17:07:25 -0800219 }
220
221 // We always want that the lowest frame rate will be corresponding to the
222 // lowest mode for power saving.
223 const auto lowestRefreshRateIt =
224 std::min_element(frameRateModes.begin(), frameRateModes.end(),
225 [](const FrameRateMode& lhs, const FrameRateMode& rhs) {
226 return isStrictlyLess(lhs.modePtr->getFps(),
227 rhs.modePtr->getFps());
228 });
229 frameRateModes.erase(frameRateModes.begin(), lowestRefreshRateIt);
230
231 return frameRateModes;
232}
233
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400234struct RefreshRateSelector::RefreshRateScoreComparator {
ramindanid72ba162022-09-09 21:33:40 +0000235 bool operator()(const RefreshRateScore& lhs, const RefreshRateScore& rhs) const {
Ady Abraham68636062022-11-16 17:07:25 -0800236 const auto& [frameRateMode, overallScore, _] = lhs;
ramindanid72ba162022-09-09 21:33:40 +0000237
Ady Abraham68636062022-11-16 17:07:25 -0800238 std::string name = to_string(frameRateMode);
239
ramindanid72ba162022-09-09 21:33:40 +0000240 ALOGV("%s sorting scores %.2f", name.c_str(), overallScore);
ramindanid72ba162022-09-09 21:33:40 +0000241 ATRACE_INT(name.c_str(), static_cast<int>(std::round(overallScore * 100)));
242
Ady Abraham68636062022-11-16 17:07:25 -0800243 if (!ScoredFrameRate::scoresEqual(overallScore, rhs.overallScore)) {
ramindanid72ba162022-09-09 21:33:40 +0000244 return overallScore > rhs.overallScore;
245 }
246
ramindanid72ba162022-09-09 21:33:40 +0000247 if (refreshRateOrder == RefreshRateOrder::Descending) {
248 using fps_approx_ops::operator>;
Ady Abraham68636062022-11-16 17:07:25 -0800249 return frameRateMode.fps > rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000250 } else {
251 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -0800252 return frameRateMode.fps < rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000253 }
254 }
255
256 const RefreshRateOrder refreshRateOrder;
257};
258
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400259std::string RefreshRateSelector::Policy::toString() const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700260 return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
Ady Abraham285f8c12022-10-11 17:12:14 -0700261 ", primaryRanges=%s, appRequestRanges=%s}",
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700262 defaultMode.value(), allowGroupSwitching ? "true" : "false",
Ady Abraham285f8c12022-10-11 17:12:14 -0700263 to_string(primaryRanges).c_str(),
264 to_string(appRequestRanges).c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200265}
266
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400267std::pair<nsecs_t, nsecs_t> RefreshRateSelector::getDisplayFrames(nsecs_t layerPeriod,
268 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800269 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
270 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
271 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
272 quotient++;
273 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800274 }
275
Ady Abraham62a0be22020-12-08 16:54:10 -0800276 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800277}
278
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400279float RefreshRateSelector::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
280 Fps refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200281 constexpr float kScoreForFractionalPairs = .8f;
282
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800283 const auto displayPeriod = refreshRate.getPeriodNsecs();
Ady Abraham62a0be22020-12-08 16:54:10 -0800284 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
285 if (layer.vote == LayerVoteType::ExplicitDefault) {
286 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200287 // that layerPeriod is the minimal period to render a frame.
288 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
289 // then the actualLayerPeriod will be 32ms, because it is the
290 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800291 auto actualLayerPeriod = displayPeriod;
292 int multiplier = 1;
293 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
294 multiplier++;
295 actualLayerPeriod = displayPeriod * multiplier;
296 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200297
298 // Because of the threshold we used above it's possible that score is slightly
299 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800300 return std::min(1.0f,
301 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
302 }
303
304 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
305 layer.vote == LayerVoteType::Heuristic) {
Ady Abraham68636062022-11-16 17:07:25 -0800306 const float multiplier = refreshRate.getValue() / layer.desiredRefreshRate.getValue();
307
308 // We only want to score this layer as a fractional pair if the content is not
309 // significantly faster than the display rate, at it would cause a significant frame drop.
310 // It is more appropriate to choose a higher display rate even if
311 // a pull-down will be required.
312 constexpr float kMinMultiplier = 0.25f;
313 if (multiplier >= kMinMultiplier &&
314 isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700315 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200316 }
317
Ady Abraham62a0be22020-12-08 16:54:10 -0800318 // Calculate how many display vsyncs we need to present a single frame for this
319 // layer
320 const auto [displayFramesQuotient, displayFramesRemainder] =
321 getDisplayFrames(layerPeriod, displayPeriod);
322 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
323 if (displayFramesRemainder == 0) {
324 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700325 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800326 }
327
328 if (displayFramesQuotient == 0) {
329 // Layer desired refresh rate is higher than the display rate.
330 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
331 (1.0f / (MAX_FRAMES_TO_FIT + 1));
332 }
333
334 // Layer desired refresh rate is lower than the display rate. Check how well it fits
335 // the cadence.
336 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
337 int iter = 2;
338 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
339 diff = diff - (displayPeriod - diff);
340 iter++;
341 }
342
Ady Abraham05243be2021-09-16 15:58:52 -0700343 return (1.0f / iter);
344 }
345
346 return 0;
347}
348
Ady Abraham68636062022-11-16 17:07:25 -0800349float RefreshRateSelector::calculateDistanceScoreFromMax(Fps refreshRate) const {
350 const auto& maxFps = mAppRequestFrameRates.back().fps;
351 const float ratio = refreshRate.getValue() / maxFps.getValue();
ramindanid72ba162022-09-09 21:33:40 +0000352 // Use ratio^2 to get a lower score the more we get further from peak
353 return ratio * ratio;
354}
355
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400356float RefreshRateSelector::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
357 bool isSeamlessSwitch) const {
Ady Abraham73c3df52023-01-12 18:09:31 -0800358 ATRACE_CALL();
Ady Abraham05243be2021-09-16 15:58:52 -0700359 // Slightly prefer seamless switches.
360 constexpr float kSeamedSwitchPenalty = 0.95f;
361 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
362
363 // If the layer wants Max, give higher score to the higher refresh rate
364 if (layer.vote == LayerVoteType::Max) {
Ady Abraham68636062022-11-16 17:07:25 -0800365 return calculateDistanceScoreFromMax(refreshRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800366 }
367
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800368 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800369 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Ady Abraham68636062022-11-16 17:07:25 -0800370 if (supportsAppFrameRateOverrideByContent()) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800371 // Since we support frame rate override, allow refresh rates which are
372 // multiples of the layer's request, as those apps would be throttled
373 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800374 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800375 }
376
Ady Abrahamcc315492022-02-17 17:06:39 -0800377 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800378 }
379
Ady Abrahamcc315492022-02-17 17:06:39 -0800380 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700381 // the highest score.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800382 if (getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700383 return 1.0f * seamlessness;
384 }
385
Ady Abrahamcc315492022-02-17 17:06:39 -0800386 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700387 // there is a small penalty attached to the score to favor the frame rates
388 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800389 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700390 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
391 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800392}
393
Ady Abraham68636062022-11-16 17:07:25 -0800394auto RefreshRateSelector::getRankedFrameRates(const std::vector<LayerRequirement>& layers,
395 GlobalSignals signals) const -> RankedFrameRates {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200396 std::lock_guard lock(mLock);
397
Ady Abraham68636062022-11-16 17:07:25 -0800398 if (mGetRankedFrameRatesCache &&
399 mGetRankedFrameRatesCache->arguments == std::make_pair(layers, signals)) {
400 return mGetRankedFrameRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200401 }
402
Ady Abraham68636062022-11-16 17:07:25 -0800403 const auto result = getRankedFrameRatesLocked(layers, signals);
404 mGetRankedFrameRatesCache = GetRankedFrameRatesCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200405 return result;
406}
407
Ady Abraham68636062022-11-16 17:07:25 -0800408auto RefreshRateSelector::getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
409 GlobalSignals signals) const
410 -> RankedFrameRates {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000411 using namespace fps_approx_ops;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800412 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800413 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700414
Ady Abrahamace3d052022-11-17 16:25:05 -0800415 const auto& activeMode = *getActiveModeLocked().modePtr;
ramindani38c84982022-08-29 18:02:57 +0000416
Ady Abraham68636062022-11-16 17:07:25 -0800417 // Keep the display at max frame rate for the duration of powering on the display.
ramindani38c84982022-08-29 18:02:57 +0000418 if (signals.powerOnImminent) {
419 ALOGV("Power On Imminent");
Ady Abrahamccf63862023-01-19 11:44:01 -0800420 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Descending);
421 ATRACE_FORMAT_INSTANT("%s (Power On Imminent)",
422 to_string(ranking.front().frameRateMode.fps).c_str());
423 return {ranking, GlobalSignals{.powerOnImminent = true}};
ramindani38c84982022-08-29 18:02:57 +0000424 }
425
Ady Abraham8a82ba62020-01-17 12:43:17 -0800426 int noVoteLayers = 0;
427 int minVoteLayers = 0;
428 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800429 int explicitDefaultVoteLayers = 0;
430 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800431 int explicitExact = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100432 int seamedFocusedLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800433
Ady Abraham8a82ba62020-01-17 12:43:17 -0800434 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800435 switch (layer.vote) {
436 case LayerVoteType::NoVote:
437 noVoteLayers++;
438 break;
439 case LayerVoteType::Min:
440 minVoteLayers++;
441 break;
442 case LayerVoteType::Max:
443 maxVoteLayers++;
444 break;
445 case LayerVoteType::ExplicitDefault:
446 explicitDefaultVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800447 break;
448 case LayerVoteType::ExplicitExactOrMultiple:
449 explicitExactOrMultipleVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800450 break;
451 case LayerVoteType::ExplicitExact:
452 explicitExact++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800453 break;
454 case LayerVoteType::Heuristic:
455 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800456 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200457
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100458 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
459 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200460 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800461 }
462
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800463 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
464 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700465
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200466 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800467 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700468
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200469 // If the default mode group is different from the group of current mode,
470 // this means a layer requesting a seamed mode switch just disappeared and
471 // we should switch back to the default group.
472 // However if a seamed layer is still present we anchor around the group
473 // of the current mode, in order to prevent unnecessary seamed mode switches
474 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800475 const auto anchorGroup =
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700476 seamedFocusedLayers > 0 ? activeMode.getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200477
Steven Thomasf734df42020-04-13 21:09:28 -0700478 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
479 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800480 if (signals.touch && !hasExplicitVoteLayers) {
ramindanid72ba162022-09-09 21:33:40 +0000481 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800482 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
483 ATRACE_FORMAT_INSTANT("%s (Touch Boost)",
484 to_string(ranking.front().frameRateMode.fps).c_str());
485 return {ranking, GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800486 }
487
Alec Mouri11232a22020-05-14 18:06:25 -0700488 // If the primary range consists of a single refresh rate then we can only
489 // move out the of range if layers explicitly request a different refresh
490 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100491 const bool primaryRangeIsSingleRate =
Ady Abraham285f8c12022-10-11 17:12:14 -0700492 isApproxEqual(policy->primaryRanges.physical.min, policy->primaryRanges.physical.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700493
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800494 if (!signals.touch && signals.idle && !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
ramindanid72ba162022-09-09 21:33:40 +0000495 ALOGV("Idle");
Ady Abrahamccf63862023-01-19 11:44:01 -0800496 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending);
497 ATRACE_FORMAT_INSTANT("%s (Idle)", to_string(ranking.front().frameRateMode.fps).c_str());
498 return {ranking, GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700499 }
500
Steven Thomasdebafed2020-05-18 17:30:35 -0700501 if (layers.empty() || noVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000502 ALOGV("No layers with votes");
Ady Abrahamccf63862023-01-19 11:44:01 -0800503 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
504 ATRACE_FORMAT_INSTANT("%s (No layers with votes)",
505 to_string(ranking.front().frameRateMode.fps).c_str());
506 return {ranking, kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700507 }
508
Ady Abraham8a82ba62020-01-17 12:43:17 -0800509 // Only if all layers want Min we should return Min
510 if (noVoteLayers + minVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000511 ALOGV("All layers Min");
Ady Abrahamccf63862023-01-19 11:44:01 -0800512 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending);
513 ATRACE_FORMAT_INSTANT("%s (All layers Min)",
514 to_string(ranking.front().frameRateMode.fps).c_str());
515 return {ranking, kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800516 }
517
Ady Abraham8a82ba62020-01-17 12:43:17 -0800518 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800519 std::vector<RefreshRateScore> scores;
Ady Abraham68636062022-11-16 17:07:25 -0800520 scores.reserve(mAppRequestFrameRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800521
Ady Abraham68636062022-11-16 17:07:25 -0800522 for (const FrameRateMode& it : mAppRequestFrameRates) {
523 scores.emplace_back(RefreshRateScore{it, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800524 }
525
526 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700527 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700528 ftl::enum_string(layer.vote).c_str(), layer.weight,
rnlee3bd610662021-06-23 16:27:57 -0700529 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800530 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800531 continue;
532 }
533
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800534 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800535
Ady Abraham68636062022-11-16 17:07:25 -0800536 for (auto& [mode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
537 const auto& [fps, modePtr] = mode;
538 const bool isSeamlessSwitch = modePtr->getGroup() == activeMode.getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200539
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100540 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100541 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800542 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700543 to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200544 continue;
545 }
546
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100547 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
548 !layer.focused) {
549 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100550 " Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800551 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700552 to_string(activeMode).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100553 continue;
554 }
555
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100556 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100557 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100558 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100559 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
560 // disappeared.
Ady Abraham68636062022-11-16 17:07:25 -0800561 const bool isInPolicyForDefault = modePtr->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100562 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100563 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham68636062022-11-16 17:07:25 -0800564 to_string(*modePtr).c_str(), to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200565 continue;
566 }
567
Ady Abraham68636062022-11-16 17:07:25 -0800568 const bool inPrimaryRange = policy->primaryRanges.physical.includes(modePtr->getFps());
Alec Mouri11232a22020-05-14 18:06:25 -0700569 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800570 !(layer.focused &&
571 (layer.vote == LayerVoteType::ExplicitDefault ||
572 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700573 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700574 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700575 continue;
576 }
577
Ady Abraham68636062022-11-16 17:07:25 -0800578 const float layerScore = calculateLayerScoreLocked(layer, fps, isSeamlessSwitch);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000579 const float weightedLayerScore = weight * layerScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800580
Ady Abraham13cfb362022-08-13 05:12:13 +0000581 // Layer with fixed source has a special consideration which depends on the
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000582 // mConfig.frameRateMultipleThreshold. We don't want these layers to score
583 // refresh rates above the threshold, but we also don't want to favor the lower
584 // ones by having a greater number of layers scoring them. Instead, we calculate
585 // the score independently for these layers and later decide which
586 // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
587 // score 120 Hz, but desired 60 fps should contribute to the score.
588 const bool fixedSourceLayer = [](LayerVoteType vote) {
589 switch (vote) {
590 case LayerVoteType::ExplicitExactOrMultiple:
591 case LayerVoteType::Heuristic:
592 return true;
593 case LayerVoteType::NoVote:
594 case LayerVoteType::Min:
595 case LayerVoteType::Max:
596 case LayerVoteType::ExplicitDefault:
597 case LayerVoteType::ExplicitExact:
598 return false;
599 }
600 }(layer.vote);
Ady Abraham62f51d92022-08-24 22:20:22 +0000601 const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000602 layer.desiredRefreshRate <
603 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
Ady Abraham62f51d92022-08-24 22:20:22 +0000604 if (fixedSourceLayer && layerBelowThreshold) {
Ady Abraham13cfb362022-08-13 05:12:13 +0000605 const bool modeAboveThreshold =
Ady Abraham68636062022-11-16 17:07:25 -0800606 modePtr->getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
Ady Abraham62f51d92022-08-24 22:20:22 +0000607 if (modeAboveThreshold) {
Ady Abraham68636062022-11-16 17:07:25 -0800608 ALOGV("%s gives %s (%s) fixed source (above threshold) score of %.4f",
609 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
610 to_string(modePtr->getFps()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000611 fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000612 } else {
Ady Abraham68636062022-11-16 17:07:25 -0800613 ALOGV("%s gives %s (%s) fixed source (below threshold) score of %.4f",
614 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
615 to_string(modePtr->getFps()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000616 fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000617 }
618 } else {
Ady Abraham68636062022-11-16 17:07:25 -0800619 ALOGV("%s gives %s (%s) score of %.4f", formatLayerInfo(layer, weight).c_str(),
620 to_string(fps).c_str(), to_string(modePtr->getFps()).c_str(), layerScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000621 overallScore += weightedLayerScore;
622 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800623 }
624 }
625
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000626 // We want to find the best refresh rate without the fixed source layers,
Ady Abraham62f51d92022-08-24 22:20:22 +0000627 // so we could know whether we should add the modeAboveThreshold scores or not.
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000628 // If the best refresh rate is already above the threshold, it means that
629 // some non-fixed source layers already scored it, so we can just add the score
630 // for all fixed source layers, even the ones that are above the threshold.
631 const bool maxScoreAboveThreshold = [&] {
632 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
633 return false;
634 }
635
636 const auto maxScoreIt =
637 std::max_element(scores.begin(), scores.end(),
638 [](RefreshRateScore max, RefreshRateScore current) {
Ady Abraham68636062022-11-16 17:07:25 -0800639 return current.overallScore > max.overallScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000640 });
Ady Abraham68636062022-11-16 17:07:25 -0800641 ALOGV("%s (%s) is the best refresh rate without fixed source layers. It is %s the "
642 "threshold for "
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000643 "refresh rate multiples",
Ady Abraham68636062022-11-16 17:07:25 -0800644 to_string(maxScoreIt->frameRateMode.fps).c_str(),
645 to_string(maxScoreIt->frameRateMode.modePtr->getFps()).c_str(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000646 maxScoreAboveThreshold ? "above" : "below");
Ady Abraham68636062022-11-16 17:07:25 -0800647 return maxScoreIt->frameRateMode.modePtr->getFps() >=
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000648 Fps::fromValue(mConfig.frameRateMultipleThreshold);
649 }();
650
651 // Now we can add the fixed rate layers score
Ady Abraham68636062022-11-16 17:07:25 -0800652 for (auto& [frameRateMode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000653 overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000654 if (maxScoreAboveThreshold) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000655 overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000656 }
Ady Abraham68636062022-11-16 17:07:25 -0800657 ALOGV("%s (%s) adjusted overallScore is %.4f", to_string(frameRateMode.fps).c_str(),
658 to_string(frameRateMode.modePtr->getFps()).c_str(), overallScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000659 }
660
661 // Now that we scored all the refresh rates we need to pick the one that got the highest
ramindanid72ba162022-09-09 21:33:40 +0000662 // overallScore. Sort the scores based on their overallScore in descending order of priority.
663 const RefreshRateOrder refreshRateOrder =
664 maxVoteLayers > 0 ? RefreshRateOrder::Descending : RefreshRateOrder::Ascending;
665 std::sort(scores.begin(), scores.end(),
666 RefreshRateScoreComparator{.refreshRateOrder = refreshRateOrder});
ramindanid72ba162022-09-09 21:33:40 +0000667
Ady Abraham68636062022-11-16 17:07:25 -0800668 FrameRateRanking ranking;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400669 ranking.reserve(scores.size());
670
671 std::transform(scores.begin(), scores.end(), back_inserter(ranking),
ramindanid72ba162022-09-09 21:33:40 +0000672 [](const RefreshRateScore& score) {
Ady Abraham68636062022-11-16 17:07:25 -0800673 return ScoredFrameRate{score.frameRateMode, score.overallScore};
ramindanid72ba162022-09-09 21:33:40 +0000674 });
Ady Abraham34702102020-02-10 14:12:05 -0800675
Ady Abraham37d46922022-10-05 13:08:51 -0700676 const bool noLayerScore = std::all_of(scores.begin(), scores.end(), [](RefreshRateScore score) {
677 return score.overallScore == 0;
678 });
679
Alec Mouri11232a22020-05-14 18:06:25 -0700680 if (primaryRangeIsSingleRate) {
681 // If we never scored any layers, then choose the rate from the primary
682 // range instead of picking a random score from the app range.
Ady Abraham37d46922022-10-05 13:08:51 -0700683 if (noLayerScore) {
ramindanid72ba162022-09-09 21:33:40 +0000684 ALOGV("Layers not scored");
Ady Abrahamccf63862023-01-19 11:44:01 -0800685 const auto descending = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
686 ATRACE_FORMAT_INSTANT("%s (Layers not scored)",
687 to_string(descending.front().frameRateMode.fps).c_str());
688 return {descending, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700689 } else {
Ady Abrahamccf63862023-01-19 11:44:01 -0800690 ATRACE_FORMAT_INSTANT("%s (primaryRangeIsSingleRate)",
691 to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400692 return {ranking, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700693 }
694 }
695
Steven Thomasf734df42020-04-13 21:09:28 -0700696 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
697 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
698 // vote we should not change it if we get a touch event. Only apply touch boost if it will
699 // actually increase the refresh rate over the normal selection.
Ady Abraham5e4e9832021-06-14 13:40:56 -0700700 const bool touchBoostForExplicitExact = [&] {
Ady Abraham68636062022-11-16 17:07:25 -0800701 if (supportsAppFrameRateOverrideByContent()) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700702 // Enable touch boost if there are other layers besides exact
703 return explicitExact + noVoteLayers != layers.size();
704 } else {
705 // Enable touch boost if there are no exact layers
706 return explicitExact == 0;
707 }
708 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700709
Ady Abraham68636062022-11-16 17:07:25 -0800710 const auto touchRefreshRates = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700711 using fps_approx_ops::operator<;
712
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800713 if (signals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Ady Abraham68636062022-11-16 17:07:25 -0800714 scores.front().frameRateMode.fps < touchRefreshRates.front().frameRateMode.fps) {
ramindanid72ba162022-09-09 21:33:40 +0000715 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800716 ATRACE_FORMAT_INSTANT("%s (Touch Boost [late])",
717 to_string(touchRefreshRates.front().frameRateMode.fps).c_str());
ramindanid72ba162022-09-09 21:33:40 +0000718 return {touchRefreshRates, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700719 }
720
Ady Abraham37d46922022-10-05 13:08:51 -0700721 // If we never scored any layers, and we don't favor high refresh rates, prefer to stay with the
722 // current config
723 if (noLayerScore && refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abrahamccf63862023-01-19 11:44:01 -0800724 const auto ascendingWithPreferred =
725 rankFrameRates(anchorGroup, RefreshRateOrder::Ascending, activeMode.getId());
726 ATRACE_FORMAT_INSTANT("%s (preferredDisplayMode)",
727 to_string(ascendingWithPreferred.front().frameRateMode.fps).c_str());
728 return {ascendingWithPreferred, kNoSignals};
Ady Abraham37d46922022-10-05 13:08:51 -0700729 }
730
Ady Abrahamccf63862023-01-19 11:44:01 -0800731 ATRACE_FORMAT_INSTANT("%s (scored))", to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400732 return {ranking, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800733}
734
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400735using LayerRequirementPtrs = std::vector<const RefreshRateSelector::LayerRequirement*>;
736using PerUidLayerRequirements = std::unordered_map<uid_t, LayerRequirementPtrs>;
737
738PerUidLayerRequirements groupLayersByUid(
739 const std::vector<RefreshRateSelector::LayerRequirement>& layers) {
740 PerUidLayerRequirements layersByUid;
Ady Abraham62a0be22020-12-08 16:54:10 -0800741 for (const auto& layer : layers) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400742 const auto it = layersByUid.emplace(layer.ownerUid, LayerRequirementPtrs()).first;
743 auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800744 layersWithSameUid.push_back(&layer);
745 }
746
747 // Remove uids that can't have a frame rate override
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400748 for (auto it = layersByUid.begin(); it != layersByUid.end();) {
749 const auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800750 bool skipUid = false;
751 for (const auto& layer : layersWithSameUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400752 using LayerVoteType = RefreshRateSelector::LayerVoteType;
753
754 if (layer->vote == LayerVoteType::Max || layer->vote == LayerVoteType::Heuristic) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800755 skipUid = true;
756 break;
757 }
758 }
759 if (skipUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400760 it = layersByUid.erase(it);
Ady Abraham62a0be22020-12-08 16:54:10 -0800761 } else {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400762 ++it;
Ady Abraham62a0be22020-12-08 16:54:10 -0800763 }
764 }
765
766 return layersByUid;
767}
768
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400769auto RefreshRateSelector::getFrameRateOverrides(const std::vector<LayerRequirement>& layers,
770 Fps displayRefreshRate,
771 GlobalSignals globalSignals) const
772 -> UidToFrameRateOverride {
Ady Abraham62a0be22020-12-08 16:54:10 -0800773 ATRACE_CALL();
Ady Abraham68636062022-11-16 17:07:25 -0800774 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Disabled) {
775 return {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800776 }
777
Ady Abraham68636062022-11-16 17:07:25 -0800778 ALOGV("%s: %zu layers", __func__, layers.size());
779 std::lock_guard lock(mLock);
780
Ady Abraham8ca643a2022-10-18 18:26:47 -0700781 const auto* policyPtr = getCurrentPolicyLocked();
782 // We don't want to run lower than 30fps
783 const Fps minFrameRate = std::max(policyPtr->appRequestRanges.render.min, 30_Hz, isApproxLess);
784
785 using fps_approx_ops::operator/;
786 const unsigned numMultiples = displayRefreshRate / minFrameRate;
787
788 std::vector<std::pair<Fps, float>> scoredFrameRates;
789 scoredFrameRates.reserve(numMultiples);
790
791 for (unsigned n = numMultiples; n > 0; n--) {
792 const Fps divisor = displayRefreshRate / n;
793 if (mConfig.enableFrameRateOverride ==
Ady Abraham68636062022-11-16 17:07:25 -0800794 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
795 !isNativeRefreshRate(divisor)) {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700796 continue;
797 }
798
799 if (policyPtr->appRequestRanges.render.includes(divisor)) {
800 ALOGV("%s: adding %s as a potential frame rate", __func__, to_string(divisor).c_str());
801 scoredFrameRates.emplace_back(divisor, 0);
802 }
803 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800804
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400805 const auto layersByUid = groupLayersByUid(layers);
Ady Abraham62a0be22020-12-08 16:54:10 -0800806 UidToFrameRateOverride frameRateOverrides;
807 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800808 // Layers with ExplicitExactOrMultiple expect touch boost
809 const bool hasExplicitExactOrMultiple =
810 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
811 [](const auto& layer) {
812 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
813 });
814
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700815 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800816 continue;
817 }
818
Ady Abraham8ca643a2022-10-18 18:26:47 -0700819 for (auto& [_, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800820 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -0800821 }
822
823 for (const auto& layer : layersWithSameUid) {
824 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
825 continue;
826 }
827
828 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800829 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
830 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700831 for (auto& [fps, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800832 constexpr bool isSeamlessSwitch = true;
Ady Abraham8ca643a2022-10-18 18:26:47 -0700833 const auto layerScore = calculateLayerScoreLocked(*layer, fps, isSeamlessSwitch);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800834 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -0800835 }
836 }
837
Ady Abraham62a0be22020-12-08 16:54:10 -0800838 // If we never scored any layers, we don't have a preferred frame rate
Ady Abraham8ca643a2022-10-18 18:26:47 -0700839 if (std::all_of(scoredFrameRates.begin(), scoredFrameRates.end(),
840 [](const auto& scoredFrameRate) {
841 const auto [_, score] = scoredFrameRate;
842 return score == 0;
843 })) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800844 continue;
845 }
846
ramindanid72ba162022-09-09 21:33:40 +0000847 // Now that we scored all the refresh rates we need to pick the lowest refresh rate
848 // that got the highest score.
Ady Abraham8ca643a2022-10-18 18:26:47 -0700849 const auto [overrideFps, _] =
850 *std::max_element(scoredFrameRates.begin(), scoredFrameRates.end(),
851 [](const auto& lhsPair, const auto& rhsPair) {
852 const float lhs = lhsPair.second;
853 const float rhs = rhsPair.second;
Ady Abraham68636062022-11-16 17:07:25 -0800854 return lhs < rhs && !ScoredFrameRate::scoresEqual(lhs, rhs);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700855 });
856 ALOGV("%s: overriding to %s for uid=%d", __func__, to_string(overrideFps).c_str(), uid);
857 frameRateOverrides.emplace(uid, overrideFps);
Ady Abraham62a0be22020-12-08 16:54:10 -0800858 }
859
860 return frameRateOverrides;
861}
862
Ady Abraham0aa373a2022-11-22 13:56:50 -0800863ftl::Optional<FrameRateMode> RefreshRateSelector::onKernelTimerChanged(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800864 std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800865 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100866
Ady Abraham0aa373a2022-11-22 13:56:50 -0800867 const auto current = [&]() REQUIRES(mLock) -> FrameRateMode {
868 if (desiredActiveModeId) {
869 const auto& modePtr = mDisplayModes.get(*desiredActiveModeId)->get();
870 return FrameRateMode{modePtr->getFps(), ftl::as_non_null(modePtr)};
871 }
872
873 return getActiveModeLocked();
874 }();
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100875
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800876 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
Ady Abraham0aa373a2022-11-22 13:56:50 -0800877 if (current.modePtr->getId() == min->getId()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800878 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100879 }
880
Ady Abraham0aa373a2022-11-22 13:56:50 -0800881 return timerExpired ? FrameRateMode{min->getFps(), ftl::as_non_null(min)} : current;
Steven Thomasf734df42020-04-13 21:09:28 -0700882}
883
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400884const DisplayModePtr& RefreshRateSelector::getMinRefreshRateByPolicyLocked() const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800885 const auto& activeMode = *getActiveModeLocked().modePtr;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700886
Ady Abraham68636062022-11-16 17:07:25 -0800887 for (const FrameRateMode& mode : mPrimaryFrameRates) {
888 if (activeMode.getGroup() == mode.modePtr->getGroup()) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800889 return mode.modePtr.get();
Marin Shalamanov46084422020-10-13 12:33:42 +0200890 }
891 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800892
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700893 ALOGE("Can't find min refresh rate by policy with the same mode group as the current mode %s",
894 to_string(activeMode).c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800895
896 // Default to the lowest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -0800897 return mPrimaryFrameRates.front().modePtr.get();
Ady Abraham2139f732019-11-13 18:56:40 -0800898}
899
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400900const DisplayModePtr& RefreshRateSelector::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800901 const ftl::NonNull<DisplayModePtr>* maxByAnchor = &mPrimaryFrameRates.back().modePtr;
902 const ftl::NonNull<DisplayModePtr>* max = &mPrimaryFrameRates.back().modePtr;
Ady Abraham68636062022-11-16 17:07:25 -0800903
904 bool maxByAnchorFound = false;
905 for (auto it = mPrimaryFrameRates.rbegin(); it != mPrimaryFrameRates.rend(); ++it) {
906 using namespace fps_approx_ops;
907 if (it->modePtr->getFps() > (*max)->getFps()) {
908 max = &it->modePtr;
Marin Shalamanov46084422020-10-13 12:33:42 +0200909 }
Ady Abraham68636062022-11-16 17:07:25 -0800910
911 if (anchorGroup == it->modePtr->getGroup() &&
912 it->modePtr->getFps() >= (*maxByAnchor)->getFps()) {
913 maxByAnchorFound = true;
914 maxByAnchor = &it->modePtr;
915 }
916 }
917
918 if (maxByAnchorFound) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800919 return maxByAnchor->get();
Marin Shalamanov46084422020-10-13 12:33:42 +0200920 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800921
ramindanid72ba162022-09-09 21:33:40 +0000922 ALOGE("Can't find max refresh rate by policy with the same group %d", anchorGroup);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800923
924 // Default to the highest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -0800925 return max->get();
Ady Abraham2139f732019-11-13 18:56:40 -0800926}
927
Ady Abraham68636062022-11-16 17:07:25 -0800928auto RefreshRateSelector::rankFrameRates(std::optional<int> anchorGroupOpt,
929 RefreshRateOrder refreshRateOrder,
930 std::optional<DisplayModeId> preferredDisplayModeOpt) const
931 -> FrameRateRanking {
932 const char* const whence = __func__;
933 std::deque<ScoredFrameRate> ranking;
934 const auto rankFrameRate = [&](const FrameRateMode& frameRateMode) REQUIRES(mLock) {
Ady Abraham3f965922023-01-23 17:18:29 -0800935 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -0800936 const auto& modePtr = frameRateMode.modePtr;
937 if (anchorGroupOpt && modePtr->getGroup() != anchorGroupOpt) {
Ady Abraham37d46922022-10-05 13:08:51 -0700938 return;
ramindanid72ba162022-09-09 21:33:40 +0000939 }
Ady Abraham37d46922022-10-05 13:08:51 -0700940
Ady Abraham3f965922023-01-23 17:18:29 -0800941 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
942 if (ascending && frameRateMode.fps < getMinRefreshRateByPolicyLocked()->getFps()) {
943 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
944 // use a lower frame rate when we want Ascending frame rates.
945 return;
946 }
947
Ady Abraham68636062022-11-16 17:07:25 -0800948 float score = calculateDistanceScoreFromMax(frameRateMode.fps);
Ady Abraham3f965922023-01-23 17:18:29 -0800949
950 if (ascending) {
Ady Abraham37d46922022-10-05 13:08:51 -0700951 score = 1.0f / score;
952 }
953 if (preferredDisplayModeOpt) {
Ady Abraham68636062022-11-16 17:07:25 -0800954 if (*preferredDisplayModeOpt == modePtr->getId()) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400955 constexpr float kScore = std::numeric_limits<float>::max();
Ady Abraham68636062022-11-16 17:07:25 -0800956 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
Ady Abraham37d46922022-10-05 13:08:51 -0700957 return;
958 }
959 constexpr float kNonPreferredModePenalty = 0.95f;
960 score *= kNonPreferredModePenalty;
961 }
Ady Abraham3f965922023-01-23 17:18:29 -0800962
Ady Abraham68636062022-11-16 17:07:25 -0800963 ALOGV("%s(%s) %s (%s) scored %.2f", whence, ftl::enum_string(refreshRateOrder).c_str(),
964 to_string(frameRateMode.fps).c_str(), to_string(modePtr->getFps()).c_str(), score);
965 ranking.emplace_back(ScoredFrameRate{frameRateMode, score});
ramindanid72ba162022-09-09 21:33:40 +0000966 };
967
968 if (refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abraham68636062022-11-16 17:07:25 -0800969 std::for_each(mPrimaryFrameRates.begin(), mPrimaryFrameRates.end(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +0000970 } else {
Ady Abraham68636062022-11-16 17:07:25 -0800971 std::for_each(mPrimaryFrameRates.rbegin(), mPrimaryFrameRates.rend(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +0000972 }
973
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400974 if (!ranking.empty() || !anchorGroupOpt) {
975 return {ranking.begin(), ranking.end()};
ramindanid72ba162022-09-09 21:33:40 +0000976 }
977
978 ALOGW("Can't find %s refresh rate by policy with the same mode group"
979 " as the mode group %d",
980 refreshRateOrder == RefreshRateOrder::Ascending ? "min" : "max", anchorGroupOpt.value());
981
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400982 constexpr std::optional<int> kNoAnchorGroup = std::nullopt;
Ady Abraham68636062022-11-16 17:07:25 -0800983 return rankFrameRates(kNoAnchorGroup, refreshRateOrder, preferredDisplayModeOpt);
ramindanid72ba162022-09-09 21:33:40 +0000984}
985
Ady Abrahamace3d052022-11-17 16:25:05 -0800986FrameRateMode RefreshRateSelector::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800987 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -0800988 return getActiveModeLocked();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700989}
990
Ady Abrahamace3d052022-11-17 16:25:05 -0800991const FrameRateMode& RefreshRateSelector::getActiveModeLocked() const {
992 return *mActiveModeOpt;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700993}
994
Ady Abrahamace3d052022-11-17 16:25:05 -0800995void RefreshRateSelector::setActiveMode(DisplayModeId modeId, Fps renderFrameRate) {
Ady Abraham2139f732019-11-13 18:56:40 -0800996 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200997
Ady Abraham68636062022-11-16 17:07:25 -0800998 // Invalidate the cached invocation to getRankedFrameRates. This forces
999 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1000 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001001
Ady Abrahamace3d052022-11-17 16:25:05 -08001002 const auto activeModeOpt = mDisplayModes.get(modeId);
1003 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1004
1005 mActiveModeOpt.emplace(FrameRateMode{renderFrameRate, ftl::as_non_null(activeModeOpt->get())});
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001006}
1007
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001008RefreshRateSelector::RefreshRateSelector(DisplayModes modes, DisplayModeId activeModeId,
1009 Config config)
rnlee3bd610662021-06-23 16:27:57 -07001010 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001011 initializeIdleTimer();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001012 FTL_FAKE_GUARD(kMainThreadContext, updateDisplayModes(std::move(modes), activeModeId));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001013}
1014
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001015void RefreshRateSelector::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +00001016 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001017 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +00001018 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001019 [this] {
1020 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1021 if (const auto callbacks = getIdleTimerCallbacks()) {
1022 callbacks->onReset();
1023 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001024 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001025 [this] {
1026 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1027 if (const auto callbacks = getIdleTimerCallbacks()) {
1028 callbacks->onExpired();
1029 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001030 });
Ady Abraham9a2ea342021-09-03 17:32:34 -07001031 }
1032}
1033
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001034void RefreshRateSelector::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001035 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001036
Ady Abraham68636062022-11-16 17:07:25 -08001037 // Invalidate the cached invocation to getRankedFrameRates. This forces
1038 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1039 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001040
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001041 mDisplayModes = std::move(modes);
Ady Abrahamace3d052022-11-17 16:25:05 -08001042 const auto activeModeOpt = mDisplayModes.get(activeModeId);
1043 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1044 mActiveModeOpt =
1045 FrameRateMode{activeModeOpt->get()->getFps(), ftl::as_non_null(activeModeOpt->get())};
Ady Abrahamabc27602020-04-08 17:20:29 -07001046
Ady Abraham68636062022-11-16 17:07:25 -08001047 const auto sortedModes = sortByRefreshRate(mDisplayModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001048 mMinRefreshRateModeIt = sortedModes.front();
1049 mMaxRefreshRateModeIt = sortedModes.back();
1050
Marin Shalamanov75f37252021-02-10 21:43:57 +01001051 // Reset the policy because the old one may no longer be valid.
1052 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001053 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -08001054
Ady Abraham8ca643a2022-10-18 18:26:47 -07001055 mFrameRateOverrideConfig = [&] {
1056 switch (mConfig.enableFrameRateOverride) {
1057 case Config::FrameRateOverride::Disabled:
Ady Abraham68636062022-11-16 17:07:25 -08001058 case Config::FrameRateOverride::AppOverride:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001059 case Config::FrameRateOverride::Enabled:
1060 return mConfig.enableFrameRateOverride;
Ady Abraham68636062022-11-16 17:07:25 -08001061 case Config::FrameRateOverride::AppOverrideNativeRefreshRates:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001062 return shouldEnableFrameRateOverride(sortedModes)
Ady Abraham68636062022-11-16 17:07:25 -08001063 ? Config::FrameRateOverride::AppOverrideNativeRefreshRates
Ady Abraham8ca643a2022-10-18 18:26:47 -07001064 : Config::FrameRateOverride::Disabled;
1065 }
1066 }();
Ady Abraham4899ff82021-01-06 13:53:29 -08001067
Ady Abraham68636062022-11-16 17:07:25 -08001068 if (mConfig.enableFrameRateOverride ==
1069 Config::FrameRateOverride::AppOverrideNativeRefreshRates) {
1070 for (const auto& [_, mode] : mDisplayModes) {
1071 mAppOverrideNativeRefreshRates.try_emplace(mode->getFps(), ftl::unit);
1072 }
1073 }
1074
Ady Abrahamabc27602020-04-08 17:20:29 -07001075 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001076}
1077
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001078bool RefreshRateSelector::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001079 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001080 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
Ady Abraham285f8c12022-10-11 17:12:14 -07001081 if (!policy.primaryRanges.physical.includes(mode->get()->getFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001082 ALOGE("Default mode is not in the primary range.");
1083 return false;
1084 }
1085 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001086 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -07001087 return false;
1088 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001089
Ady Abraham68636062022-11-16 17:07:25 -08001090 const auto& primaryRanges = policy.primaryRanges;
1091 const auto& appRequestRanges = policy.appRequestRanges;
1092 ALOGE_IF(!appRequestRanges.physical.includes(primaryRanges.physical),
Ady Abraham08048ce2022-11-30 18:08:00 -08001093 "Physical range is invalid: primary: %s appRequest: %s",
1094 to_string(primaryRanges.physical).c_str(),
1095 to_string(appRequestRanges.physical).c_str());
1096 ALOGE_IF(!appRequestRanges.render.includes(primaryRanges.render),
1097 "Render range is invalid: primary: %s appRequest: %s",
1098 to_string(primaryRanges.render).c_str(), to_string(appRequestRanges.render).c_str());
Ady Abraham68636062022-11-16 17:07:25 -08001099
1100 return primaryRanges.valid() && appRequestRanges.valid();
Steven Thomasd4071902020-03-24 16:02:53 -07001101}
1102
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001103auto RefreshRateSelector::setPolicy(const PolicyVariant& policy) -> SetPolicyResult {
Dominik Laskowski36dced82022-09-02 09:24:00 -07001104 Policy oldPolicy;
Ady Abrahamace3d052022-11-17 16:25:05 -08001105 PhysicalDisplayId displayId;
Dominik Laskowski36dced82022-09-02 09:24:00 -07001106 {
1107 std::lock_guard lock(mLock);
1108 oldPolicy = *getCurrentPolicyLocked();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001109
Dominik Laskowski36dced82022-09-02 09:24:00 -07001110 const bool valid = ftl::match(
1111 policy,
1112 [this](const auto& policy) {
1113 ftl::FakeGuard guard(mLock);
1114 if (!isPolicyValidLocked(policy)) {
1115 ALOGE("Invalid policy: %s", policy.toString().c_str());
1116 return false;
1117 }
1118
1119 using T = std::decay_t<decltype(policy)>;
1120
1121 if constexpr (std::is_same_v<T, DisplayManagerPolicy>) {
1122 mDisplayManagerPolicy = policy;
1123 } else {
1124 static_assert(std::is_same_v<T, OverridePolicy>);
1125 mOverridePolicy = policy;
1126 }
1127 return true;
1128 },
1129 [this](NoOverridePolicy) {
1130 ftl::FakeGuard guard(mLock);
1131 mOverridePolicy.reset();
1132 return true;
1133 });
1134
1135 if (!valid) {
1136 return SetPolicyResult::Invalid;
1137 }
1138
Ady Abraham68636062022-11-16 17:07:25 -08001139 mGetRankedFrameRatesCache.reset();
Dominik Laskowski36dced82022-09-02 09:24:00 -07001140
1141 if (*getCurrentPolicyLocked() == oldPolicy) {
1142 return SetPolicyResult::Unchanged;
1143 }
1144 constructAvailableRefreshRates();
Ady Abrahamace3d052022-11-17 16:25:05 -08001145
1146 displayId = getActiveModeLocked().modePtr->getPhysicalDisplayId();
Steven Thomasd4071902020-03-24 16:02:53 -07001147 }
Dominik Laskowski36dced82022-09-02 09:24:00 -07001148
Dominik Laskowski36dced82022-09-02 09:24:00 -07001149 const unsigned numModeChanges = std::exchange(mNumModeSwitchesInPolicy, 0u);
1150
1151 ALOGI("Display %s policy changed\n"
1152 "Previous: %s\n"
1153 "Current: %s\n"
1154 "%u mode changes were performed under the previous policy",
1155 to_string(displayId).c_str(), oldPolicy.toString().c_str(), toString(policy).c_str(),
1156 numModeChanges);
1157
1158 return SetPolicyResult::Changed;
Steven Thomasd4071902020-03-24 16:02:53 -07001159}
1160
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001161auto RefreshRateSelector::getCurrentPolicyLocked() const -> const Policy* {
Steven Thomasd4071902020-03-24 16:02:53 -07001162 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
1163}
1164
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001165auto RefreshRateSelector::getCurrentPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001166 std::lock_guard lock(mLock);
1167 return *getCurrentPolicyLocked();
1168}
1169
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001170auto RefreshRateSelector::getDisplayManagerPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001171 std::lock_guard lock(mLock);
1172 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001173}
1174
Ady Abrahamace3d052022-11-17 16:25:05 -08001175bool RefreshRateSelector::isModeAllowed(const FrameRateMode& mode) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001176 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001177 return std::find(mAppRequestFrameRates.begin(), mAppRequestFrameRates.end(), mode) !=
1178 mAppRequestFrameRates.end();
Ady Abraham2139f732019-11-13 18:56:40 -08001179}
1180
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001181void RefreshRateSelector::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001182 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -07001183 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001184 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -07001185
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001186 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -08001187
Ady Abraham68636062022-11-16 17:07:25 -08001188 const auto filterRefreshRates = [&](const FpsRanges& ranges,
1189 const char* rangeName) REQUIRES(mLock) {
1190 const auto filterModes = [&](const DisplayMode& mode) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001191 return mode.getResolution() == defaultMode->getResolution() &&
1192 mode.getDpi() == defaultMode->getDpi() &&
1193 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
Ady Abraham68636062022-11-16 17:07:25 -08001194 ranges.physical.includes(mode.getFps()) &&
1195 (supportsFrameRateOverride() || ranges.render.includes(mode.getFps()));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001196 };
Ady Abraham8a82ba62020-01-17 12:43:17 -08001197
Ady Abraham68636062022-11-16 17:07:25 -08001198 const auto frameRateModes = createFrameRateModes(filterModes, ranges.render);
1199 LOG_ALWAYS_FATAL_IF(frameRateModes.empty(),
Ady Abraham08048ce2022-11-30 18:08:00 -08001200 "No matching frame rate modes for %s range. policy: %s", rangeName,
1201 policy->toString().c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -08001202
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001203 const auto stringifyModes = [&] {
1204 std::string str;
Ady Abraham68636062022-11-16 17:07:25 -08001205 for (const auto& frameRateMode : frameRateModes) {
1206 str += to_string(frameRateMode) + " ";
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001207 }
1208 return str;
1209 };
Ady Abraham68636062022-11-16 17:07:25 -08001210 ALOGV("%s render rates: %s", rangeName, stringifyModes().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -07001211
Ady Abraham68636062022-11-16 17:07:25 -08001212 return frameRateModes;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001213 };
1214
Ady Abraham68636062022-11-16 17:07:25 -08001215 mPrimaryFrameRates = filterRefreshRates(policy->primaryRanges, "primary");
1216 mAppRequestFrameRates = filterRefreshRates(policy->appRequestRanges, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -08001217}
1218
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001219Fps RefreshRateSelector::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001220 using namespace fps_approx_ops;
1221
1222 if (frameRate <= mKnownFrameRates.front()) {
1223 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001224 }
1225
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001226 if (frameRate >= mKnownFrameRates.back()) {
1227 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001228 }
1229
Marin Shalamanove8a663d2020-11-24 17:48:00 +01001230 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001231 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001232
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001233 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
1234 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001235 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
1236}
1237
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001238auto RefreshRateSelector::getIdleTimerAction() const -> KernelIdleTimerAction {
Ana Krulecb9afd792020-06-11 13:16:15 -07001239 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001240
1241 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getFps();
1242 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -07001243
1244 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
1245 // the min allowed refresh rate is higher than the device min, we do not want to enable the
1246 // timer.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001247 if (isStrictlyLess(deviceMinFps, minByPolicy->getFps())) {
1248 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001249 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001250
ramindanid72ba162022-09-09 21:33:40 +00001251 const DisplayModePtr& maxByPolicy =
Ady Abrahamace3d052022-11-17 16:25:05 -08001252 getMaxRefreshRateByPolicyLocked(getActiveModeLocked().modePtr->getGroup());
Ana Krulecb9afd792020-06-11 13:16:15 -07001253 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001254 // Turn on the timer when the min of the primary range is below the device min.
1255 if (const Policy* currentPolicy = getCurrentPolicyLocked();
Ady Abraham285f8c12022-10-11 17:12:14 -07001256 isApproxLess(currentPolicy->primaryRanges.physical.min, deviceMinFps)) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001257 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001258 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001259 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001260 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001261
Ana Krulecb9afd792020-06-11 13:16:15 -07001262 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001263 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001264}
1265
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001266int RefreshRateSelector::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -07001267 // This calculation needs to be in sync with the java code
1268 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001269
1270 // The threshold must be smaller than 0.001 in order to differentiate
1271 // between the fractional pairs (e.g. 59.94 and 60).
1272 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001273 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -07001274 const auto numPeriodsRounded = std::round(numPeriods);
1275 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001276 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -07001277 }
1278
Ady Abraham62f216c2020-10-13 19:07:23 -07001279 return static_cast<int>(numPeriodsRounded);
1280}
1281
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001282bool RefreshRateSelector::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001283 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001284 return isFractionalPairOrMultiple(bigger, smaller);
1285 }
1286
1287 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
1288 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001289 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
1290 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001291}
1292
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001293void RefreshRateSelector::dump(utils::Dumper& dumper) const {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001294 using namespace std::string_view_literals;
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001295
Marin Shalamanovba421a82020-11-10 21:49:26 +01001296 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +01001297
Ady Abrahamace3d052022-11-17 16:25:05 -08001298 const auto activeMode = getActiveModeLocked();
1299 dumper.dump("activeMode"sv, to_string(activeMode));
Marin Shalamanovba421a82020-11-10 21:49:26 +01001300
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001301 dumper.dump("displayModes"sv);
1302 {
1303 utils::Dumper::Indent indent(dumper);
1304 for (const auto& [id, mode] : mDisplayModes) {
1305 dumper.dump({}, to_string(*mode));
1306 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001307 }
1308
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001309 dumper.dump("displayManagerPolicy"sv, mDisplayManagerPolicy.toString());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001310
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001311 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
1312 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001313 dumper.dump("overridePolicy"sv, currentPolicy.toString());
ramindani32cf0602022-03-02 02:30:29 +00001314 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001315
Ady Abraham8ca643a2022-10-18 18:26:47 -07001316 dumper.dump("frameRateOverrideConfig"sv, *ftl::enum_name(mFrameRateOverrideConfig));
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001317
Dominik Laskowski03cfce82022-11-02 12:13:29 -04001318 dumper.dump("idleTimer"sv);
1319 {
1320 utils::Dumper::Indent indent(dumper);
1321 dumper.dump("interval"sv, mIdleTimer.transform(&OneShotTimer::interval));
1322 dumper.dump("controller"sv,
1323 mConfig.kernelIdleTimerController
1324 .and_then(&ftl::enum_name<KernelIdleTimerController>)
1325 .value_or("Platform"sv));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001326 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001327}
1328
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001329std::chrono::milliseconds RefreshRateSelector::getIdleTimerTimeout() {
ramindani32cf0602022-03-02 02:30:29 +00001330 return mConfig.idleTimerTimeout;
1331}
1332
Ady Abraham2139f732019-11-13 18:56:40 -08001333} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001334
1335// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001336#pragma clang diagnostic pop // ignored "-Wextra"