blob: 47c8ef9f16c3594887c7fe3197720fde3c2ff083 [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
ramindania04b8a52023-08-07 18:49:47 -070042#include <com_android_graphics_surfaceflinger_flags.h>
43
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080044#undef LOG_TAG
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040045#define LOG_TAG "RefreshRateSelector"
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080046
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080047namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010048namespace {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070049
ramindania04b8a52023-08-07 18:49:47 -070050using namespace com::android::graphics::surfaceflinger;
51
Dominik Laskowskib0054a22022-03-03 09:03:06 -080052struct RefreshRateScore {
Ady Abraham68636062022-11-16 17:07:25 -080053 FrameRateMode frameRateMode;
Ady Abrahamae2e3c72022-08-13 05:12:13 +000054 float overallScore;
55 struct {
Ady Abraham62f51d92022-08-24 22:20:22 +000056 float modeBelowThreshold;
57 float modeAboveThreshold;
58 } fixedRateBelowThresholdLayersScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -080059};
60
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040061constexpr RefreshRateSelector::GlobalSignals kNoSignals;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080062
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040063std::string formatLayerInfo(const RefreshRateSelector::LayerRequirement& layer, float weight) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080064 return base::StringPrintf("%s (type=%s, weight=%.2f, seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070065 ftl::enum_string(layer.vote).c_str(), weight,
66 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010067 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010068}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010069
Marin Shalamanova7fe3042021-01-29 21:02:08 +010070std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070071 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010072 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010073
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070074 // Add all supported refresh rates.
Dominik Laskowskib0054a22022-03-03 09:03:06 -080075 for (const auto& [id, mode] : modes) {
ramindania04b8a52023-08-07 18:49:47 -070076 knownFrameRates.push_back(mode->getPeakFps());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010077 }
78
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070079 // Sort and remove duplicates.
80 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010081 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070082 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010083 knownFrameRates.end());
84 return knownFrameRates;
85}
86
Ady Abraham68636062022-11-16 17:07:25 -080087std::vector<DisplayModeIterator> sortByRefreshRate(const DisplayModes& modes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080088 std::vector<DisplayModeIterator> sortedModes;
89 sortedModes.reserve(modes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -080090 for (auto it = modes.begin(); it != modes.end(); ++it) {
Ady Abraham68636062022-11-16 17:07:25 -080091 sortedModes.push_back(it);
Dominik Laskowskib0054a22022-03-03 09:03:06 -080092 }
93
94 std::sort(sortedModes.begin(), sortedModes.end(), [](auto it1, auto it2) {
95 const auto& mode1 = it1->second;
96 const auto& mode2 = it2->second;
97
ramindania04b8a52023-08-07 18:49:47 -070098 if (mode1->getVsyncRate().getPeriodNsecs() == mode2->getVsyncRate().getPeriodNsecs()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080099 return mode1->getGroup() > mode2->getGroup();
100 }
101
ramindania04b8a52023-08-07 18:49:47 -0700102 return mode1->getVsyncRate().getPeriodNsecs() > mode2->getVsyncRate().getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800103 });
104
105 return sortedModes;
Marin Shalamanov46084422020-10-13 12:33:42 +0200106}
107
ramindania04b8a52023-08-07 18:49:47 -0700108std::pair<unsigned, unsigned> divisorRange(Fps vsyncRate, Fps peakFps, FpsRange range,
Ady Abraham68636062022-11-16 17:07:25 -0800109 RefreshRateSelector::Config::FrameRateOverride config) {
110 if (config != RefreshRateSelector::Config::FrameRateOverride::Enabled) {
111 return {1, 1};
112 }
113
114 using fps_approx_ops::operator/;
Ady Abraham08048ce2022-11-30 18:08:00 -0800115 // use signed type as `fps / range.max` might be 0
ramindania04b8a52023-08-07 18:49:47 -0700116 auto start = std::max(1, static_cast<int>(peakFps / range.max) - 1);
Ady Abrahamd6d80162023-10-23 12:57:41 -0700117 if (FlagManager::getInstance().vrr_config()) {
ramindania04b8a52023-08-07 18:49:47 -0700118 start = std::max(1,
119 static_cast<int>(vsyncRate /
120 std::min(range.max, peakFps, fps_approx_ops::operator<)) -
121 1);
122 }
123 const auto end = vsyncRate /
Ady Abraham68636062022-11-16 17:07:25 -0800124 std::max(range.min, RefreshRateSelector::kMinSupportedFrameRate,
125 fps_approx_ops::operator<);
126
127 return {start, end};
128}
129
Ady Abraham8ca643a2022-10-18 18:26:47 -0700130bool shouldEnableFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800131 for (const auto it1 : sortedModes) {
132 const auto& mode1 = it1->second;
133 for (const auto it2 : sortedModes) {
134 const auto& mode2 = it2->second;
135
ramindania04b8a52023-08-07 18:49:47 -0700136 if (RefreshRateSelector::getFrameRateDivisor(mode1->getPeakFps(),
137 mode2->getPeakFps()) >= 2) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800138 return true;
139 }
140 }
141 }
142 return false;
143}
144
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400145std::string toString(const RefreshRateSelector::PolicyVariant& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700146 using namespace std::string_literals;
147
148 return ftl::match(
149 policy,
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400150 [](const RefreshRateSelector::DisplayManagerPolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700151 return "DisplayManagerPolicy"s + policy.toString();
152 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400153 [](const RefreshRateSelector::OverridePolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700154 return "OverridePolicy"s + policy.toString();
155 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400156 [](RefreshRateSelector::NoOverridePolicy) { return "NoOverridePolicy"s; });
Dominik Laskowski36dced82022-09-02 09:24:00 -0700157}
158
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800159} // namespace
160
Ady Abraham68636062022-11-16 17:07:25 -0800161auto RefreshRateSelector::createFrameRateModes(
Ady Abraham90f7fd22023-08-16 11:02:00 -0700162 const Policy& policy, std::function<bool(const DisplayMode&)>&& filterModes,
163 const FpsRange& renderRange) const -> std::vector<FrameRateMode> {
Ady Abraham68636062022-11-16 17:07:25 -0800164 struct Key {
165 Fps fps;
166 int32_t group;
167 };
168
169 struct KeyLess {
170 bool operator()(const Key& a, const Key& b) const {
171 using namespace fps_approx_ops;
172 if (a.fps != b.fps) {
173 return a.fps < b.fps;
174 }
175
176 // For the same fps the order doesn't really matter, but we still
177 // want the behaviour of a strictly less operator.
178 // We use the group id as the secondary ordering for that.
179 return a.group < b.group;
180 }
181 };
182
183 std::map<Key, DisplayModeIterator, KeyLess> ratesMap;
184 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
185 const auto& [id, mode] = *it;
186
187 if (!filterModes(*mode)) {
188 continue;
189 }
ramindania04b8a52023-08-07 18:49:47 -0700190 const auto vsyncRate = mode->getVsyncRate();
191 const auto peakFps = mode->getPeakFps();
Ady Abraham68636062022-11-16 17:07:25 -0800192 const auto [start, end] =
ramindania04b8a52023-08-07 18:49:47 -0700193 divisorRange(vsyncRate, peakFps, renderRange, mConfig.enableFrameRateOverride);
Ady Abraham68636062022-11-16 17:07:25 -0800194 for (auto divisor = start; divisor <= end; divisor++) {
ramindania04b8a52023-08-07 18:49:47 -0700195 const auto fps = vsyncRate / divisor;
Ady Abraham68636062022-11-16 17:07:25 -0800196 using fps_approx_ops::operator<;
Ady Abrahamdc0b3a72023-01-04 16:58:27 -0800197 if (divisor > 1 && fps < kMinSupportedFrameRate) {
Ady Abraham68636062022-11-16 17:07:25 -0800198 break;
199 }
200
201 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Enabled &&
202 !renderRange.includes(fps)) {
203 continue;
204 }
205
206 if (mConfig.enableFrameRateOverride ==
207 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
208 !isNativeRefreshRate(fps)) {
209 continue;
210 }
211
212 const auto [existingIter, emplaceHappened] =
213 ratesMap.try_emplace(Key{fps, mode->getGroup()}, it);
214 if (emplaceHappened) {
ramindania04b8a52023-08-07 18:49:47 -0700215 ALOGV("%s: including %s (%s(%s))", __func__, to_string(fps).c_str(),
216 to_string(peakFps).c_str(), to_string(vsyncRate).c_str());
Ady Abraham68636062022-11-16 17:07:25 -0800217 } else {
Ady Abraham90f7fd22023-08-16 11:02:00 -0700218 // If the primary physical range is a single rate, prefer to stay in that rate
219 // even if there is a lower physical refresh rate available. This would cause more
220 // cases to stay within the primary physical range
ramindania04b8a52023-08-07 18:49:47 -0700221 const Fps existingModeFps = existingIter->second->second->getPeakFps();
Ady Abraham90f7fd22023-08-16 11:02:00 -0700222 const bool existingModeIsPrimaryRange = policy.primaryRangeIsSingleRate() &&
223 policy.primaryRanges.physical.includes(existingModeFps);
224 const bool newModeIsPrimaryRange = policy.primaryRangeIsSingleRate() &&
ramindania04b8a52023-08-07 18:49:47 -0700225 policy.primaryRanges.physical.includes(mode->getPeakFps());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700226 if (newModeIsPrimaryRange == existingModeIsPrimaryRange) {
227 // We might need to update the map as we found a lower refresh rate
ramindania04b8a52023-08-07 18:49:47 -0700228 if (isStrictlyLess(mode->getPeakFps(), existingModeFps)) {
Ady Abraham90f7fd22023-08-16 11:02:00 -0700229 existingIter->second = it;
ramindania04b8a52023-08-07 18:49:47 -0700230 ALOGV("%s: changing %s (%s(%s)) as we found a lower physical rate",
231 __func__, to_string(fps).c_str(), to_string(peakFps).c_str(),
232 to_string(vsyncRate).c_str());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700233 }
234 } else if (newModeIsPrimaryRange) {
Ady Abraham68636062022-11-16 17:07:25 -0800235 existingIter->second = it;
ramindania04b8a52023-08-07 18:49:47 -0700236 ALOGV("%s: changing %s (%s(%s)) to stay in the primary range", __func__,
237 to_string(fps).c_str(), to_string(peakFps).c_str(),
238 to_string(vsyncRate).c_str());
Ady Abraham68636062022-11-16 17:07:25 -0800239 }
240 }
241 }
242 }
243
244 std::vector<FrameRateMode> frameRateModes;
245 frameRateModes.reserve(ratesMap.size());
246 for (const auto& [key, mode] : ratesMap) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800247 frameRateModes.emplace_back(FrameRateMode{key.fps, ftl::as_non_null(mode->second)});
Ady Abraham68636062022-11-16 17:07:25 -0800248 }
249
250 // We always want that the lowest frame rate will be corresponding to the
251 // lowest mode for power saving.
252 const auto lowestRefreshRateIt =
253 std::min_element(frameRateModes.begin(), frameRateModes.end(),
254 [](const FrameRateMode& lhs, const FrameRateMode& rhs) {
ramindania04b8a52023-08-07 18:49:47 -0700255 return isStrictlyLess(lhs.modePtr->getVsyncRate(),
256 rhs.modePtr->getVsyncRate());
Ady Abraham68636062022-11-16 17:07:25 -0800257 });
258 frameRateModes.erase(frameRateModes.begin(), lowestRefreshRateIt);
259
260 return frameRateModes;
261}
262
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400263struct RefreshRateSelector::RefreshRateScoreComparator {
ramindanid72ba162022-09-09 21:33:40 +0000264 bool operator()(const RefreshRateScore& lhs, const RefreshRateScore& rhs) const {
Ady Abraham68636062022-11-16 17:07:25 -0800265 const auto& [frameRateMode, overallScore, _] = lhs;
ramindanid72ba162022-09-09 21:33:40 +0000266
Ady Abraham68636062022-11-16 17:07:25 -0800267 std::string name = to_string(frameRateMode);
268
ramindanid72ba162022-09-09 21:33:40 +0000269 ALOGV("%s sorting scores %.2f", name.c_str(), overallScore);
ramindanid72ba162022-09-09 21:33:40 +0000270
Ady Abraham68636062022-11-16 17:07:25 -0800271 if (!ScoredFrameRate::scoresEqual(overallScore, rhs.overallScore)) {
ramindanid72ba162022-09-09 21:33:40 +0000272 return overallScore > rhs.overallScore;
273 }
274
ramindanid72ba162022-09-09 21:33:40 +0000275 if (refreshRateOrder == RefreshRateOrder::Descending) {
276 using fps_approx_ops::operator>;
Ady Abraham68636062022-11-16 17:07:25 -0800277 return frameRateMode.fps > rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000278 } else {
279 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -0800280 return frameRateMode.fps < rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000281 }
282 }
283
284 const RefreshRateOrder refreshRateOrder;
285};
286
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400287std::string RefreshRateSelector::Policy::toString() const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700288 return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
Ady Abraham285f8c12022-10-11 17:12:14 -0700289 ", primaryRanges=%s, appRequestRanges=%s}",
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700290 defaultMode.value(), allowGroupSwitching ? "true" : "false",
Ady Abraham285f8c12022-10-11 17:12:14 -0700291 to_string(primaryRanges).c_str(),
292 to_string(appRequestRanges).c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200293}
294
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400295std::pair<nsecs_t, nsecs_t> RefreshRateSelector::getDisplayFrames(nsecs_t layerPeriod,
296 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800297 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
298 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
299 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
300 quotient++;
301 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800302 }
303
Ady Abraham62a0be22020-12-08 16:54:10 -0800304 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800305}
306
Rachel Leece6e0042023-06-27 11:22:54 -0700307float RefreshRateSelector::calculateNonExactMatchingDefaultLayerScoreLocked(
308 nsecs_t displayPeriod, nsecs_t layerPeriod) const {
309 // Find the actual rate the layer will render, assuming
310 // that layerPeriod is the minimal period to render a frame.
311 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
312 // then the actualLayerPeriod will be 32ms, because it is the
313 // smallest multiple of the display period which is >= layerPeriod.
314 auto actualLayerPeriod = displayPeriod;
315 int multiplier = 1;
316 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
317 multiplier++;
318 actualLayerPeriod = displayPeriod * multiplier;
319 }
320
321 // Because of the threshold we used above it's possible that score is slightly
322 // above 1.
323 return std::min(1.0f, static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
324}
325
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400326float RefreshRateSelector::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
327 Fps refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200328 constexpr float kScoreForFractionalPairs = .8f;
329
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800330 const auto displayPeriod = refreshRate.getPeriodNsecs();
Ady Abraham62a0be22020-12-08 16:54:10 -0800331 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
332 if (layer.vote == LayerVoteType::ExplicitDefault) {
Rachel Leece6e0042023-06-27 11:22:54 -0700333 return calculateNonExactMatchingDefaultLayerScoreLocked(displayPeriod, layerPeriod);
Ady Abraham62a0be22020-12-08 16:54:10 -0800334 }
335
336 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
337 layer.vote == LayerVoteType::Heuristic) {
Ady Abrahambd44e8a2023-07-24 11:30:06 -0700338 using fps_approx_ops::operator<;
339 if (refreshRate < 60_Hz) {
340 const bool favorsAtLeast60 =
341 std::find_if(mFrameRatesThatFavorsAtLeast60.begin(),
342 mFrameRatesThatFavorsAtLeast60.end(), [&](Fps fps) {
343 using fps_approx_ops::operator==;
344 return fps == layer.desiredRefreshRate;
345 }) != mFrameRatesThatFavorsAtLeast60.end();
346 if (favorsAtLeast60) {
347 return 0;
348 }
349 }
350
Ady Abraham68636062022-11-16 17:07:25 -0800351 const float multiplier = refreshRate.getValue() / layer.desiredRefreshRate.getValue();
352
353 // We only want to score this layer as a fractional pair if the content is not
354 // significantly faster than the display rate, at it would cause a significant frame drop.
355 // It is more appropriate to choose a higher display rate even if
356 // a pull-down will be required.
Rachel Lee36426fa2023-03-08 20:13:52 -0800357 constexpr float kMinMultiplier = 0.75f;
Ady Abraham68636062022-11-16 17:07:25 -0800358 if (multiplier >= kMinMultiplier &&
359 isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700360 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200361 }
362
Ady Abraham62a0be22020-12-08 16:54:10 -0800363 // Calculate how many display vsyncs we need to present a single frame for this
364 // layer
365 const auto [displayFramesQuotient, displayFramesRemainder] =
366 getDisplayFrames(layerPeriod, displayPeriod);
367 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
368 if (displayFramesRemainder == 0) {
369 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700370 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800371 }
372
373 if (displayFramesQuotient == 0) {
374 // Layer desired refresh rate is higher than the display rate.
375 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
376 (1.0f / (MAX_FRAMES_TO_FIT + 1));
377 }
378
379 // Layer desired refresh rate is lower than the display rate. Check how well it fits
380 // the cadence.
381 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
382 int iter = 2;
383 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
384 diff = diff - (displayPeriod - diff);
385 iter++;
386 }
387
Ady Abraham05243be2021-09-16 15:58:52 -0700388 return (1.0f / iter);
389 }
390
391 return 0;
392}
393
Ady Abraham68636062022-11-16 17:07:25 -0800394float RefreshRateSelector::calculateDistanceScoreFromMax(Fps refreshRate) const {
395 const auto& maxFps = mAppRequestFrameRates.back().fps;
396 const float ratio = refreshRate.getValue() / maxFps.getValue();
ramindanid72ba162022-09-09 21:33:40 +0000397 // Use ratio^2 to get a lower score the more we get further from peak
398 return ratio * ratio;
399}
400
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400401float RefreshRateSelector::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
402 bool isSeamlessSwitch) const {
Ady Abraham05243be2021-09-16 15:58:52 -0700403 // Slightly prefer seamless switches.
404 constexpr float kSeamedSwitchPenalty = 0.95f;
405 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
406
Rachel Leece6e0042023-06-27 11:22:54 -0700407 if (layer.vote == LayerVoteType::ExplicitCategory) {
408 if (getFrameRateCategoryRange(layer.frameRateCategory).includes(refreshRate)) {
409 return 1.f;
410 }
411
412 FpsRange categoryRange = getFrameRateCategoryRange(layer.frameRateCategory);
413 using fps_approx_ops::operator<;
414 if (refreshRate < categoryRange.min) {
415 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
416 categoryRange.min
417 .getPeriodNsecs());
418 }
419 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
420 categoryRange.max.getPeriodNsecs());
421 }
422
Ady Abraham05243be2021-09-16 15:58:52 -0700423 // If the layer wants Max, give higher score to the higher refresh rate
424 if (layer.vote == LayerVoteType::Max) {
Ady Abraham68636062022-11-16 17:07:25 -0800425 return calculateDistanceScoreFromMax(refreshRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800426 }
427
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800428 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800429 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Ady Abraham68636062022-11-16 17:07:25 -0800430 if (supportsAppFrameRateOverrideByContent()) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800431 // Since we support frame rate override, allow refresh rates which are
432 // multiples of the layer's request, as those apps would be throttled
433 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800434 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800435 }
436
Ady Abrahamcc315492022-02-17 17:06:39 -0800437 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800438 }
439
Ady Abrahamcc315492022-02-17 17:06:39 -0800440 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700441 // the highest score.
Rachel Leece6e0042023-06-27 11:22:54 -0700442 if (layer.desiredRefreshRate.isValid() &&
443 getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700444 return 1.0f * seamlessness;
445 }
446
Ady Abrahamcc315492022-02-17 17:06:39 -0800447 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700448 // there is a small penalty attached to the score to favor the frame rates
449 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800450 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700451 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
452 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800453}
454
Ady Abraham68636062022-11-16 17:07:25 -0800455auto RefreshRateSelector::getRankedFrameRates(const std::vector<LayerRequirement>& layers,
456 GlobalSignals signals) const -> RankedFrameRates {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200457 std::lock_guard lock(mLock);
458
Ady Abraham68636062022-11-16 17:07:25 -0800459 if (mGetRankedFrameRatesCache &&
460 mGetRankedFrameRatesCache->arguments == std::make_pair(layers, signals)) {
461 return mGetRankedFrameRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200462 }
463
Ady Abraham68636062022-11-16 17:07:25 -0800464 const auto result = getRankedFrameRatesLocked(layers, signals);
465 mGetRankedFrameRatesCache = GetRankedFrameRatesCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200466 return result;
467}
468
Ady Abraham68636062022-11-16 17:07:25 -0800469auto RefreshRateSelector::getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
470 GlobalSignals signals) const
471 -> RankedFrameRates {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000472 using namespace fps_approx_ops;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800473 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800474 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700475
Ady Abrahamace3d052022-11-17 16:25:05 -0800476 const auto& activeMode = *getActiveModeLocked().modePtr;
ramindani38c84982022-08-29 18:02:57 +0000477
Ady Abraham68636062022-11-16 17:07:25 -0800478 // Keep the display at max frame rate for the duration of powering on the display.
ramindani38c84982022-08-29 18:02:57 +0000479 if (signals.powerOnImminent) {
480 ALOGV("Power On Imminent");
Ady Abrahamccf63862023-01-19 11:44:01 -0800481 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Descending);
482 ATRACE_FORMAT_INSTANT("%s (Power On Imminent)",
483 to_string(ranking.front().frameRateMode.fps).c_str());
484 return {ranking, GlobalSignals{.powerOnImminent = true}};
ramindani38c84982022-08-29 18:02:57 +0000485 }
486
Ady Abraham8a82ba62020-01-17 12:43:17 -0800487 int noVoteLayers = 0;
488 int minVoteLayers = 0;
489 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800490 int explicitDefaultVoteLayers = 0;
491 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800492 int explicitExact = 0;
Rachel Leece6e0042023-06-27 11:22:54 -0700493 int explicitCategoryVoteLayers = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100494 int seamedFocusedLayers = 0;
Rachel Lee67afbea2023-09-28 15:35:07 -0700495 int categorySmoothSwitchOnlyLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800496
Ady Abraham8a82ba62020-01-17 12:43:17 -0800497 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800498 switch (layer.vote) {
499 case LayerVoteType::NoVote:
500 noVoteLayers++;
501 break;
502 case LayerVoteType::Min:
503 minVoteLayers++;
504 break;
505 case LayerVoteType::Max:
506 maxVoteLayers++;
507 break;
508 case LayerVoteType::ExplicitDefault:
509 explicitDefaultVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800510 break;
511 case LayerVoteType::ExplicitExactOrMultiple:
512 explicitExactOrMultipleVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800513 break;
514 case LayerVoteType::ExplicitExact:
515 explicitExact++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800516 break;
Rachel Leece6e0042023-06-27 11:22:54 -0700517 case LayerVoteType::ExplicitCategory:
518 explicitCategoryVoteLayers++;
Rachel Leef377b362023-09-06 15:01:06 -0700519 if (layer.frameRateCategory == FrameRateCategory::NoPreference) {
520 // Count this layer for Min vote as well. The explicit vote avoids
521 // touch boost and idle for choosing a category, while Min vote is for correct
522 // behavior when all layers are Min or no vote.
523 minVoteLayers++;
524 }
Rachel Leece6e0042023-06-27 11:22:54 -0700525 break;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800526 case LayerVoteType::Heuristic:
527 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800528 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200529
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100530 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
531 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200532 }
Rachel Lee67afbea2023-09-28 15:35:07 -0700533 if (layer.frameRateCategorySmoothSwitchOnly) {
534 categorySmoothSwitchOnlyLayers++;
535 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800536 }
537
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800538 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
Rachel Leece6e0042023-06-27 11:22:54 -0700539 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0 ||
540 explicitCategoryVoteLayers > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700541
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200542 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800543 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700544
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200545 // If the default mode group is different from the group of current mode,
546 // this means a layer requesting a seamed mode switch just disappeared and
547 // we should switch back to the default group.
548 // However if a seamed layer is still present we anchor around the group
549 // of the current mode, in order to prevent unnecessary seamed mode switches
550 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800551 const auto anchorGroup =
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700552 seamedFocusedLayers > 0 ? activeMode.getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200553
Steven Thomasf734df42020-04-13 21:09:28 -0700554 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
555 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800556 if (signals.touch && !hasExplicitVoteLayers) {
ramindanid72ba162022-09-09 21:33:40 +0000557 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800558 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
559 ATRACE_FORMAT_INSTANT("%s (Touch Boost)",
560 to_string(ranking.front().frameRateMode.fps).c_str());
561 return {ranking, GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800562 }
563
Alec Mouri11232a22020-05-14 18:06:25 -0700564 // If the primary range consists of a single refresh rate then we can only
565 // move out the of range if layers explicitly request a different refresh
566 // rate.
Ady Abraham90f7fd22023-08-16 11:02:00 -0700567 if (!signals.touch && signals.idle &&
568 !(policy->primaryRangeIsSingleRate() && hasExplicitVoteLayers)) {
ramindanid72ba162022-09-09 21:33:40 +0000569 ALOGV("Idle");
Ady Abrahamccf63862023-01-19 11:44:01 -0800570 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending);
571 ATRACE_FORMAT_INSTANT("%s (Idle)", to_string(ranking.front().frameRateMode.fps).c_str());
572 return {ranking, GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700573 }
574
Steven Thomasdebafed2020-05-18 17:30:35 -0700575 if (layers.empty() || noVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000576 ALOGV("No layers with votes");
Ady Abrahamccf63862023-01-19 11:44:01 -0800577 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
578 ATRACE_FORMAT_INSTANT("%s (No layers with votes)",
579 to_string(ranking.front().frameRateMode.fps).c_str());
580 return {ranking, kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700581 }
582
Rachel Lee67afbea2023-09-28 15:35:07 -0700583 const bool smoothSwitchOnly = categorySmoothSwitchOnlyLayers > 0;
584 const DisplayModeId activeModeId = activeMode.getId();
585
Ady Abraham8a82ba62020-01-17 12:43:17 -0800586 // Only if all layers want Min we should return Min
587 if (noVoteLayers + minVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000588 ALOGV("All layers Min");
Rachel Lee67afbea2023-09-28 15:35:07 -0700589 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending,
590 std::nullopt, [&](FrameRateMode mode) {
591 return !smoothSwitchOnly ||
592 mode.modePtr->getId() == activeModeId;
593 });
Ady Abrahamccf63862023-01-19 11:44:01 -0800594 ATRACE_FORMAT_INSTANT("%s (All layers Min)",
595 to_string(ranking.front().frameRateMode.fps).c_str());
596 return {ranking, kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800597 }
598
Ady Abraham8a82ba62020-01-17 12:43:17 -0800599 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800600 std::vector<RefreshRateScore> scores;
Ady Abraham68636062022-11-16 17:07:25 -0800601 scores.reserve(mAppRequestFrameRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800602
Ady Abraham68636062022-11-16 17:07:25 -0800603 for (const FrameRateMode& it : mAppRequestFrameRates) {
604 scores.emplace_back(RefreshRateScore{it, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800605 }
606
607 for (const auto& layer : layers) {
Rachel Leece6e0042023-06-27 11:22:54 -0700608 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f, category %s) ",
609 layer.name.c_str(), ftl::enum_string(layer.vote).c_str(), layer.weight,
610 layer.desiredRefreshRate.getValue(),
611 ftl::enum_string(layer.frameRateCategory).c_str());
Rachel Leed0694bc2023-09-12 14:57:58 -0700612 if (layer.isNoVote() || layer.frameRateCategory == FrameRateCategory::NoPreference ||
613 layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800614 continue;
615 }
616
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800617 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800618
Ady Abraham68636062022-11-16 17:07:25 -0800619 for (auto& [mode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
620 const auto& [fps, modePtr] = mode;
621 const bool isSeamlessSwitch = modePtr->getGroup() == activeMode.getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200622
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100623 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100624 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800625 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700626 to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200627 continue;
628 }
629
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100630 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
631 !layer.focused) {
632 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100633 " Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800634 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700635 to_string(activeMode).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100636 continue;
637 }
638
Rachel Lee67afbea2023-09-28 15:35:07 -0700639 if (smoothSwitchOnly && modePtr->getId() != activeModeId) {
640 ALOGV("%s ignores %s because it's non-VRR and smooth switch only."
641 " Current mode = %s",
642 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
643 to_string(activeMode).c_str());
644 continue;
645 }
646
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100647 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100648 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100649 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100650 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
651 // disappeared.
Ady Abraham68636062022-11-16 17:07:25 -0800652 const bool isInPolicyForDefault = modePtr->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100653 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100654 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham68636062022-11-16 17:07:25 -0800655 to_string(*modePtr).c_str(), to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200656 continue;
657 }
658
Ady Abraham90f7fd22023-08-16 11:02:00 -0700659 const bool inPrimaryPhysicalRange =
ramindania04b8a52023-08-07 18:49:47 -0700660 policy->primaryRanges.physical.includes(modePtr->getPeakFps());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700661 const bool inPrimaryRenderRange = policy->primaryRanges.render.includes(fps);
662 if (((policy->primaryRangeIsSingleRate() && !inPrimaryPhysicalRange) ||
663 !inPrimaryRenderRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800664 !(layer.focused &&
665 (layer.vote == LayerVoteType::ExplicitDefault ||
666 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700667 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700668 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700669 continue;
670 }
671
Ady Abraham68636062022-11-16 17:07:25 -0800672 const float layerScore = calculateLayerScoreLocked(layer, fps, isSeamlessSwitch);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000673 const float weightedLayerScore = weight * layerScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800674
Ady Abraham13cfb362022-08-13 05:12:13 +0000675 // Layer with fixed source has a special consideration which depends on the
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000676 // mConfig.frameRateMultipleThreshold. We don't want these layers to score
677 // refresh rates above the threshold, but we also don't want to favor the lower
678 // ones by having a greater number of layers scoring them. Instead, we calculate
679 // the score independently for these layers and later decide which
680 // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
681 // score 120 Hz, but desired 60 fps should contribute to the score.
682 const bool fixedSourceLayer = [](LayerVoteType vote) {
683 switch (vote) {
684 case LayerVoteType::ExplicitExactOrMultiple:
685 case LayerVoteType::Heuristic:
686 return true;
687 case LayerVoteType::NoVote:
688 case LayerVoteType::Min:
689 case LayerVoteType::Max:
690 case LayerVoteType::ExplicitDefault:
691 case LayerVoteType::ExplicitExact:
Rachel Leece6e0042023-06-27 11:22:54 -0700692 case LayerVoteType::ExplicitCategory:
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000693 return false;
694 }
695 }(layer.vote);
Ady Abraham62f51d92022-08-24 22:20:22 +0000696 const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000697 layer.desiredRefreshRate <
698 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
Ady Abraham62f51d92022-08-24 22:20:22 +0000699 if (fixedSourceLayer && layerBelowThreshold) {
Ady Abraham13cfb362022-08-13 05:12:13 +0000700 const bool modeAboveThreshold =
ramindania04b8a52023-08-07 18:49:47 -0700701 modePtr->getPeakFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
Ady Abraham62f51d92022-08-24 22:20:22 +0000702 if (modeAboveThreshold) {
ramindania04b8a52023-08-07 18:49:47 -0700703 ALOGV("%s gives %s (%s(%s)) fixed source (above threshold) score of %.4f",
Ady Abraham68636062022-11-16 17:07:25 -0800704 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700705 to_string(modePtr->getPeakFps()).c_str(),
706 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000707 fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000708 } else {
ramindania04b8a52023-08-07 18:49:47 -0700709 ALOGV("%s gives %s (%s(%s)) fixed source (below threshold) score of %.4f",
Ady Abraham68636062022-11-16 17:07:25 -0800710 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700711 to_string(modePtr->getPeakFps()).c_str(),
712 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000713 fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000714 }
715 } else {
ramindania04b8a52023-08-07 18:49:47 -0700716 ALOGV("%s gives %s (%s(%s)) score of %.4f", formatLayerInfo(layer, weight).c_str(),
717 to_string(fps).c_str(), to_string(modePtr->getPeakFps()).c_str(),
718 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000719 overallScore += weightedLayerScore;
720 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800721 }
722 }
723
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000724 // We want to find the best refresh rate without the fixed source layers,
Ady Abraham62f51d92022-08-24 22:20:22 +0000725 // so we could know whether we should add the modeAboveThreshold scores or not.
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000726 // If the best refresh rate is already above the threshold, it means that
727 // some non-fixed source layers already scored it, so we can just add the score
728 // for all fixed source layers, even the ones that are above the threshold.
729 const bool maxScoreAboveThreshold = [&] {
730 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
731 return false;
732 }
733
734 const auto maxScoreIt =
735 std::max_element(scores.begin(), scores.end(),
736 [](RefreshRateScore max, RefreshRateScore current) {
Ady Abraham68636062022-11-16 17:07:25 -0800737 return current.overallScore > max.overallScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000738 });
ramindania04b8a52023-08-07 18:49:47 -0700739 ALOGV("%s (%s(%s)) is the best refresh rate without fixed source layers. It is %s the "
Ady Abraham68636062022-11-16 17:07:25 -0800740 "threshold for "
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000741 "refresh rate multiples",
Ady Abraham68636062022-11-16 17:07:25 -0800742 to_string(maxScoreIt->frameRateMode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700743 to_string(maxScoreIt->frameRateMode.modePtr->getPeakFps()).c_str(),
744 to_string(maxScoreIt->frameRateMode.modePtr->getVsyncRate()).c_str(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000745 maxScoreAboveThreshold ? "above" : "below");
ramindania04b8a52023-08-07 18:49:47 -0700746 return maxScoreIt->frameRateMode.modePtr->getPeakFps() >=
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000747 Fps::fromValue(mConfig.frameRateMultipleThreshold);
748 }();
749
750 // Now we can add the fixed rate layers score
Ady Abraham68636062022-11-16 17:07:25 -0800751 for (auto& [frameRateMode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000752 overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000753 if (maxScoreAboveThreshold) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000754 overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000755 }
ramindania04b8a52023-08-07 18:49:47 -0700756 ALOGV("%s (%s(%s)) adjusted overallScore is %.4f", to_string(frameRateMode.fps).c_str(),
757 to_string(frameRateMode.modePtr->getPeakFps()).c_str(),
758 to_string(frameRateMode.modePtr->getVsyncRate()).c_str(), overallScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000759 }
760
761 // Now that we scored all the refresh rates we need to pick the one that got the highest
ramindanid72ba162022-09-09 21:33:40 +0000762 // overallScore. Sort the scores based on their overallScore in descending order of priority.
763 const RefreshRateOrder refreshRateOrder =
764 maxVoteLayers > 0 ? RefreshRateOrder::Descending : RefreshRateOrder::Ascending;
765 std::sort(scores.begin(), scores.end(),
766 RefreshRateScoreComparator{.refreshRateOrder = refreshRateOrder});
ramindanid72ba162022-09-09 21:33:40 +0000767
Ady Abraham68636062022-11-16 17:07:25 -0800768 FrameRateRanking ranking;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400769 ranking.reserve(scores.size());
770
771 std::transform(scores.begin(), scores.end(), back_inserter(ranking),
ramindanid72ba162022-09-09 21:33:40 +0000772 [](const RefreshRateScore& score) {
Ady Abraham68636062022-11-16 17:07:25 -0800773 return ScoredFrameRate{score.frameRateMode, score.overallScore};
ramindanid72ba162022-09-09 21:33:40 +0000774 });
Ady Abraham34702102020-02-10 14:12:05 -0800775
Ady Abraham37d46922022-10-05 13:08:51 -0700776 const bool noLayerScore = std::all_of(scores.begin(), scores.end(), [](RefreshRateScore score) {
777 return score.overallScore == 0;
778 });
779
Ady Abraham90f7fd22023-08-16 11:02:00 -0700780 if (policy->primaryRangeIsSingleRate()) {
Alec Mouri11232a22020-05-14 18:06:25 -0700781 // If we never scored any layers, then choose the rate from the primary
782 // range instead of picking a random score from the app range.
Ady Abraham37d46922022-10-05 13:08:51 -0700783 if (noLayerScore) {
ramindanid72ba162022-09-09 21:33:40 +0000784 ALOGV("Layers not scored");
Ady Abrahamccf63862023-01-19 11:44:01 -0800785 const auto descending = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
786 ATRACE_FORMAT_INSTANT("%s (Layers not scored)",
787 to_string(descending.front().frameRateMode.fps).c_str());
788 return {descending, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700789 } else {
Rachel Lee67afbea2023-09-28 15:35:07 -0700790 ALOGV("primaryRangeIsSingleRate");
Ady Abrahamccf63862023-01-19 11:44:01 -0800791 ATRACE_FORMAT_INSTANT("%s (primaryRangeIsSingleRate)",
792 to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400793 return {ranking, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700794 }
795 }
796
Steven Thomasf734df42020-04-13 21:09:28 -0700797 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
798 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
799 // vote we should not change it if we get a touch event. Only apply touch boost if it will
800 // actually increase the refresh rate over the normal selection.
Ady Abraham5e4e9832021-06-14 13:40:56 -0700801 const bool touchBoostForExplicitExact = [&] {
Ady Abraham68636062022-11-16 17:07:25 -0800802 if (supportsAppFrameRateOverrideByContent()) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700803 // Enable touch boost if there are other layers besides exact
804 return explicitExact + noVoteLayers != layers.size();
805 } else {
806 // Enable touch boost if there are no exact layers
807 return explicitExact == 0;
808 }
809 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700810
Ady Abraham68636062022-11-16 17:07:25 -0800811 const auto touchRefreshRates = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700812 using fps_approx_ops::operator<;
813
Rachel Leece6e0042023-06-27 11:22:54 -0700814 if (signals.touch && explicitDefaultVoteLayers == 0 && explicitCategoryVoteLayers == 0 &&
815 touchBoostForExplicitExact &&
Ady Abraham68636062022-11-16 17:07:25 -0800816 scores.front().frameRateMode.fps < touchRefreshRates.front().frameRateMode.fps) {
ramindanid72ba162022-09-09 21:33:40 +0000817 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800818 ATRACE_FORMAT_INSTANT("%s (Touch Boost [late])",
819 to_string(touchRefreshRates.front().frameRateMode.fps).c_str());
ramindanid72ba162022-09-09 21:33:40 +0000820 return {touchRefreshRates, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700821 }
822
Ady Abraham37d46922022-10-05 13:08:51 -0700823 // If we never scored any layers, and we don't favor high refresh rates, prefer to stay with the
824 // current config
825 if (noLayerScore && refreshRateOrder == RefreshRateOrder::Ascending) {
Rachel Lee67afbea2023-09-28 15:35:07 -0700826 ALOGV("preferredDisplayMode");
Ady Abrahamccf63862023-01-19 11:44:01 -0800827 const auto ascendingWithPreferred =
828 rankFrameRates(anchorGroup, RefreshRateOrder::Ascending, activeMode.getId());
829 ATRACE_FORMAT_INSTANT("%s (preferredDisplayMode)",
830 to_string(ascendingWithPreferred.front().frameRateMode.fps).c_str());
831 return {ascendingWithPreferred, kNoSignals};
Ady Abraham37d46922022-10-05 13:08:51 -0700832 }
833
Rachel Lee67afbea2023-09-28 15:35:07 -0700834 ALOGV("%s (scored))", to_string(ranking.front().frameRateMode.fps).c_str());
Ady Abrahamccf63862023-01-19 11:44:01 -0800835 ATRACE_FORMAT_INSTANT("%s (scored))", to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400836 return {ranking, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800837}
838
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400839using LayerRequirementPtrs = std::vector<const RefreshRateSelector::LayerRequirement*>;
840using PerUidLayerRequirements = std::unordered_map<uid_t, LayerRequirementPtrs>;
841
842PerUidLayerRequirements groupLayersByUid(
843 const std::vector<RefreshRateSelector::LayerRequirement>& layers) {
844 PerUidLayerRequirements layersByUid;
Ady Abraham62a0be22020-12-08 16:54:10 -0800845 for (const auto& layer : layers) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400846 const auto it = layersByUid.emplace(layer.ownerUid, LayerRequirementPtrs()).first;
847 auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800848 layersWithSameUid.push_back(&layer);
849 }
850
851 // Remove uids that can't have a frame rate override
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400852 for (auto it = layersByUid.begin(); it != layersByUid.end();) {
853 const auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800854 bool skipUid = false;
855 for (const auto& layer : layersWithSameUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400856 using LayerVoteType = RefreshRateSelector::LayerVoteType;
857
858 if (layer->vote == LayerVoteType::Max || layer->vote == LayerVoteType::Heuristic) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800859 skipUid = true;
860 break;
861 }
862 }
863 if (skipUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400864 it = layersByUid.erase(it);
Ady Abraham62a0be22020-12-08 16:54:10 -0800865 } else {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400866 ++it;
Ady Abraham62a0be22020-12-08 16:54:10 -0800867 }
868 }
869
870 return layersByUid;
871}
872
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400873auto RefreshRateSelector::getFrameRateOverrides(const std::vector<LayerRequirement>& layers,
874 Fps displayRefreshRate,
875 GlobalSignals globalSignals) const
876 -> UidToFrameRateOverride {
Ady Abraham62a0be22020-12-08 16:54:10 -0800877 ATRACE_CALL();
Ady Abraham68636062022-11-16 17:07:25 -0800878 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Disabled) {
879 return {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800880 }
881
Ady Abraham68636062022-11-16 17:07:25 -0800882 ALOGV("%s: %zu layers", __func__, layers.size());
883 std::lock_guard lock(mLock);
884
Ady Abraham8ca643a2022-10-18 18:26:47 -0700885 const auto* policyPtr = getCurrentPolicyLocked();
886 // We don't want to run lower than 30fps
ramindania04b8a52023-08-07 18:49:47 -0700887 // TODO(b/297600226): revise this for dVRR
Ady Abraham8ca643a2022-10-18 18:26:47 -0700888 const Fps minFrameRate = std::max(policyPtr->appRequestRanges.render.min, 30_Hz, isApproxLess);
889
890 using fps_approx_ops::operator/;
891 const unsigned numMultiples = displayRefreshRate / minFrameRate;
892
893 std::vector<std::pair<Fps, float>> scoredFrameRates;
894 scoredFrameRates.reserve(numMultiples);
895
896 for (unsigned n = numMultiples; n > 0; n--) {
897 const Fps divisor = displayRefreshRate / n;
898 if (mConfig.enableFrameRateOverride ==
Ady Abraham68636062022-11-16 17:07:25 -0800899 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
900 !isNativeRefreshRate(divisor)) {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700901 continue;
902 }
903
904 if (policyPtr->appRequestRanges.render.includes(divisor)) {
905 ALOGV("%s: adding %s as a potential frame rate", __func__, to_string(divisor).c_str());
906 scoredFrameRates.emplace_back(divisor, 0);
907 }
908 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800909
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400910 const auto layersByUid = groupLayersByUid(layers);
Ady Abraham62a0be22020-12-08 16:54:10 -0800911 UidToFrameRateOverride frameRateOverrides;
912 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800913 // Layers with ExplicitExactOrMultiple expect touch boost
914 const bool hasExplicitExactOrMultiple =
915 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
916 [](const auto& layer) {
917 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
918 });
919
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700920 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800921 continue;
922 }
923
Ady Abraham8ca643a2022-10-18 18:26:47 -0700924 for (auto& [_, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800925 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -0800926 }
927
928 for (const auto& layer : layersWithSameUid) {
Rachel Lee47adfcf2023-09-15 17:36:56 -0700929 if (layer->isNoVote() || layer->frameRateCategory == FrameRateCategory::NoPreference ||
930 layer->vote == LayerVoteType::Min) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800931 continue;
932 }
933
934 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Rachel Leece6e0042023-06-27 11:22:54 -0700935 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
936 layer->vote != LayerVoteType::ExplicitExact &&
937 layer->vote != LayerVoteType::ExplicitCategory,
938 "Invalid layer vote type for frame rate overrides");
Ady Abraham8ca643a2022-10-18 18:26:47 -0700939 for (auto& [fps, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800940 constexpr bool isSeamlessSwitch = true;
Ady Abraham8ca643a2022-10-18 18:26:47 -0700941 const auto layerScore = calculateLayerScoreLocked(*layer, fps, isSeamlessSwitch);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800942 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -0800943 }
944 }
945
Ady Abraham62a0be22020-12-08 16:54:10 -0800946 // If we never scored any layers, we don't have a preferred frame rate
Ady Abraham8ca643a2022-10-18 18:26:47 -0700947 if (std::all_of(scoredFrameRates.begin(), scoredFrameRates.end(),
948 [](const auto& scoredFrameRate) {
949 const auto [_, score] = scoredFrameRate;
950 return score == 0;
951 })) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800952 continue;
953 }
954
ramindanid72ba162022-09-09 21:33:40 +0000955 // Now that we scored all the refresh rates we need to pick the lowest refresh rate
956 // that got the highest score.
Ady Abraham8ca643a2022-10-18 18:26:47 -0700957 const auto [overrideFps, _] =
958 *std::max_element(scoredFrameRates.begin(), scoredFrameRates.end(),
959 [](const auto& lhsPair, const auto& rhsPair) {
960 const float lhs = lhsPair.second;
961 const float rhs = rhsPair.second;
Ady Abraham68636062022-11-16 17:07:25 -0800962 return lhs < rhs && !ScoredFrameRate::scoresEqual(lhs, rhs);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700963 });
964 ALOGV("%s: overriding to %s for uid=%d", __func__, to_string(overrideFps).c_str(), uid);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700965 ATRACE_FORMAT_INSTANT("%s: overriding to %s for uid=%d", __func__,
966 to_string(overrideFps).c_str(), uid);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700967 frameRateOverrides.emplace(uid, overrideFps);
Ady Abraham62a0be22020-12-08 16:54:10 -0800968 }
969
970 return frameRateOverrides;
971}
972
Ady Abraham0aa373a2022-11-22 13:56:50 -0800973ftl::Optional<FrameRateMode> RefreshRateSelector::onKernelTimerChanged(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800974 std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800975 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100976
Ady Abraham0aa373a2022-11-22 13:56:50 -0800977 const auto current = [&]() REQUIRES(mLock) -> FrameRateMode {
978 if (desiredActiveModeId) {
979 const auto& modePtr = mDisplayModes.get(*desiredActiveModeId)->get();
ramindania04b8a52023-08-07 18:49:47 -0700980 return FrameRateMode{modePtr->getPeakFps(), ftl::as_non_null(modePtr)};
Ady Abraham0aa373a2022-11-22 13:56:50 -0800981 }
982
983 return getActiveModeLocked();
984 }();
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100985
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800986 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
Ady Abraham0aa373a2022-11-22 13:56:50 -0800987 if (current.modePtr->getId() == min->getId()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800988 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100989 }
990
ramindania04b8a52023-08-07 18:49:47 -0700991 return timerExpired ? FrameRateMode{min->getPeakFps(), ftl::as_non_null(min)} : current;
Steven Thomasf734df42020-04-13 21:09:28 -0700992}
993
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400994const DisplayModePtr& RefreshRateSelector::getMinRefreshRateByPolicyLocked() const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800995 const auto& activeMode = *getActiveModeLocked().modePtr;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700996
Ady Abraham68636062022-11-16 17:07:25 -0800997 for (const FrameRateMode& mode : mPrimaryFrameRates) {
998 if (activeMode.getGroup() == mode.modePtr->getGroup()) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800999 return mode.modePtr.get();
Marin Shalamanov46084422020-10-13 12:33:42 +02001000 }
1001 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001002
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001003 ALOGE("Can't find min refresh rate by policy with the same mode group as the current mode %s",
1004 to_string(activeMode).c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001005
1006 // Default to the lowest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -08001007 return mPrimaryFrameRates.front().modePtr.get();
Ady Abraham2139f732019-11-13 18:56:40 -08001008}
1009
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001010const DisplayModePtr& RefreshRateSelector::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Ady Abrahamace3d052022-11-17 16:25:05 -08001011 const ftl::NonNull<DisplayModePtr>* maxByAnchor = &mPrimaryFrameRates.back().modePtr;
1012 const ftl::NonNull<DisplayModePtr>* max = &mPrimaryFrameRates.back().modePtr;
Ady Abraham68636062022-11-16 17:07:25 -08001013
1014 bool maxByAnchorFound = false;
1015 for (auto it = mPrimaryFrameRates.rbegin(); it != mPrimaryFrameRates.rend(); ++it) {
1016 using namespace fps_approx_ops;
ramindania04b8a52023-08-07 18:49:47 -07001017 if (it->modePtr->getPeakFps() > (*max)->getPeakFps()) {
Ady Abraham68636062022-11-16 17:07:25 -08001018 max = &it->modePtr;
Marin Shalamanov46084422020-10-13 12:33:42 +02001019 }
Ady Abraham68636062022-11-16 17:07:25 -08001020
1021 if (anchorGroup == it->modePtr->getGroup() &&
ramindania04b8a52023-08-07 18:49:47 -07001022 it->modePtr->getPeakFps() >= (*maxByAnchor)->getPeakFps()) {
Ady Abraham68636062022-11-16 17:07:25 -08001023 maxByAnchorFound = true;
1024 maxByAnchor = &it->modePtr;
1025 }
1026 }
1027
1028 if (maxByAnchorFound) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001029 return maxByAnchor->get();
Marin Shalamanov46084422020-10-13 12:33:42 +02001030 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001031
ramindanid72ba162022-09-09 21:33:40 +00001032 ALOGE("Can't find max refresh rate by policy with the same group %d", anchorGroup);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001033
1034 // Default to the highest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -08001035 return max->get();
Ady Abraham2139f732019-11-13 18:56:40 -08001036}
1037
Ady Abraham68636062022-11-16 17:07:25 -08001038auto RefreshRateSelector::rankFrameRates(std::optional<int> anchorGroupOpt,
1039 RefreshRateOrder refreshRateOrder,
Rachel Lee67afbea2023-09-28 15:35:07 -07001040 std::optional<DisplayModeId> preferredDisplayModeOpt,
1041 const RankFrameRatesPredicate& predicate) const
Ady Abraham68636062022-11-16 17:07:25 -08001042 -> FrameRateRanking {
Ady Abrahama5992df2023-01-27 21:10:57 -08001043 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -08001044 const char* const whence = __func__;
Ady Abrahama5992df2023-01-27 21:10:57 -08001045
1046 // find the highest frame rate for each display mode
1047 ftl::SmallMap<DisplayModeId, Fps, 8> maxRenderRateForMode;
1048 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
1049 if (ascending) {
1050 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1051 // use a lower frame rate when we want Ascending frame rates.
1052 for (const auto& frameRateMode : mPrimaryFrameRates) {
1053 if (anchorGroupOpt && frameRateMode.modePtr->getGroup() != anchorGroupOpt) {
1054 continue;
1055 }
1056
1057 const auto [iter, _] = maxRenderRateForMode.try_emplace(frameRateMode.modePtr->getId(),
1058 frameRateMode.fps);
1059 if (iter->second < frameRateMode.fps) {
1060 iter->second = frameRateMode.fps;
1061 }
1062 }
1063 }
1064
Ady Abraham68636062022-11-16 17:07:25 -08001065 std::deque<ScoredFrameRate> ranking;
1066 const auto rankFrameRate = [&](const FrameRateMode& frameRateMode) REQUIRES(mLock) {
1067 const auto& modePtr = frameRateMode.modePtr;
Rachel Lee67afbea2023-09-28 15:35:07 -07001068 if ((anchorGroupOpt && modePtr->getGroup() != anchorGroupOpt) ||
1069 !predicate(frameRateMode)) {
Ady Abraham37d46922022-10-05 13:08:51 -07001070 return;
ramindanid72ba162022-09-09 21:33:40 +00001071 }
Ady Abraham37d46922022-10-05 13:08:51 -07001072
Ady Abraham3f965922023-01-23 17:18:29 -08001073 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
ramindanif7075202023-03-10 00:24:34 +00001074 const auto id = modePtr->getId();
Ady Abrahama5992df2023-01-27 21:10:57 -08001075 if (ascending && frameRateMode.fps < *maxRenderRateForMode.get(id)) {
Ady Abraham3f965922023-01-23 17:18:29 -08001076 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1077 // use a lower frame rate when we want Ascending frame rates.
1078 return;
1079 }
1080
Ady Abraham68636062022-11-16 17:07:25 -08001081 float score = calculateDistanceScoreFromMax(frameRateMode.fps);
Ady Abraham3f965922023-01-23 17:18:29 -08001082
1083 if (ascending) {
Ady Abraham37d46922022-10-05 13:08:51 -07001084 score = 1.0f / score;
1085 }
ramindanif7075202023-03-10 00:24:34 +00001086
1087 constexpr float kScore = std::numeric_limits<float>::max();
Ady Abraham37d46922022-10-05 13:08:51 -07001088 if (preferredDisplayModeOpt) {
Ady Abraham68636062022-11-16 17:07:25 -08001089 if (*preferredDisplayModeOpt == modePtr->getId()) {
Ady Abraham68636062022-11-16 17:07:25 -08001090 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
Ady Abraham37d46922022-10-05 13:08:51 -07001091 return;
1092 }
1093 constexpr float kNonPreferredModePenalty = 0.95f;
1094 score *= kNonPreferredModePenalty;
ramindanif7075202023-03-10 00:24:34 +00001095 } else if (ascending && id == getMinRefreshRateByPolicyLocked()->getId()) {
1096 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround
1097 // and actually use a lower frame rate when we want Ascending frame rates.
1098 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
1099 return;
Ady Abraham37d46922022-10-05 13:08:51 -07001100 }
Ady Abraham3f965922023-01-23 17:18:29 -08001101
ramindania04b8a52023-08-07 18:49:47 -07001102 ALOGV("%s(%s) %s (%s(%s)) scored %.2f", whence, ftl::enum_string(refreshRateOrder).c_str(),
1103 to_string(frameRateMode.fps).c_str(), to_string(modePtr->getPeakFps()).c_str(),
1104 to_string(modePtr->getVsyncRate()).c_str(), score);
Ady Abraham68636062022-11-16 17:07:25 -08001105 ranking.emplace_back(ScoredFrameRate{frameRateMode, score});
ramindanid72ba162022-09-09 21:33:40 +00001106 };
1107
1108 if (refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abraham68636062022-11-16 17:07:25 -08001109 std::for_each(mPrimaryFrameRates.begin(), mPrimaryFrameRates.end(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001110 } else {
Ady Abraham68636062022-11-16 17:07:25 -08001111 std::for_each(mPrimaryFrameRates.rbegin(), mPrimaryFrameRates.rend(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001112 }
1113
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001114 if (!ranking.empty() || !anchorGroupOpt) {
1115 return {ranking.begin(), ranking.end()};
ramindanid72ba162022-09-09 21:33:40 +00001116 }
1117
1118 ALOGW("Can't find %s refresh rate by policy with the same mode group"
1119 " as the mode group %d",
1120 refreshRateOrder == RefreshRateOrder::Ascending ? "min" : "max", anchorGroupOpt.value());
1121
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001122 constexpr std::optional<int> kNoAnchorGroup = std::nullopt;
Ady Abraham68636062022-11-16 17:07:25 -08001123 return rankFrameRates(kNoAnchorGroup, refreshRateOrder, preferredDisplayModeOpt);
ramindanid72ba162022-09-09 21:33:40 +00001124}
1125
Ady Abrahamace3d052022-11-17 16:25:05 -08001126FrameRateMode RefreshRateSelector::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -08001127 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001128 return getActiveModeLocked();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001129}
1130
Ady Abrahamace3d052022-11-17 16:25:05 -08001131const FrameRateMode& RefreshRateSelector::getActiveModeLocked() const {
1132 return *mActiveModeOpt;
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001133}
1134
Ady Abrahamace3d052022-11-17 16:25:05 -08001135void RefreshRateSelector::setActiveMode(DisplayModeId modeId, Fps renderFrameRate) {
Ady Abraham2139f732019-11-13 18:56:40 -08001136 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001137
Ady Abraham68636062022-11-16 17:07:25 -08001138 // Invalidate the cached invocation to getRankedFrameRates. This forces
1139 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1140 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001141
Ady Abrahamace3d052022-11-17 16:25:05 -08001142 const auto activeModeOpt = mDisplayModes.get(modeId);
1143 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1144
1145 mActiveModeOpt.emplace(FrameRateMode{renderFrameRate, ftl::as_non_null(activeModeOpt->get())});
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001146}
1147
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001148RefreshRateSelector::RefreshRateSelector(DisplayModes modes, DisplayModeId activeModeId,
1149 Config config)
rnlee3bd610662021-06-23 16:27:57 -07001150 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001151 initializeIdleTimer();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001152 FTL_FAKE_GUARD(kMainThreadContext, updateDisplayModes(std::move(modes), activeModeId));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001153}
1154
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001155void RefreshRateSelector::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +00001156 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001157 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +00001158 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001159 [this] {
1160 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1161 if (const auto callbacks = getIdleTimerCallbacks()) {
1162 callbacks->onReset();
1163 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001164 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001165 [this] {
1166 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1167 if (const auto callbacks = getIdleTimerCallbacks()) {
1168 callbacks->onExpired();
1169 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001170 });
Ady Abraham9a2ea342021-09-03 17:32:34 -07001171 }
1172}
1173
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001174void RefreshRateSelector::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001175 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001176
Ady Abraham68636062022-11-16 17:07:25 -08001177 // Invalidate the cached invocation to getRankedFrameRates. This forces
1178 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1179 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001180
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001181 mDisplayModes = std::move(modes);
Ady Abrahamace3d052022-11-17 16:25:05 -08001182 const auto activeModeOpt = mDisplayModes.get(activeModeId);
1183 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
ramindania04b8a52023-08-07 18:49:47 -07001184 mActiveModeOpt = FrameRateMode{activeModeOpt->get()->getPeakFps(),
1185 ftl::as_non_null(activeModeOpt->get())};
Ady Abrahamabc27602020-04-08 17:20:29 -07001186
Ady Abraham68636062022-11-16 17:07:25 -08001187 const auto sortedModes = sortByRefreshRate(mDisplayModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001188 mMinRefreshRateModeIt = sortedModes.front();
1189 mMaxRefreshRateModeIt = sortedModes.back();
1190
Marin Shalamanov75f37252021-02-10 21:43:57 +01001191 // Reset the policy because the old one may no longer be valid.
1192 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001193 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -08001194
Ady Abraham8ca643a2022-10-18 18:26:47 -07001195 mFrameRateOverrideConfig = [&] {
1196 switch (mConfig.enableFrameRateOverride) {
1197 case Config::FrameRateOverride::Disabled:
Ady Abraham68636062022-11-16 17:07:25 -08001198 case Config::FrameRateOverride::AppOverride:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001199 case Config::FrameRateOverride::Enabled:
1200 return mConfig.enableFrameRateOverride;
Ady Abraham68636062022-11-16 17:07:25 -08001201 case Config::FrameRateOverride::AppOverrideNativeRefreshRates:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001202 return shouldEnableFrameRateOverride(sortedModes)
Ady Abraham68636062022-11-16 17:07:25 -08001203 ? Config::FrameRateOverride::AppOverrideNativeRefreshRates
Ady Abraham8ca643a2022-10-18 18:26:47 -07001204 : Config::FrameRateOverride::Disabled;
1205 }
1206 }();
Ady Abraham4899ff82021-01-06 13:53:29 -08001207
Ady Abraham68636062022-11-16 17:07:25 -08001208 if (mConfig.enableFrameRateOverride ==
1209 Config::FrameRateOverride::AppOverrideNativeRefreshRates) {
1210 for (const auto& [_, mode] : mDisplayModes) {
ramindania04b8a52023-08-07 18:49:47 -07001211 mAppOverrideNativeRefreshRates.try_emplace(mode->getPeakFps(), ftl::unit);
Ady Abraham68636062022-11-16 17:07:25 -08001212 }
1213 }
1214
Ady Abrahamabc27602020-04-08 17:20:29 -07001215 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001216}
1217
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001218bool RefreshRateSelector::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001219 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001220 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
ramindania04b8a52023-08-07 18:49:47 -07001221 if (!policy.primaryRanges.physical.includes(mode->get()->getPeakFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001222 ALOGE("Default mode is not in the primary range.");
1223 return false;
1224 }
1225 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001226 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -07001227 return false;
1228 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001229
Ady Abraham68636062022-11-16 17:07:25 -08001230 const auto& primaryRanges = policy.primaryRanges;
1231 const auto& appRequestRanges = policy.appRequestRanges;
1232 ALOGE_IF(!appRequestRanges.physical.includes(primaryRanges.physical),
Ady Abraham08048ce2022-11-30 18:08:00 -08001233 "Physical range is invalid: primary: %s appRequest: %s",
1234 to_string(primaryRanges.physical).c_str(),
1235 to_string(appRequestRanges.physical).c_str());
1236 ALOGE_IF(!appRequestRanges.render.includes(primaryRanges.render),
1237 "Render range is invalid: primary: %s appRequest: %s",
1238 to_string(primaryRanges.render).c_str(), to_string(appRequestRanges.render).c_str());
Ady Abraham68636062022-11-16 17:07:25 -08001239
1240 return primaryRanges.valid() && appRequestRanges.valid();
Steven Thomasd4071902020-03-24 16:02:53 -07001241}
1242
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001243auto RefreshRateSelector::setPolicy(const PolicyVariant& policy) -> SetPolicyResult {
Dominik Laskowski36dced82022-09-02 09:24:00 -07001244 Policy oldPolicy;
Ady Abrahamace3d052022-11-17 16:25:05 -08001245 PhysicalDisplayId displayId;
Dominik Laskowski36dced82022-09-02 09:24:00 -07001246 {
1247 std::lock_guard lock(mLock);
1248 oldPolicy = *getCurrentPolicyLocked();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001249
Dominik Laskowski36dced82022-09-02 09:24:00 -07001250 const bool valid = ftl::match(
1251 policy,
1252 [this](const auto& policy) {
1253 ftl::FakeGuard guard(mLock);
1254 if (!isPolicyValidLocked(policy)) {
1255 ALOGE("Invalid policy: %s", policy.toString().c_str());
1256 return false;
1257 }
1258
1259 using T = std::decay_t<decltype(policy)>;
1260
1261 if constexpr (std::is_same_v<T, DisplayManagerPolicy>) {
1262 mDisplayManagerPolicy = policy;
1263 } else {
1264 static_assert(std::is_same_v<T, OverridePolicy>);
1265 mOverridePolicy = policy;
1266 }
1267 return true;
1268 },
1269 [this](NoOverridePolicy) {
1270 ftl::FakeGuard guard(mLock);
1271 mOverridePolicy.reset();
1272 return true;
1273 });
1274
1275 if (!valid) {
1276 return SetPolicyResult::Invalid;
1277 }
1278
Ady Abraham68636062022-11-16 17:07:25 -08001279 mGetRankedFrameRatesCache.reset();
Dominik Laskowski36dced82022-09-02 09:24:00 -07001280
1281 if (*getCurrentPolicyLocked() == oldPolicy) {
1282 return SetPolicyResult::Unchanged;
1283 }
1284 constructAvailableRefreshRates();
Ady Abrahamace3d052022-11-17 16:25:05 -08001285
1286 displayId = getActiveModeLocked().modePtr->getPhysicalDisplayId();
Steven Thomasd4071902020-03-24 16:02:53 -07001287 }
Dominik Laskowski36dced82022-09-02 09:24:00 -07001288
Dominik Laskowski36dced82022-09-02 09:24:00 -07001289 const unsigned numModeChanges = std::exchange(mNumModeSwitchesInPolicy, 0u);
1290
1291 ALOGI("Display %s policy changed\n"
1292 "Previous: %s\n"
1293 "Current: %s\n"
1294 "%u mode changes were performed under the previous policy",
1295 to_string(displayId).c_str(), oldPolicy.toString().c_str(), toString(policy).c_str(),
1296 numModeChanges);
1297
1298 return SetPolicyResult::Changed;
Steven Thomasd4071902020-03-24 16:02:53 -07001299}
1300
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001301auto RefreshRateSelector::getCurrentPolicyLocked() const -> const Policy* {
Steven Thomasd4071902020-03-24 16:02:53 -07001302 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
1303}
1304
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001305auto RefreshRateSelector::getCurrentPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001306 std::lock_guard lock(mLock);
1307 return *getCurrentPolicyLocked();
1308}
1309
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001310auto RefreshRateSelector::getDisplayManagerPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001311 std::lock_guard lock(mLock);
1312 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001313}
1314
Ady Abrahamace3d052022-11-17 16:25:05 -08001315bool RefreshRateSelector::isModeAllowed(const FrameRateMode& mode) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001316 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001317 return std::find(mAppRequestFrameRates.begin(), mAppRequestFrameRates.end(), mode) !=
1318 mAppRequestFrameRates.end();
Ady Abraham2139f732019-11-13 18:56:40 -08001319}
1320
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001321void RefreshRateSelector::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001322 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -07001323 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001324 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -07001325
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001326 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -08001327
Ady Abraham68636062022-11-16 17:07:25 -08001328 const auto filterRefreshRates = [&](const FpsRanges& ranges,
1329 const char* rangeName) REQUIRES(mLock) {
1330 const auto filterModes = [&](const DisplayMode& mode) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001331 return mode.getResolution() == defaultMode->getResolution() &&
1332 mode.getDpi() == defaultMode->getDpi() &&
1333 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
ramindania04b8a52023-08-07 18:49:47 -07001334 ranges.physical.includes(mode.getPeakFps()) &&
1335 (supportsFrameRateOverride() || ranges.render.includes(mode.getPeakFps()));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001336 };
Ady Abraham8a82ba62020-01-17 12:43:17 -08001337
Ady Abraham90f7fd22023-08-16 11:02:00 -07001338 auto frameRateModes = createFrameRateModes(*policy, filterModes, ranges.render);
Ady Abraham41bf7c62023-07-20 10:33:06 -07001339 if (frameRateModes.empty()) {
1340 ALOGW("No matching frame rate modes for %s range. policy: %s", rangeName,
1341 policy->toString().c_str());
1342 // TODO(b/292105422): Ideally DisplayManager should not send render ranges smaller than
1343 // the min supported. See b/292047939.
1344 // For not we just ignore the render ranges.
Ady Abraham90f7fd22023-08-16 11:02:00 -07001345 frameRateModes = createFrameRateModes(*policy, filterModes, {});
Ady Abraham41bf7c62023-07-20 10:33:06 -07001346 }
Ady Abraham68636062022-11-16 17:07:25 -08001347 LOG_ALWAYS_FATAL_IF(frameRateModes.empty(),
Ady Abraham41bf7c62023-07-20 10:33:06 -07001348 "No matching frame rate modes for %s range even after ignoring the "
1349 "render range. policy: %s",
1350 rangeName, policy->toString().c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -08001351
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001352 const auto stringifyModes = [&] {
1353 std::string str;
Ady Abraham68636062022-11-16 17:07:25 -08001354 for (const auto& frameRateMode : frameRateModes) {
1355 str += to_string(frameRateMode) + " ";
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001356 }
1357 return str;
1358 };
Ady Abraham68636062022-11-16 17:07:25 -08001359 ALOGV("%s render rates: %s", rangeName, stringifyModes().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -07001360
Ady Abraham68636062022-11-16 17:07:25 -08001361 return frameRateModes;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001362 };
1363
Ady Abraham68636062022-11-16 17:07:25 -08001364 mPrimaryFrameRates = filterRefreshRates(policy->primaryRanges, "primary");
1365 mAppRequestFrameRates = filterRefreshRates(policy->appRequestRanges, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -08001366}
1367
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001368Fps RefreshRateSelector::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001369 using namespace fps_approx_ops;
1370
1371 if (frameRate <= mKnownFrameRates.front()) {
1372 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001373 }
1374
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001375 if (frameRate >= mKnownFrameRates.back()) {
1376 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001377 }
1378
Marin Shalamanove8a663d2020-11-24 17:48:00 +01001379 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001380 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001381
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001382 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
1383 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001384 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
1385}
1386
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001387auto RefreshRateSelector::getIdleTimerAction() const -> KernelIdleTimerAction {
Ana Krulecb9afd792020-06-11 13:16:15 -07001388 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001389
ramindania04b8a52023-08-07 18:49:47 -07001390 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getPeakFps();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001391 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -07001392
1393 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
1394 // the min allowed refresh rate is higher than the device min, we do not want to enable the
1395 // timer.
ramindania04b8a52023-08-07 18:49:47 -07001396 if (isStrictlyLess(deviceMinFps, minByPolicy->getPeakFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001397 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001398 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001399
ramindanid72ba162022-09-09 21:33:40 +00001400 const DisplayModePtr& maxByPolicy =
Ady Abrahamace3d052022-11-17 16:25:05 -08001401 getMaxRefreshRateByPolicyLocked(getActiveModeLocked().modePtr->getGroup());
Ana Krulecb9afd792020-06-11 13:16:15 -07001402 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001403 // Turn on the timer when the min of the primary range is below the device min.
1404 if (const Policy* currentPolicy = getCurrentPolicyLocked();
Ady Abraham285f8c12022-10-11 17:12:14 -07001405 isApproxLess(currentPolicy->primaryRanges.physical.min, deviceMinFps)) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001406 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001407 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001408 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001409 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001410
Ana Krulecb9afd792020-06-11 13:16:15 -07001411 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001412 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001413}
1414
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001415int RefreshRateSelector::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -07001416 // This calculation needs to be in sync with the java code
1417 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001418
1419 // The threshold must be smaller than 0.001 in order to differentiate
1420 // between the fractional pairs (e.g. 59.94 and 60).
1421 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001422 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -07001423 const auto numPeriodsRounded = std::round(numPeriods);
1424 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001425 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -07001426 }
1427
Ady Abraham62f216c2020-10-13 19:07:23 -07001428 return static_cast<int>(numPeriodsRounded);
1429}
1430
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001431bool RefreshRateSelector::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001432 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001433 return isFractionalPairOrMultiple(bigger, smaller);
1434 }
1435
1436 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
1437 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001438 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
1439 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001440}
1441
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001442void RefreshRateSelector::dump(utils::Dumper& dumper) const {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001443 using namespace std::string_view_literals;
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001444
Marin Shalamanovba421a82020-11-10 21:49:26 +01001445 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +01001446
Ady Abrahamace3d052022-11-17 16:25:05 -08001447 const auto activeMode = getActiveModeLocked();
1448 dumper.dump("activeMode"sv, to_string(activeMode));
Marin Shalamanovba421a82020-11-10 21:49:26 +01001449
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001450 dumper.dump("displayModes"sv);
1451 {
1452 utils::Dumper::Indent indent(dumper);
1453 for (const auto& [id, mode] : mDisplayModes) {
1454 dumper.dump({}, to_string(*mode));
1455 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001456 }
1457
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001458 dumper.dump("displayManagerPolicy"sv, mDisplayManagerPolicy.toString());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001459
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001460 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
1461 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001462 dumper.dump("overridePolicy"sv, currentPolicy.toString());
ramindani32cf0602022-03-02 02:30:29 +00001463 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001464
Ady Abraham8ca643a2022-10-18 18:26:47 -07001465 dumper.dump("frameRateOverrideConfig"sv, *ftl::enum_name(mFrameRateOverrideConfig));
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001466
Dominik Laskowski03cfce82022-11-02 12:13:29 -04001467 dumper.dump("idleTimer"sv);
1468 {
1469 utils::Dumper::Indent indent(dumper);
1470 dumper.dump("interval"sv, mIdleTimer.transform(&OneShotTimer::interval));
1471 dumper.dump("controller"sv,
1472 mConfig.kernelIdleTimerController
1473 .and_then(&ftl::enum_name<KernelIdleTimerController>)
1474 .value_or("Platform"sv));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001475 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001476}
1477
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001478std::chrono::milliseconds RefreshRateSelector::getIdleTimerTimeout() {
ramindani32cf0602022-03-02 02:30:29 +00001479 return mConfig.idleTimerTimeout;
1480}
1481
Rachel Leece6e0042023-06-27 11:22:54 -07001482// TODO(b/293651105): Extract category FpsRange mapping to OEM-configurable config.
1483FpsRange RefreshRateSelector::getFrameRateCategoryRange(FrameRateCategory category) {
1484 switch (category) {
1485 case FrameRateCategory::High:
1486 return FpsRange{90_Hz, 120_Hz};
1487 case FrameRateCategory::Normal:
1488 return FpsRange{60_Hz, 90_Hz};
1489 case FrameRateCategory::Low:
Rachel Leee4c1dfc2023-11-10 14:05:03 -08001490 return FpsRange{30_Hz, 30_Hz};
Rachel Leece6e0042023-06-27 11:22:54 -07001491 case FrameRateCategory::NoPreference:
1492 case FrameRateCategory::Default:
1493 LOG_ALWAYS_FATAL("Should not get fps range for frame rate category: %s",
1494 ftl::enum_string(category).c_str());
1495 return FpsRange{0_Hz, 0_Hz};
1496 default:
1497 LOG_ALWAYS_FATAL("Invalid frame rate category for range: %s",
1498 ftl::enum_string(category).c_str());
1499 return FpsRange{0_Hz, 0_Hz};
1500 }
1501}
1502
Ady Abraham2139f732019-11-13 18:56:40 -08001503} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001504
1505// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001506#pragma clang diagnostic pop // ignored "-Wextra"