blob: eac527b0e84ada237ed780402a4e26b548268dfe [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
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040039#include "RefreshRateSelector.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080040
ramindania04b8a52023-08-07 18:49:47 -070041#include <com_android_graphics_surfaceflinger_flags.h>
42
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080043#undef LOG_TAG
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040044#define LOG_TAG "RefreshRateSelector"
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080045
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080046namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010047namespace {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070048
ramindania04b8a52023-08-07 18:49:47 -070049using namespace com::android::graphics::surfaceflinger;
50
Dominik Laskowskib0054a22022-03-03 09:03:06 -080051struct RefreshRateScore {
Ady Abraham68636062022-11-16 17:07:25 -080052 FrameRateMode frameRateMode;
Ady Abrahamae2e3c72022-08-13 05:12:13 +000053 float overallScore;
54 struct {
Ady Abraham62f51d92022-08-24 22:20:22 +000055 float modeBelowThreshold;
56 float modeAboveThreshold;
57 } fixedRateBelowThresholdLayersScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -080058};
59
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040060constexpr RefreshRateSelector::GlobalSignals kNoSignals;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080061
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040062std::string formatLayerInfo(const RefreshRateSelector::LayerRequirement& layer, float weight) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080063 return base::StringPrintf("%s (type=%s, weight=%.2f, seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070064 ftl::enum_string(layer.vote).c_str(), weight,
65 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010066 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010067}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010068
Marin Shalamanova7fe3042021-01-29 21:02:08 +010069std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070070 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010071 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010072
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070073 // Add all supported refresh rates.
Dominik Laskowskib0054a22022-03-03 09:03:06 -080074 for (const auto& [id, mode] : modes) {
ramindania04b8a52023-08-07 18:49:47 -070075 knownFrameRates.push_back(mode->getPeakFps());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010076 }
77
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070078 // Sort and remove duplicates.
79 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010080 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070081 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010082 knownFrameRates.end());
83 return knownFrameRates;
84}
85
Ady Abraham68636062022-11-16 17:07:25 -080086std::vector<DisplayModeIterator> sortByRefreshRate(const DisplayModes& modes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080087 std::vector<DisplayModeIterator> sortedModes;
88 sortedModes.reserve(modes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -080089 for (auto it = modes.begin(); it != modes.end(); ++it) {
Ady Abraham68636062022-11-16 17:07:25 -080090 sortedModes.push_back(it);
Dominik Laskowskib0054a22022-03-03 09:03:06 -080091 }
92
93 std::sort(sortedModes.begin(), sortedModes.end(), [](auto it1, auto it2) {
94 const auto& mode1 = it1->second;
95 const auto& mode2 = it2->second;
96
ramindania04b8a52023-08-07 18:49:47 -070097 if (mode1->getVsyncRate().getPeriodNsecs() == mode2->getVsyncRate().getPeriodNsecs()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080098 return mode1->getGroup() > mode2->getGroup();
99 }
100
ramindania04b8a52023-08-07 18:49:47 -0700101 return mode1->getVsyncRate().getPeriodNsecs() > mode2->getVsyncRate().getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800102 });
103
104 return sortedModes;
Marin Shalamanov46084422020-10-13 12:33:42 +0200105}
106
ramindania04b8a52023-08-07 18:49:47 -0700107std::pair<unsigned, unsigned> divisorRange(Fps vsyncRate, Fps peakFps, FpsRange range,
Ady Abraham68636062022-11-16 17:07:25 -0800108 RefreshRateSelector::Config::FrameRateOverride config) {
109 if (config != RefreshRateSelector::Config::FrameRateOverride::Enabled) {
110 return {1, 1};
111 }
112
113 using fps_approx_ops::operator/;
Ady Abraham08048ce2022-11-30 18:08:00 -0800114 // use signed type as `fps / range.max` might be 0
ramindania04b8a52023-08-07 18:49:47 -0700115 auto start = std::max(1, static_cast<int>(peakFps / range.max) - 1);
Ady Abrahamd6d80162023-10-23 12:57:41 -0700116 if (FlagManager::getInstance().vrr_config()) {
ramindania04b8a52023-08-07 18:49:47 -0700117 start = std::max(1,
118 static_cast<int>(vsyncRate /
119 std::min(range.max, peakFps, fps_approx_ops::operator<)) -
120 1);
121 }
122 const auto end = vsyncRate /
Ady Abraham68636062022-11-16 17:07:25 -0800123 std::max(range.min, RefreshRateSelector::kMinSupportedFrameRate,
124 fps_approx_ops::operator<);
125
126 return {start, end};
127}
128
Ady Abraham8ca643a2022-10-18 18:26:47 -0700129bool shouldEnableFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800130 for (const auto it1 : sortedModes) {
131 const auto& mode1 = it1->second;
132 for (const auto it2 : sortedModes) {
133 const auto& mode2 = it2->second;
134
ramindania04b8a52023-08-07 18:49:47 -0700135 if (RefreshRateSelector::getFrameRateDivisor(mode1->getPeakFps(),
136 mode2->getPeakFps()) >= 2) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800137 return true;
138 }
139 }
140 }
141 return false;
142}
143
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400144std::string toString(const RefreshRateSelector::PolicyVariant& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700145 using namespace std::string_literals;
146
147 return ftl::match(
148 policy,
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400149 [](const RefreshRateSelector::DisplayManagerPolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700150 return "DisplayManagerPolicy"s + policy.toString();
151 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400152 [](const RefreshRateSelector::OverridePolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700153 return "OverridePolicy"s + policy.toString();
154 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400155 [](RefreshRateSelector::NoOverridePolicy) { return "NoOverridePolicy"s; });
Dominik Laskowski36dced82022-09-02 09:24:00 -0700156}
157
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800158} // namespace
159
Ady Abraham68636062022-11-16 17:07:25 -0800160auto RefreshRateSelector::createFrameRateModes(
Ady Abraham90f7fd22023-08-16 11:02:00 -0700161 const Policy& policy, std::function<bool(const DisplayMode&)>&& filterModes,
162 const FpsRange& renderRange) const -> std::vector<FrameRateMode> {
Ady Abraham68636062022-11-16 17:07:25 -0800163 struct Key {
164 Fps fps;
165 int32_t group;
166 };
167
168 struct KeyLess {
169 bool operator()(const Key& a, const Key& b) const {
170 using namespace fps_approx_ops;
171 if (a.fps != b.fps) {
172 return a.fps < b.fps;
173 }
174
175 // For the same fps the order doesn't really matter, but we still
176 // want the behaviour of a strictly less operator.
177 // We use the group id as the secondary ordering for that.
178 return a.group < b.group;
179 }
180 };
181
182 std::map<Key, DisplayModeIterator, KeyLess> ratesMap;
183 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
184 const auto& [id, mode] = *it;
185
186 if (!filterModes(*mode)) {
187 continue;
188 }
ramindania04b8a52023-08-07 18:49:47 -0700189 const auto vsyncRate = mode->getVsyncRate();
190 const auto peakFps = mode->getPeakFps();
Ady Abraham68636062022-11-16 17:07:25 -0800191 const auto [start, end] =
ramindania04b8a52023-08-07 18:49:47 -0700192 divisorRange(vsyncRate, peakFps, renderRange, mConfig.enableFrameRateOverride);
Ady Abraham68636062022-11-16 17:07:25 -0800193 for (auto divisor = start; divisor <= end; divisor++) {
ramindania04b8a52023-08-07 18:49:47 -0700194 const auto fps = vsyncRate / divisor;
Ady Abraham68636062022-11-16 17:07:25 -0800195 using fps_approx_ops::operator<;
Ady Abrahamdc0b3a72023-01-04 16:58:27 -0800196 if (divisor > 1 && fps < kMinSupportedFrameRate) {
Ady Abraham68636062022-11-16 17:07:25 -0800197 break;
198 }
199
200 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Enabled &&
201 !renderRange.includes(fps)) {
202 continue;
203 }
204
205 if (mConfig.enableFrameRateOverride ==
206 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
207 !isNativeRefreshRate(fps)) {
208 continue;
209 }
210
211 const auto [existingIter, emplaceHappened] =
212 ratesMap.try_emplace(Key{fps, mode->getGroup()}, it);
213 if (emplaceHappened) {
ramindania04b8a52023-08-07 18:49:47 -0700214 ALOGV("%s: including %s (%s(%s))", __func__, to_string(fps).c_str(),
215 to_string(peakFps).c_str(), to_string(vsyncRate).c_str());
Ady Abraham68636062022-11-16 17:07:25 -0800216 } else {
Ady Abraham90f7fd22023-08-16 11:02:00 -0700217 // If the primary physical range is a single rate, prefer to stay in that rate
218 // even if there is a lower physical refresh rate available. This would cause more
219 // cases to stay within the primary physical range
ramindania04b8a52023-08-07 18:49:47 -0700220 const Fps existingModeFps = existingIter->second->second->getPeakFps();
Ady Abraham90f7fd22023-08-16 11:02:00 -0700221 const bool existingModeIsPrimaryRange = policy.primaryRangeIsSingleRate() &&
222 policy.primaryRanges.physical.includes(existingModeFps);
223 const bool newModeIsPrimaryRange = policy.primaryRangeIsSingleRate() &&
ramindania04b8a52023-08-07 18:49:47 -0700224 policy.primaryRanges.physical.includes(mode->getPeakFps());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700225 if (newModeIsPrimaryRange == existingModeIsPrimaryRange) {
226 // We might need to update the map as we found a lower refresh rate
ramindania04b8a52023-08-07 18:49:47 -0700227 if (isStrictlyLess(mode->getPeakFps(), existingModeFps)) {
Ady Abraham90f7fd22023-08-16 11:02:00 -0700228 existingIter->second = it;
ramindania04b8a52023-08-07 18:49:47 -0700229 ALOGV("%s: changing %s (%s(%s)) as we found a lower physical rate",
230 __func__, to_string(fps).c_str(), to_string(peakFps).c_str(),
231 to_string(vsyncRate).c_str());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700232 }
233 } else if (newModeIsPrimaryRange) {
Ady Abraham68636062022-11-16 17:07:25 -0800234 existingIter->second = it;
ramindania04b8a52023-08-07 18:49:47 -0700235 ALOGV("%s: changing %s (%s(%s)) to stay in the primary range", __func__,
236 to_string(fps).c_str(), to_string(peakFps).c_str(),
237 to_string(vsyncRate).c_str());
Ady Abraham68636062022-11-16 17:07:25 -0800238 }
239 }
240 }
241 }
242
243 std::vector<FrameRateMode> frameRateModes;
244 frameRateModes.reserve(ratesMap.size());
245 for (const auto& [key, mode] : ratesMap) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800246 frameRateModes.emplace_back(FrameRateMode{key.fps, ftl::as_non_null(mode->second)});
Ady Abraham68636062022-11-16 17:07:25 -0800247 }
248
249 // We always want that the lowest frame rate will be corresponding to the
250 // lowest mode for power saving.
251 const auto lowestRefreshRateIt =
252 std::min_element(frameRateModes.begin(), frameRateModes.end(),
253 [](const FrameRateMode& lhs, const FrameRateMode& rhs) {
ramindania04b8a52023-08-07 18:49:47 -0700254 return isStrictlyLess(lhs.modePtr->getVsyncRate(),
255 rhs.modePtr->getVsyncRate());
Ady Abraham68636062022-11-16 17:07:25 -0800256 });
257 frameRateModes.erase(frameRateModes.begin(), lowestRefreshRateIt);
258
259 return frameRateModes;
260}
261
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400262struct RefreshRateSelector::RefreshRateScoreComparator {
ramindanid72ba162022-09-09 21:33:40 +0000263 bool operator()(const RefreshRateScore& lhs, const RefreshRateScore& rhs) const {
Ady Abraham68636062022-11-16 17:07:25 -0800264 const auto& [frameRateMode, overallScore, _] = lhs;
ramindanid72ba162022-09-09 21:33:40 +0000265
Ady Abraham68636062022-11-16 17:07:25 -0800266 std::string name = to_string(frameRateMode);
267
ramindanid72ba162022-09-09 21:33:40 +0000268 ALOGV("%s sorting scores %.2f", name.c_str(), overallScore);
ramindanid72ba162022-09-09 21:33:40 +0000269
Ady Abraham68636062022-11-16 17:07:25 -0800270 if (!ScoredFrameRate::scoresEqual(overallScore, rhs.overallScore)) {
ramindanid72ba162022-09-09 21:33:40 +0000271 return overallScore > rhs.overallScore;
272 }
273
ramindanid72ba162022-09-09 21:33:40 +0000274 if (refreshRateOrder == RefreshRateOrder::Descending) {
275 using fps_approx_ops::operator>;
Ady Abraham68636062022-11-16 17:07:25 -0800276 return frameRateMode.fps > rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000277 } else {
278 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -0800279 return frameRateMode.fps < rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000280 }
281 }
282
283 const RefreshRateOrder refreshRateOrder;
284};
285
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400286std::string RefreshRateSelector::Policy::toString() const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700287 return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
Ady Abraham285f8c12022-10-11 17:12:14 -0700288 ", primaryRanges=%s, appRequestRanges=%s}",
Dominik Laskowski43baf902023-11-17 18:13:11 -0500289 ftl::to_underlying(defaultMode),
290 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
Rachel Leee5514a72023-10-25 16:20:29 -0700336 if (layer.vote == LayerVoteType::ExplicitGte) {
337 using fps_approx_ops::operator>=;
338 if (refreshRate >= layer.desiredRefreshRate) {
339 return 1.0f;
340 } else {
341 return calculateDistanceScoreLocked(layer.desiredRefreshRate, refreshRate);
342 }
343 }
344
Ady Abraham62a0be22020-12-08 16:54:10 -0800345 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
346 layer.vote == LayerVoteType::Heuristic) {
Ady Abrahambd44e8a2023-07-24 11:30:06 -0700347 using fps_approx_ops::operator<;
348 if (refreshRate < 60_Hz) {
349 const bool favorsAtLeast60 =
350 std::find_if(mFrameRatesThatFavorsAtLeast60.begin(),
351 mFrameRatesThatFavorsAtLeast60.end(), [&](Fps fps) {
352 using fps_approx_ops::operator==;
353 return fps == layer.desiredRefreshRate;
354 }) != mFrameRatesThatFavorsAtLeast60.end();
355 if (favorsAtLeast60) {
356 return 0;
357 }
358 }
359
Ady Abraham68636062022-11-16 17:07:25 -0800360 const float multiplier = refreshRate.getValue() / layer.desiredRefreshRate.getValue();
361
362 // We only want to score this layer as a fractional pair if the content is not
363 // significantly faster than the display rate, at it would cause a significant frame drop.
364 // It is more appropriate to choose a higher display rate even if
365 // a pull-down will be required.
Rachel Lee36426fa2023-03-08 20:13:52 -0800366 constexpr float kMinMultiplier = 0.75f;
Ady Abraham68636062022-11-16 17:07:25 -0800367 if (multiplier >= kMinMultiplier &&
368 isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700369 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200370 }
371
Ady Abraham62a0be22020-12-08 16:54:10 -0800372 // Calculate how many display vsyncs we need to present a single frame for this
373 // layer
374 const auto [displayFramesQuotient, displayFramesRemainder] =
375 getDisplayFrames(layerPeriod, displayPeriod);
376 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
377 if (displayFramesRemainder == 0) {
378 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700379 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800380 }
381
382 if (displayFramesQuotient == 0) {
383 // Layer desired refresh rate is higher than the display rate.
384 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
385 (1.0f / (MAX_FRAMES_TO_FIT + 1));
386 }
387
388 // Layer desired refresh rate is lower than the display rate. Check how well it fits
389 // the cadence.
390 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
391 int iter = 2;
392 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
393 diff = diff - (displayPeriod - diff);
394 iter++;
395 }
396
Ady Abraham05243be2021-09-16 15:58:52 -0700397 return (1.0f / iter);
398 }
399
400 return 0;
401}
402
Rachel Leee5514a72023-10-25 16:20:29 -0700403float RefreshRateSelector::calculateDistanceScoreLocked(Fps referenceRate, Fps refreshRate) const {
404 using fps_approx_ops::operator>=;
405 const float ratio = referenceRate >= refreshRate
406 ? refreshRate.getValue() / referenceRate.getValue()
407 : referenceRate.getValue() / refreshRate.getValue();
408 // Use ratio^2 to get a lower score the more we get further from the reference rate.
ramindanid72ba162022-09-09 21:33:40 +0000409 return ratio * ratio;
410}
411
Rachel Leee5514a72023-10-25 16:20:29 -0700412float RefreshRateSelector::calculateDistanceScoreFromMaxLocked(Fps refreshRate) const {
413 const auto& maxFps = mAppRequestFrameRates.back().fps;
414 return calculateDistanceScoreLocked(maxFps, refreshRate);
415}
416
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400417float RefreshRateSelector::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
418 bool isSeamlessSwitch) const {
Ady Abraham05243be2021-09-16 15:58:52 -0700419 // Slightly prefer seamless switches.
420 constexpr float kSeamedSwitchPenalty = 0.95f;
421 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
422
Rachel Leece6e0042023-06-27 11:22:54 -0700423 if (layer.vote == LayerVoteType::ExplicitCategory) {
Rachel Lee9580ff12023-12-26 17:33:41 -0800424 // HighHint is considered later for touch boost.
425 if (layer.frameRateCategory == FrameRateCategory::HighHint) {
426 return 0.f;
427 }
428
Rachel Leece6e0042023-06-27 11:22:54 -0700429 if (getFrameRateCategoryRange(layer.frameRateCategory).includes(refreshRate)) {
430 return 1.f;
431 }
432
433 FpsRange categoryRange = getFrameRateCategoryRange(layer.frameRateCategory);
434 using fps_approx_ops::operator<;
435 if (refreshRate < categoryRange.min) {
436 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
437 categoryRange.min
438 .getPeriodNsecs());
439 }
440 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
441 categoryRange.max.getPeriodNsecs());
442 }
443
Ady Abraham05243be2021-09-16 15:58:52 -0700444 // If the layer wants Max, give higher score to the higher refresh rate
445 if (layer.vote == LayerVoteType::Max) {
Rachel Leee5514a72023-10-25 16:20:29 -0700446 return calculateDistanceScoreFromMaxLocked(refreshRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800447 }
448
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800449 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800450 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Ady Abraham68636062022-11-16 17:07:25 -0800451 if (supportsAppFrameRateOverrideByContent()) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800452 // Since we support frame rate override, allow refresh rates which are
453 // multiples of the layer's request, as those apps would be throttled
454 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800455 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800456 }
457
Ady Abrahamcc315492022-02-17 17:06:39 -0800458 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800459 }
460
Ady Abrahamcc315492022-02-17 17:06:39 -0800461 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700462 // the highest score.
Rachel Leece6e0042023-06-27 11:22:54 -0700463 if (layer.desiredRefreshRate.isValid() &&
464 getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700465 return 1.0f * seamlessness;
466 }
467
Ady Abrahamcc315492022-02-17 17:06:39 -0800468 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700469 // there is a small penalty attached to the score to favor the frame rates
470 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800471 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700472 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
473 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800474}
475
Ady Abraham68636062022-11-16 17:07:25 -0800476auto RefreshRateSelector::getRankedFrameRates(const std::vector<LayerRequirement>& layers,
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500477 GlobalSignals signals, Fps pacesetterFps) const
478 -> RankedFrameRates {
479 GetRankedFrameRatesCache cache{layers, signals, pacesetterFps};
480
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200481 std::lock_guard lock(mLock);
482
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500483 if (mGetRankedFrameRatesCache && mGetRankedFrameRatesCache->matches(cache)) {
Ady Abraham68636062022-11-16 17:07:25 -0800484 return mGetRankedFrameRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200485 }
486
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500487 cache.result = getRankedFrameRatesLocked(layers, signals, pacesetterFps);
488 mGetRankedFrameRatesCache = std::move(cache);
489 return mGetRankedFrameRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200490}
491
Ady Abraham68636062022-11-16 17:07:25 -0800492auto RefreshRateSelector::getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500493 GlobalSignals signals, Fps pacesetterFps) const
Ady Abraham68636062022-11-16 17:07:25 -0800494 -> RankedFrameRates {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000495 using namespace fps_approx_ops;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800496 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800497 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700498
Ady Abrahamace3d052022-11-17 16:25:05 -0800499 const auto& activeMode = *getActiveModeLocked().modePtr;
ramindani38c84982022-08-29 18:02:57 +0000500
Dominik Laskowski9e88d622024-03-06 17:42:39 -0500501 if (pacesetterFps.isValid()) {
502 ALOGV("Follower display");
503
504 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Descending,
505 std::nullopt, [&](FrameRateMode mode) {
506 return mode.modePtr->getPeakFps() == pacesetterFps;
507 });
508
509 if (!ranking.empty()) {
510 ATRACE_FORMAT_INSTANT("%s (Follower display)",
511 to_string(ranking.front().frameRateMode.fps).c_str());
512
513 return {ranking, kNoSignals, pacesetterFps};
514 }
515
516 ALOGW("Follower display cannot follow the pacesetter");
517 }
518
Ady Abraham68636062022-11-16 17:07:25 -0800519 // Keep the display at max frame rate for the duration of powering on the display.
ramindani38c84982022-08-29 18:02:57 +0000520 if (signals.powerOnImminent) {
521 ALOGV("Power On Imminent");
Ady Abrahamccf63862023-01-19 11:44:01 -0800522 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Descending);
523 ATRACE_FORMAT_INSTANT("%s (Power On Imminent)",
524 to_string(ranking.front().frameRateMode.fps).c_str());
525 return {ranking, GlobalSignals{.powerOnImminent = true}};
ramindani38c84982022-08-29 18:02:57 +0000526 }
527
Ady Abraham8a82ba62020-01-17 12:43:17 -0800528 int noVoteLayers = 0;
Rachel Lee19f01d02024-03-13 20:42:24 -0700529 // Layers that prefer the same mode ("no-op").
530 int noPreferenceLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800531 int minVoteLayers = 0;
532 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800533 int explicitDefaultVoteLayers = 0;
534 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800535 int explicitExact = 0;
Rachel Leee5514a72023-10-25 16:20:29 -0700536 int explicitGteLayers = 0;
Rachel Leece6e0042023-06-27 11:22:54 -0700537 int explicitCategoryVoteLayers = 0;
Rachel Lee9580ff12023-12-26 17:33:41 -0800538 int interactiveLayers = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100539 int seamedFocusedLayers = 0;
Rachel Lee67afbea2023-09-28 15:35:07 -0700540 int categorySmoothSwitchOnlyLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800541
Ady Abraham8a82ba62020-01-17 12:43:17 -0800542 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800543 switch (layer.vote) {
544 case LayerVoteType::NoVote:
545 noVoteLayers++;
546 break;
547 case LayerVoteType::Min:
548 minVoteLayers++;
549 break;
550 case LayerVoteType::Max:
551 maxVoteLayers++;
552 break;
553 case LayerVoteType::ExplicitDefault:
554 explicitDefaultVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800555 break;
556 case LayerVoteType::ExplicitExactOrMultiple:
557 explicitExactOrMultipleVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800558 break;
559 case LayerVoteType::ExplicitExact:
560 explicitExact++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800561 break;
Rachel Leee5514a72023-10-25 16:20:29 -0700562 case LayerVoteType::ExplicitGte:
563 explicitGteLayers++;
564 break;
Rachel Leece6e0042023-06-27 11:22:54 -0700565 case LayerVoteType::ExplicitCategory:
Rachel Lee9580ff12023-12-26 17:33:41 -0800566 if (layer.frameRateCategory == FrameRateCategory::HighHint) {
567 // HighHint does not count as an explicit signal from an app. It may be
568 // be a touch signal.
569 interactiveLayers++;
570 } else {
571 explicitCategoryVoteLayers++;
572 }
Rachel Leef377b362023-09-06 15:01:06 -0700573 if (layer.frameRateCategory == FrameRateCategory::NoPreference) {
Rachel Lee19f01d02024-03-13 20:42:24 -0700574 noPreferenceLayers++;
Rachel Leef377b362023-09-06 15:01:06 -0700575 }
Rachel Leece6e0042023-06-27 11:22:54 -0700576 break;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800577 case LayerVoteType::Heuristic:
578 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800579 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200580
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100581 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
582 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200583 }
Rachel Lee67afbea2023-09-28 15:35:07 -0700584 if (layer.frameRateCategorySmoothSwitchOnly) {
585 categorySmoothSwitchOnlyLayers++;
586 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800587 }
588
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800589 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
Rachel Leee5514a72023-10-25 16:20:29 -0700590 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0 || explicitGteLayers > 0 ||
Rachel Leece6e0042023-06-27 11:22:54 -0700591 explicitCategoryVoteLayers > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700592
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200593 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800594 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700595
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200596 // If the default mode group is different from the group of current mode,
597 // this means a layer requesting a seamed mode switch just disappeared and
598 // we should switch back to the default group.
599 // However if a seamed layer is still present we anchor around the group
600 // of the current mode, in order to prevent unnecessary seamed mode switches
601 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800602 const auto anchorGroup =
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700603 seamedFocusedLayers > 0 ? activeMode.getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200604
Steven Thomasf734df42020-04-13 21:09:28 -0700605 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
606 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800607 if (signals.touch && !hasExplicitVoteLayers) {
ramindanid72ba162022-09-09 21:33:40 +0000608 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800609 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
610 ATRACE_FORMAT_INSTANT("%s (Touch Boost)",
611 to_string(ranking.front().frameRateMode.fps).c_str());
612 return {ranking, GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800613 }
614
Alec Mouri11232a22020-05-14 18:06:25 -0700615 // If the primary range consists of a single refresh rate then we can only
616 // move out the of range if layers explicitly request a different refresh
617 // rate.
Ady Abraham90f7fd22023-08-16 11:02:00 -0700618 if (!signals.touch && signals.idle &&
619 !(policy->primaryRangeIsSingleRate() && hasExplicitVoteLayers)) {
ramindanid72ba162022-09-09 21:33:40 +0000620 ALOGV("Idle");
Ady Abrahamccf63862023-01-19 11:44:01 -0800621 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending);
622 ATRACE_FORMAT_INSTANT("%s (Idle)", to_string(ranking.front().frameRateMode.fps).c_str());
623 return {ranking, GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700624 }
625
Steven Thomasdebafed2020-05-18 17:30:35 -0700626 if (layers.empty() || noVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000627 ALOGV("No layers with votes");
Ady Abrahamccf63862023-01-19 11:44:01 -0800628 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
629 ATRACE_FORMAT_INSTANT("%s (No layers with votes)",
630 to_string(ranking.front().frameRateMode.fps).c_str());
631 return {ranking, kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700632 }
633
Rachel Lee19f01d02024-03-13 20:42:24 -0700634 // If all layers are category NoPreference, use the current config.
635 if (noPreferenceLayers + noVoteLayers == layers.size()) {
636 ALOGV("All layers NoPreference");
637 const auto ascendingWithPreferred =
638 rankFrameRates(anchorGroup, RefreshRateOrder::Ascending, activeMode.getId());
639 ATRACE_FORMAT_INSTANT("%s (All layers NoPreference)",
640 to_string(ascendingWithPreferred.front().frameRateMode.fps).c_str());
641 return {ascendingWithPreferred, kNoSignals};
642 }
643
Rachel Lee67afbea2023-09-28 15:35:07 -0700644 const bool smoothSwitchOnly = categorySmoothSwitchOnlyLayers > 0;
645 const DisplayModeId activeModeId = activeMode.getId();
646
Ady Abraham8a82ba62020-01-17 12:43:17 -0800647 // Only if all layers want Min we should return Min
648 if (noVoteLayers + minVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000649 ALOGV("All layers Min");
Rachel Lee67afbea2023-09-28 15:35:07 -0700650 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending,
651 std::nullopt, [&](FrameRateMode mode) {
652 return !smoothSwitchOnly ||
653 mode.modePtr->getId() == activeModeId;
654 });
Ady Abrahamccf63862023-01-19 11:44:01 -0800655 ATRACE_FORMAT_INSTANT("%s (All layers Min)",
656 to_string(ranking.front().frameRateMode.fps).c_str());
657 return {ranking, kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800658 }
659
Ady Abraham8a82ba62020-01-17 12:43:17 -0800660 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800661 std::vector<RefreshRateScore> scores;
Ady Abraham68636062022-11-16 17:07:25 -0800662 scores.reserve(mAppRequestFrameRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800663
Ady Abraham68636062022-11-16 17:07:25 -0800664 for (const FrameRateMode& it : mAppRequestFrameRates) {
665 scores.emplace_back(RefreshRateScore{it, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800666 }
667
668 for (const auto& layer : layers) {
Rachel Leece6e0042023-06-27 11:22:54 -0700669 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f, category %s) ",
670 layer.name.c_str(), ftl::enum_string(layer.vote).c_str(), layer.weight,
671 layer.desiredRefreshRate.getValue(),
672 ftl::enum_string(layer.frameRateCategory).c_str());
Rachel Leed0694bc2023-09-12 14:57:58 -0700673 if (layer.isNoVote() || layer.frameRateCategory == FrameRateCategory::NoPreference ||
674 layer.vote == LayerVoteType::Min) {
Rachel Lee19f01d02024-03-13 20:42:24 -0700675 ALOGV("%s scoring skipped due to vote", formatLayerInfo(layer, layer.weight).c_str());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800676 continue;
677 }
678
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800679 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800680
Ady Abraham68636062022-11-16 17:07:25 -0800681 for (auto& [mode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
682 const auto& [fps, modePtr] = mode;
683 const bool isSeamlessSwitch = modePtr->getGroup() == activeMode.getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200684
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100685 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100686 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800687 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700688 to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200689 continue;
690 }
691
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100692 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
693 !layer.focused) {
694 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100695 " Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800696 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700697 to_string(activeMode).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100698 continue;
699 }
700
Rachel Lee67afbea2023-09-28 15:35:07 -0700701 if (smoothSwitchOnly && modePtr->getId() != activeModeId) {
702 ALOGV("%s ignores %s because it's non-VRR and smooth switch only."
703 " Current mode = %s",
704 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
705 to_string(activeMode).c_str());
706 continue;
707 }
708
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100709 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100710 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100711 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100712 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
713 // disappeared.
Ady Abraham68636062022-11-16 17:07:25 -0800714 const bool isInPolicyForDefault = modePtr->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100715 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100716 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham68636062022-11-16 17:07:25 -0800717 to_string(*modePtr).c_str(), to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200718 continue;
719 }
720
Ady Abraham90f7fd22023-08-16 11:02:00 -0700721 const bool inPrimaryPhysicalRange =
ramindania04b8a52023-08-07 18:49:47 -0700722 policy->primaryRanges.physical.includes(modePtr->getPeakFps());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700723 const bool inPrimaryRenderRange = policy->primaryRanges.render.includes(fps);
724 if (((policy->primaryRangeIsSingleRate() && !inPrimaryPhysicalRange) ||
725 !inPrimaryRenderRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800726 !(layer.focused &&
727 (layer.vote == LayerVoteType::ExplicitDefault ||
728 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700729 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700730 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700731 continue;
732 }
733
Ady Abraham68636062022-11-16 17:07:25 -0800734 const float layerScore = calculateLayerScoreLocked(layer, fps, isSeamlessSwitch);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000735 const float weightedLayerScore = weight * layerScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800736
Ady Abraham13cfb362022-08-13 05:12:13 +0000737 // Layer with fixed source has a special consideration which depends on the
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000738 // mConfig.frameRateMultipleThreshold. We don't want these layers to score
739 // refresh rates above the threshold, but we also don't want to favor the lower
740 // ones by having a greater number of layers scoring them. Instead, we calculate
741 // the score independently for these layers and later decide which
742 // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
743 // score 120 Hz, but desired 60 fps should contribute to the score.
744 const bool fixedSourceLayer = [](LayerVoteType vote) {
745 switch (vote) {
746 case LayerVoteType::ExplicitExactOrMultiple:
747 case LayerVoteType::Heuristic:
748 return true;
749 case LayerVoteType::NoVote:
750 case LayerVoteType::Min:
751 case LayerVoteType::Max:
752 case LayerVoteType::ExplicitDefault:
753 case LayerVoteType::ExplicitExact:
Rachel Leee5514a72023-10-25 16:20:29 -0700754 case LayerVoteType::ExplicitGte:
Rachel Leece6e0042023-06-27 11:22:54 -0700755 case LayerVoteType::ExplicitCategory:
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000756 return false;
757 }
758 }(layer.vote);
Ady Abraham62f51d92022-08-24 22:20:22 +0000759 const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000760 layer.desiredRefreshRate <
761 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
Ady Abraham62f51d92022-08-24 22:20:22 +0000762 if (fixedSourceLayer && layerBelowThreshold) {
Ady Abraham13cfb362022-08-13 05:12:13 +0000763 const bool modeAboveThreshold =
ramindania04b8a52023-08-07 18:49:47 -0700764 modePtr->getPeakFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
Ady Abraham62f51d92022-08-24 22:20:22 +0000765 if (modeAboveThreshold) {
ramindania04b8a52023-08-07 18:49:47 -0700766 ALOGV("%s gives %s (%s(%s)) fixed source (above threshold) score of %.4f",
Ady Abraham68636062022-11-16 17:07:25 -0800767 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700768 to_string(modePtr->getPeakFps()).c_str(),
769 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000770 fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000771 } else {
ramindania04b8a52023-08-07 18:49:47 -0700772 ALOGV("%s gives %s (%s(%s)) fixed source (below threshold) score of %.4f",
Ady Abraham68636062022-11-16 17:07:25 -0800773 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700774 to_string(modePtr->getPeakFps()).c_str(),
775 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000776 fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000777 }
778 } else {
ramindania04b8a52023-08-07 18:49:47 -0700779 ALOGV("%s gives %s (%s(%s)) score of %.4f", formatLayerInfo(layer, weight).c_str(),
780 to_string(fps).c_str(), to_string(modePtr->getPeakFps()).c_str(),
781 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000782 overallScore += weightedLayerScore;
783 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800784 }
785 }
786
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000787 // We want to find the best refresh rate without the fixed source layers,
Ady Abraham62f51d92022-08-24 22:20:22 +0000788 // so we could know whether we should add the modeAboveThreshold scores or not.
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000789 // If the best refresh rate is already above the threshold, it means that
790 // some non-fixed source layers already scored it, so we can just add the score
791 // for all fixed source layers, even the ones that are above the threshold.
792 const bool maxScoreAboveThreshold = [&] {
793 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
794 return false;
795 }
796
797 const auto maxScoreIt =
798 std::max_element(scores.begin(), scores.end(),
799 [](RefreshRateScore max, RefreshRateScore current) {
Ady Abraham68636062022-11-16 17:07:25 -0800800 return current.overallScore > max.overallScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000801 });
ramindania04b8a52023-08-07 18:49:47 -0700802 ALOGV("%s (%s(%s)) is the best refresh rate without fixed source layers. It is %s the "
Ady Abraham68636062022-11-16 17:07:25 -0800803 "threshold for "
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000804 "refresh rate multiples",
Ady Abraham68636062022-11-16 17:07:25 -0800805 to_string(maxScoreIt->frameRateMode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700806 to_string(maxScoreIt->frameRateMode.modePtr->getPeakFps()).c_str(),
807 to_string(maxScoreIt->frameRateMode.modePtr->getVsyncRate()).c_str(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000808 maxScoreAboveThreshold ? "above" : "below");
ramindania04b8a52023-08-07 18:49:47 -0700809 return maxScoreIt->frameRateMode.modePtr->getPeakFps() >=
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000810 Fps::fromValue(mConfig.frameRateMultipleThreshold);
811 }();
812
813 // Now we can add the fixed rate layers score
Ady Abraham68636062022-11-16 17:07:25 -0800814 for (auto& [frameRateMode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000815 overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000816 if (maxScoreAboveThreshold) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000817 overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000818 }
ramindania04b8a52023-08-07 18:49:47 -0700819 ALOGV("%s (%s(%s)) adjusted overallScore is %.4f", to_string(frameRateMode.fps).c_str(),
820 to_string(frameRateMode.modePtr->getPeakFps()).c_str(),
821 to_string(frameRateMode.modePtr->getVsyncRate()).c_str(), overallScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000822 }
823
824 // Now that we scored all the refresh rates we need to pick the one that got the highest
ramindanid72ba162022-09-09 21:33:40 +0000825 // overallScore. Sort the scores based on their overallScore in descending order of priority.
826 const RefreshRateOrder refreshRateOrder =
827 maxVoteLayers > 0 ? RefreshRateOrder::Descending : RefreshRateOrder::Ascending;
828 std::sort(scores.begin(), scores.end(),
829 RefreshRateScoreComparator{.refreshRateOrder = refreshRateOrder});
ramindanid72ba162022-09-09 21:33:40 +0000830
Ady Abraham68636062022-11-16 17:07:25 -0800831 FrameRateRanking ranking;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400832 ranking.reserve(scores.size());
833
834 std::transform(scores.begin(), scores.end(), back_inserter(ranking),
ramindanid72ba162022-09-09 21:33:40 +0000835 [](const RefreshRateScore& score) {
Ady Abraham68636062022-11-16 17:07:25 -0800836 return ScoredFrameRate{score.frameRateMode, score.overallScore};
ramindanid72ba162022-09-09 21:33:40 +0000837 });
Ady Abraham34702102020-02-10 14:12:05 -0800838
Ady Abraham37d46922022-10-05 13:08:51 -0700839 const bool noLayerScore = std::all_of(scores.begin(), scores.end(), [](RefreshRateScore score) {
840 return score.overallScore == 0;
841 });
842
Ady Abraham90f7fd22023-08-16 11:02:00 -0700843 if (policy->primaryRangeIsSingleRate()) {
Alec Mouri11232a22020-05-14 18:06:25 -0700844 // If we never scored any layers, then choose the rate from the primary
845 // range instead of picking a random score from the app range.
Ady Abraham37d46922022-10-05 13:08:51 -0700846 if (noLayerScore) {
ramindanid72ba162022-09-09 21:33:40 +0000847 ALOGV("Layers not scored");
Ady Abrahamccf63862023-01-19 11:44:01 -0800848 const auto descending = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
849 ATRACE_FORMAT_INSTANT("%s (Layers not scored)",
850 to_string(descending.front().frameRateMode.fps).c_str());
851 return {descending, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700852 } else {
Rachel Lee67afbea2023-09-28 15:35:07 -0700853 ALOGV("primaryRangeIsSingleRate");
Ady Abrahamccf63862023-01-19 11:44:01 -0800854 ATRACE_FORMAT_INSTANT("%s (primaryRangeIsSingleRate)",
855 to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400856 return {ranking, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700857 }
858 }
859
Steven Thomasf734df42020-04-13 21:09:28 -0700860 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
861 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
862 // vote we should not change it if we get a touch event. Only apply touch boost if it will
863 // actually increase the refresh rate over the normal selection.
Dominik Laskowski788cba82024-03-15 11:29:11 -0400864 const auto isTouchBoostForExplicitExact = [&]() -> bool {
Ady Abraham68636062022-11-16 17:07:25 -0800865 if (supportsAppFrameRateOverrideByContent()) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700866 // Enable touch boost if there are other layers besides exact
Ady Abraham52ad61c2024-03-06 11:39:35 -0800867 return explicitExact + noVoteLayers + explicitGteLayers != layers.size();
Ady Abraham5e4e9832021-06-14 13:40:56 -0700868 } else {
869 // Enable touch boost if there are no exact layers
870 return explicitExact == 0;
871 }
Dominik Laskowski788cba82024-03-15 11:29:11 -0400872 };
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700873
Dominik Laskowski788cba82024-03-15 11:29:11 -0400874 const auto isTouchBoostForCategory = [&]() -> bool {
875 return explicitCategoryVoteLayers + noVoteLayers + explicitGteLayers != layers.size();
876 };
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700877
Rachel Lee9e2416c2024-01-23 15:03:57 -0800878 // A method for UI Toolkit to send the touch signal via "HighHint" category vote,
879 // which will touch boost when there are no ExplicitDefault layer votes. This is an
880 // incomplete solution but accounts for cases such as games that use `setFrameRate` with default
881 // compatibility to limit the frame rate, which should not have touch boost.
Rachel Lee9580ff12023-12-26 17:33:41 -0800882 const bool hasInteraction = signals.touch || interactiveLayers > 0;
Rachel Lee9e2416c2024-01-23 15:03:57 -0800883
Dominik Laskowski788cba82024-03-15 11:29:11 -0400884 if (hasInteraction && explicitDefaultVoteLayers == 0 && isTouchBoostForExplicitExact() &&
885 isTouchBoostForCategory()) {
886 const auto touchRefreshRates = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
887 using fps_approx_ops::operator<;
888
889 if (scores.front().frameRateMode.fps < touchRefreshRates.front().frameRateMode.fps) {
890 ALOGV("Touch Boost");
891 ATRACE_FORMAT_INSTANT("%s (Touch Boost [late])",
892 to_string(touchRefreshRates.front().frameRateMode.fps).c_str());
893 return {touchRefreshRates, GlobalSignals{.touch = true}};
894 }
Steven Thomasf734df42020-04-13 21:09:28 -0700895 }
896
Ady Abraham37d46922022-10-05 13:08:51 -0700897 // If we never scored any layers, and we don't favor high refresh rates, prefer to stay with the
898 // current config
899 if (noLayerScore && refreshRateOrder == RefreshRateOrder::Ascending) {
Rachel Lee67afbea2023-09-28 15:35:07 -0700900 ALOGV("preferredDisplayMode");
Ady Abrahamccf63862023-01-19 11:44:01 -0800901 const auto ascendingWithPreferred =
902 rankFrameRates(anchorGroup, RefreshRateOrder::Ascending, activeMode.getId());
903 ATRACE_FORMAT_INSTANT("%s (preferredDisplayMode)",
904 to_string(ascendingWithPreferred.front().frameRateMode.fps).c_str());
905 return {ascendingWithPreferred, kNoSignals};
Ady Abraham37d46922022-10-05 13:08:51 -0700906 }
907
Dominik Laskowski788cba82024-03-15 11:29:11 -0400908 ALOGV("%s (scored)", to_string(ranking.front().frameRateMode.fps).c_str());
909 ATRACE_FORMAT_INSTANT("%s (scored)", to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400910 return {ranking, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800911}
912
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400913using LayerRequirementPtrs = std::vector<const RefreshRateSelector::LayerRequirement*>;
914using PerUidLayerRequirements = std::unordered_map<uid_t, LayerRequirementPtrs>;
915
916PerUidLayerRequirements groupLayersByUid(
917 const std::vector<RefreshRateSelector::LayerRequirement>& layers) {
918 PerUidLayerRequirements layersByUid;
Ady Abraham62a0be22020-12-08 16:54:10 -0800919 for (const auto& layer : layers) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400920 const auto it = layersByUid.emplace(layer.ownerUid, LayerRequirementPtrs()).first;
921 auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800922 layersWithSameUid.push_back(&layer);
923 }
924
925 // Remove uids that can't have a frame rate override
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400926 for (auto it = layersByUid.begin(); it != layersByUid.end();) {
927 const auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800928 bool skipUid = false;
929 for (const auto& layer : layersWithSameUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400930 using LayerVoteType = RefreshRateSelector::LayerVoteType;
931
932 if (layer->vote == LayerVoteType::Max || layer->vote == LayerVoteType::Heuristic) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800933 skipUid = true;
934 break;
935 }
936 }
937 if (skipUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400938 it = layersByUid.erase(it);
Ady Abraham62a0be22020-12-08 16:54:10 -0800939 } else {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400940 ++it;
Ady Abraham62a0be22020-12-08 16:54:10 -0800941 }
942 }
943
944 return layersByUid;
945}
946
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400947auto RefreshRateSelector::getFrameRateOverrides(const std::vector<LayerRequirement>& layers,
948 Fps displayRefreshRate,
949 GlobalSignals globalSignals) const
950 -> UidToFrameRateOverride {
Ady Abraham62a0be22020-12-08 16:54:10 -0800951 ATRACE_CALL();
Ady Abraham68636062022-11-16 17:07:25 -0800952 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Disabled) {
953 return {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800954 }
955
Ady Abraham68636062022-11-16 17:07:25 -0800956 ALOGV("%s: %zu layers", __func__, layers.size());
957 std::lock_guard lock(mLock);
958
Ady Abraham8ca643a2022-10-18 18:26:47 -0700959 const auto* policyPtr = getCurrentPolicyLocked();
960 // We don't want to run lower than 30fps
ramindania04b8a52023-08-07 18:49:47 -0700961 // TODO(b/297600226): revise this for dVRR
Ady Abraham8ca643a2022-10-18 18:26:47 -0700962 const Fps minFrameRate = std::max(policyPtr->appRequestRanges.render.min, 30_Hz, isApproxLess);
963
964 using fps_approx_ops::operator/;
965 const unsigned numMultiples = displayRefreshRate / minFrameRate;
966
967 std::vector<std::pair<Fps, float>> scoredFrameRates;
968 scoredFrameRates.reserve(numMultiples);
969
970 for (unsigned n = numMultiples; n > 0; n--) {
971 const Fps divisor = displayRefreshRate / n;
972 if (mConfig.enableFrameRateOverride ==
Ady Abraham68636062022-11-16 17:07:25 -0800973 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
974 !isNativeRefreshRate(divisor)) {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700975 continue;
976 }
977
978 if (policyPtr->appRequestRanges.render.includes(divisor)) {
979 ALOGV("%s: adding %s as a potential frame rate", __func__, to_string(divisor).c_str());
980 scoredFrameRates.emplace_back(divisor, 0);
981 }
982 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800983
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400984 const auto layersByUid = groupLayersByUid(layers);
Ady Abraham62a0be22020-12-08 16:54:10 -0800985 UidToFrameRateOverride frameRateOverrides;
986 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Rachel Lee93bec072024-02-23 17:29:34 -0800987 // Look for cases that should not have frame rate overrides.
988 bool hasExplicitExactOrMultiple = false;
989 bool hasExplicitDefault = false;
990 bool hasHighHint = false;
991 for (const auto& layer : layersWithSameUid) {
992 switch (layer->vote) {
993 case LayerVoteType::ExplicitExactOrMultiple:
994 hasExplicitExactOrMultiple = true;
995 break;
996 case LayerVoteType::ExplicitDefault:
997 hasExplicitDefault = true;
998 break;
999 case LayerVoteType::ExplicitCategory:
1000 if (layer->frameRateCategory == FrameRateCategory::HighHint) {
1001 hasHighHint = true;
1002 }
1003 break;
1004 default:
1005 // No action
1006 break;
1007 }
1008 if (hasExplicitExactOrMultiple && hasExplicitDefault && hasHighHint) {
1009 break;
1010 }
1011 }
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001012
Rachel Lee93bec072024-02-23 17:29:34 -08001013 // Layers with ExplicitExactOrMultiple expect touch boost
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001014 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001015 continue;
1016 }
1017
Rachel Lee93bec072024-02-23 17:29:34 -08001018 // Mirrors getRankedFrameRates. If there is no ExplicitDefault, expect touch boost and
1019 // skip frame rate override.
1020 if (hasHighHint && !hasExplicitDefault) {
1021 continue;
1022 }
1023
Ady Abraham8ca643a2022-10-18 18:26:47 -07001024 for (auto& [_, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001025 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -08001026 }
1027
1028 for (const auto& layer : layersWithSameUid) {
Rachel Lee47adfcf2023-09-15 17:36:56 -07001029 if (layer->isNoVote() || layer->frameRateCategory == FrameRateCategory::NoPreference ||
1030 layer->vote == LayerVoteType::Min) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001031 continue;
1032 }
1033
1034 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Rachel Leece6e0042023-06-27 11:22:54 -07001035 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
1036 layer->vote != LayerVoteType::ExplicitExact &&
Rachel Leeef9fb682024-02-23 11:04:33 -08001037 layer->vote != LayerVoteType::ExplicitGte &&
Rachel Leece6e0042023-06-27 11:22:54 -07001038 layer->vote != LayerVoteType::ExplicitCategory,
1039 "Invalid layer vote type for frame rate overrides");
Ady Abraham8ca643a2022-10-18 18:26:47 -07001040 for (auto& [fps, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001041 constexpr bool isSeamlessSwitch = true;
Ady Abraham8ca643a2022-10-18 18:26:47 -07001042 const auto layerScore = calculateLayerScoreLocked(*layer, fps, isSeamlessSwitch);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001043 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -08001044 }
1045 }
1046
Ady Abraham62a0be22020-12-08 16:54:10 -08001047 // If we never scored any layers, we don't have a preferred frame rate
Ady Abraham8ca643a2022-10-18 18:26:47 -07001048 if (std::all_of(scoredFrameRates.begin(), scoredFrameRates.end(),
1049 [](const auto& scoredFrameRate) {
1050 const auto [_, score] = scoredFrameRate;
1051 return score == 0;
1052 })) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001053 continue;
1054 }
1055
ramindanid72ba162022-09-09 21:33:40 +00001056 // Now that we scored all the refresh rates we need to pick the lowest refresh rate
1057 // that got the highest score.
Ady Abraham8ca643a2022-10-18 18:26:47 -07001058 const auto [overrideFps, _] =
1059 *std::max_element(scoredFrameRates.begin(), scoredFrameRates.end(),
1060 [](const auto& lhsPair, const auto& rhsPair) {
1061 const float lhs = lhsPair.second;
1062 const float rhs = rhsPair.second;
Ady Abraham68636062022-11-16 17:07:25 -08001063 return lhs < rhs && !ScoredFrameRate::scoresEqual(lhs, rhs);
Ady Abraham8ca643a2022-10-18 18:26:47 -07001064 });
1065 ALOGV("%s: overriding to %s for uid=%d", __func__, to_string(overrideFps).c_str(), uid);
Ady Abraham822ecbd2023-07-07 16:16:09 -07001066 ATRACE_FORMAT_INSTANT("%s: overriding to %s for uid=%d", __func__,
1067 to_string(overrideFps).c_str(), uid);
Ady Abraham8ca643a2022-10-18 18:26:47 -07001068 frameRateOverrides.emplace(uid, overrideFps);
Ady Abraham62a0be22020-12-08 16:54:10 -08001069 }
1070
1071 return frameRateOverrides;
1072}
1073
Ady Abraham0aa373a2022-11-22 13:56:50 -08001074ftl::Optional<FrameRateMode> RefreshRateSelector::onKernelTimerChanged(
Dominik Laskowski59746512023-11-19 09:30:24 -05001075 ftl::Optional<DisplayModeId> desiredModeIdOpt, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -08001076 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001077
Dominik Laskowski61651552023-11-19 10:06:19 -05001078 const auto current =
1079 desiredModeIdOpt
1080 .and_then([this](DisplayModeId modeId)
1081 REQUIRES(mLock) { return mDisplayModes.get(modeId); })
1082 .transform([](const DisplayModePtr& modePtr) {
1083 return FrameRateMode{modePtr->getPeakFps(), ftl::as_non_null(modePtr)};
1084 })
1085 .or_else([this] {
1086 ftl::FakeGuard guard(mLock);
1087 return std::make_optional(getActiveModeLocked());
1088 })
1089 .value();
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001090
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001091 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
Ady Abraham0aa373a2022-11-22 13:56:50 -08001092 if (current.modePtr->getId() == min->getId()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001093 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001094 }
1095
ramindania04b8a52023-08-07 18:49:47 -07001096 return timerExpired ? FrameRateMode{min->getPeakFps(), ftl::as_non_null(min)} : current;
Steven Thomasf734df42020-04-13 21:09:28 -07001097}
1098
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001099const DisplayModePtr& RefreshRateSelector::getMinRefreshRateByPolicyLocked() const {
Ady Abrahamace3d052022-11-17 16:25:05 -08001100 const auto& activeMode = *getActiveModeLocked().modePtr;
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001101
Ady Abraham68636062022-11-16 17:07:25 -08001102 for (const FrameRateMode& mode : mPrimaryFrameRates) {
1103 if (activeMode.getGroup() == mode.modePtr->getGroup()) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001104 return mode.modePtr.get();
Marin Shalamanov46084422020-10-13 12:33:42 +02001105 }
1106 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001107
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001108 ALOGE("Can't find min refresh rate by policy with the same mode group as the current mode %s",
1109 to_string(activeMode).c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001110
1111 // Default to the lowest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -08001112 return mPrimaryFrameRates.front().modePtr.get();
Ady Abraham2139f732019-11-13 18:56:40 -08001113}
1114
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001115const DisplayModePtr& RefreshRateSelector::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Ady Abrahamace3d052022-11-17 16:25:05 -08001116 const ftl::NonNull<DisplayModePtr>* maxByAnchor = &mPrimaryFrameRates.back().modePtr;
1117 const ftl::NonNull<DisplayModePtr>* max = &mPrimaryFrameRates.back().modePtr;
Ady Abraham68636062022-11-16 17:07:25 -08001118
1119 bool maxByAnchorFound = false;
1120 for (auto it = mPrimaryFrameRates.rbegin(); it != mPrimaryFrameRates.rend(); ++it) {
1121 using namespace fps_approx_ops;
ramindania04b8a52023-08-07 18:49:47 -07001122 if (it->modePtr->getPeakFps() > (*max)->getPeakFps()) {
Ady Abraham68636062022-11-16 17:07:25 -08001123 max = &it->modePtr;
Marin Shalamanov46084422020-10-13 12:33:42 +02001124 }
Ady Abraham68636062022-11-16 17:07:25 -08001125
1126 if (anchorGroup == it->modePtr->getGroup() &&
ramindania04b8a52023-08-07 18:49:47 -07001127 it->modePtr->getPeakFps() >= (*maxByAnchor)->getPeakFps()) {
Ady Abraham68636062022-11-16 17:07:25 -08001128 maxByAnchorFound = true;
1129 maxByAnchor = &it->modePtr;
1130 }
1131 }
1132
1133 if (maxByAnchorFound) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001134 return maxByAnchor->get();
Marin Shalamanov46084422020-10-13 12:33:42 +02001135 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001136
ramindanid72ba162022-09-09 21:33:40 +00001137 ALOGE("Can't find max refresh rate by policy with the same group %d", anchorGroup);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001138
1139 // Default to the highest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -08001140 return max->get();
Ady Abraham2139f732019-11-13 18:56:40 -08001141}
1142
Ady Abraham68636062022-11-16 17:07:25 -08001143auto RefreshRateSelector::rankFrameRates(std::optional<int> anchorGroupOpt,
1144 RefreshRateOrder refreshRateOrder,
Rachel Lee67afbea2023-09-28 15:35:07 -07001145 std::optional<DisplayModeId> preferredDisplayModeOpt,
1146 const RankFrameRatesPredicate& predicate) const
Ady Abraham68636062022-11-16 17:07:25 -08001147 -> FrameRateRanking {
Ady Abrahama5992df2023-01-27 21:10:57 -08001148 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -08001149 const char* const whence = __func__;
Ady Abrahama5992df2023-01-27 21:10:57 -08001150
1151 // find the highest frame rate for each display mode
1152 ftl::SmallMap<DisplayModeId, Fps, 8> maxRenderRateForMode;
1153 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
1154 if (ascending) {
1155 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1156 // use a lower frame rate when we want Ascending frame rates.
1157 for (const auto& frameRateMode : mPrimaryFrameRates) {
1158 if (anchorGroupOpt && frameRateMode.modePtr->getGroup() != anchorGroupOpt) {
1159 continue;
1160 }
1161
1162 const auto [iter, _] = maxRenderRateForMode.try_emplace(frameRateMode.modePtr->getId(),
1163 frameRateMode.fps);
1164 if (iter->second < frameRateMode.fps) {
1165 iter->second = frameRateMode.fps;
1166 }
1167 }
1168 }
1169
Ady Abraham68636062022-11-16 17:07:25 -08001170 std::deque<ScoredFrameRate> ranking;
1171 const auto rankFrameRate = [&](const FrameRateMode& frameRateMode) REQUIRES(mLock) {
1172 const auto& modePtr = frameRateMode.modePtr;
Rachel Lee67afbea2023-09-28 15:35:07 -07001173 if ((anchorGroupOpt && modePtr->getGroup() != anchorGroupOpt) ||
1174 !predicate(frameRateMode)) {
Ady Abraham37d46922022-10-05 13:08:51 -07001175 return;
ramindanid72ba162022-09-09 21:33:40 +00001176 }
Ady Abraham37d46922022-10-05 13:08:51 -07001177
Ady Abraham3f965922023-01-23 17:18:29 -08001178 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
ramindanif7075202023-03-10 00:24:34 +00001179 const auto id = modePtr->getId();
Ady Abrahama5992df2023-01-27 21:10:57 -08001180 if (ascending && frameRateMode.fps < *maxRenderRateForMode.get(id)) {
Ady Abraham3f965922023-01-23 17:18:29 -08001181 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1182 // use a lower frame rate when we want Ascending frame rates.
1183 return;
1184 }
1185
Rachel Leee5514a72023-10-25 16:20:29 -07001186 float score = calculateDistanceScoreFromMaxLocked(frameRateMode.fps);
Ady Abraham3f965922023-01-23 17:18:29 -08001187
1188 if (ascending) {
Ady Abraham37d46922022-10-05 13:08:51 -07001189 score = 1.0f / score;
1190 }
ramindanif7075202023-03-10 00:24:34 +00001191
1192 constexpr float kScore = std::numeric_limits<float>::max();
Ady Abraham37d46922022-10-05 13:08:51 -07001193 if (preferredDisplayModeOpt) {
Ady Abraham68636062022-11-16 17:07:25 -08001194 if (*preferredDisplayModeOpt == modePtr->getId()) {
Ady Abraham68636062022-11-16 17:07:25 -08001195 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
Ady Abraham37d46922022-10-05 13:08:51 -07001196 return;
1197 }
1198 constexpr float kNonPreferredModePenalty = 0.95f;
1199 score *= kNonPreferredModePenalty;
ramindanif7075202023-03-10 00:24:34 +00001200 } else if (ascending && id == getMinRefreshRateByPolicyLocked()->getId()) {
1201 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround
1202 // and actually use a lower frame rate when we want Ascending frame rates.
1203 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
1204 return;
Ady Abraham37d46922022-10-05 13:08:51 -07001205 }
Ady Abraham3f965922023-01-23 17:18:29 -08001206
ramindania04b8a52023-08-07 18:49:47 -07001207 ALOGV("%s(%s) %s (%s(%s)) scored %.2f", whence, ftl::enum_string(refreshRateOrder).c_str(),
1208 to_string(frameRateMode.fps).c_str(), to_string(modePtr->getPeakFps()).c_str(),
1209 to_string(modePtr->getVsyncRate()).c_str(), score);
Ady Abraham68636062022-11-16 17:07:25 -08001210 ranking.emplace_back(ScoredFrameRate{frameRateMode, score});
ramindanid72ba162022-09-09 21:33:40 +00001211 };
1212
1213 if (refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abraham68636062022-11-16 17:07:25 -08001214 std::for_each(mPrimaryFrameRates.begin(), mPrimaryFrameRates.end(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001215 } else {
Ady Abraham68636062022-11-16 17:07:25 -08001216 std::for_each(mPrimaryFrameRates.rbegin(), mPrimaryFrameRates.rend(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001217 }
1218
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001219 if (!ranking.empty() || !anchorGroupOpt) {
1220 return {ranking.begin(), ranking.end()};
ramindanid72ba162022-09-09 21:33:40 +00001221 }
1222
1223 ALOGW("Can't find %s refresh rate by policy with the same mode group"
1224 " as the mode group %d",
1225 refreshRateOrder == RefreshRateOrder::Ascending ? "min" : "max", anchorGroupOpt.value());
1226
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001227 constexpr std::optional<int> kNoAnchorGroup = std::nullopt;
Ady Abraham68636062022-11-16 17:07:25 -08001228 return rankFrameRates(kNoAnchorGroup, refreshRateOrder, preferredDisplayModeOpt);
ramindanid72ba162022-09-09 21:33:40 +00001229}
1230
Ady Abrahamace3d052022-11-17 16:25:05 -08001231FrameRateMode RefreshRateSelector::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -08001232 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001233 return getActiveModeLocked();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001234}
1235
Ady Abrahamace3d052022-11-17 16:25:05 -08001236const FrameRateMode& RefreshRateSelector::getActiveModeLocked() const {
1237 return *mActiveModeOpt;
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001238}
1239
Ady Abrahamace3d052022-11-17 16:25:05 -08001240void RefreshRateSelector::setActiveMode(DisplayModeId modeId, Fps renderFrameRate) {
Ady Abraham2139f732019-11-13 18:56:40 -08001241 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001242
Ady Abraham68636062022-11-16 17:07:25 -08001243 // Invalidate the cached invocation to getRankedFrameRates. This forces
1244 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1245 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001246
Ady Abrahamace3d052022-11-17 16:25:05 -08001247 const auto activeModeOpt = mDisplayModes.get(modeId);
1248 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1249
1250 mActiveModeOpt.emplace(FrameRateMode{renderFrameRate, ftl::as_non_null(activeModeOpt->get())});
Rachel Lee45681982024-03-14 18:40:15 -07001251 mIsVrrDevice = FlagManager::getInstance().vrr_config() &&
1252 activeModeOpt->get()->getVrrConfig().has_value();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001253}
1254
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001255RefreshRateSelector::RefreshRateSelector(DisplayModes modes, DisplayModeId activeModeId,
1256 Config config)
rnlee3bd610662021-06-23 16:27:57 -07001257 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001258 initializeIdleTimer();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001259 FTL_FAKE_GUARD(kMainThreadContext, updateDisplayModes(std::move(modes), activeModeId));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001260}
1261
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001262void RefreshRateSelector::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +00001263 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001264 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +00001265 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001266 [this] {
1267 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1268 if (const auto callbacks = getIdleTimerCallbacks()) {
1269 callbacks->onReset();
1270 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001271 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001272 [this] {
1273 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1274 if (const auto callbacks = getIdleTimerCallbacks()) {
1275 callbacks->onExpired();
1276 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001277 });
Ady Abraham9a2ea342021-09-03 17:32:34 -07001278 }
1279}
1280
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001281void RefreshRateSelector::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001282 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001283
Ady Abraham68636062022-11-16 17:07:25 -08001284 // Invalidate the cached invocation to getRankedFrameRates. This forces
1285 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1286 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001287
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001288 mDisplayModes = std::move(modes);
Ady Abrahamace3d052022-11-17 16:25:05 -08001289 const auto activeModeOpt = mDisplayModes.get(activeModeId);
1290 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
ramindania04b8a52023-08-07 18:49:47 -07001291 mActiveModeOpt = FrameRateMode{activeModeOpt->get()->getPeakFps(),
1292 ftl::as_non_null(activeModeOpt->get())};
Ady Abrahamabc27602020-04-08 17:20:29 -07001293
Ady Abraham68636062022-11-16 17:07:25 -08001294 const auto sortedModes = sortByRefreshRate(mDisplayModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001295 mMinRefreshRateModeIt = sortedModes.front();
1296 mMaxRefreshRateModeIt = sortedModes.back();
1297
Marin Shalamanov75f37252021-02-10 21:43:57 +01001298 // Reset the policy because the old one may no longer be valid.
1299 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001300 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -08001301
Ady Abraham8ca643a2022-10-18 18:26:47 -07001302 mFrameRateOverrideConfig = [&] {
1303 switch (mConfig.enableFrameRateOverride) {
1304 case Config::FrameRateOverride::Disabled:
Ady Abraham68636062022-11-16 17:07:25 -08001305 case Config::FrameRateOverride::AppOverride:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001306 case Config::FrameRateOverride::Enabled:
1307 return mConfig.enableFrameRateOverride;
Ady Abraham68636062022-11-16 17:07:25 -08001308 case Config::FrameRateOverride::AppOverrideNativeRefreshRates:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001309 return shouldEnableFrameRateOverride(sortedModes)
Ady Abraham68636062022-11-16 17:07:25 -08001310 ? Config::FrameRateOverride::AppOverrideNativeRefreshRates
Ady Abraham8ca643a2022-10-18 18:26:47 -07001311 : Config::FrameRateOverride::Disabled;
1312 }
1313 }();
Ady Abraham4899ff82021-01-06 13:53:29 -08001314
Ady Abraham68636062022-11-16 17:07:25 -08001315 if (mConfig.enableFrameRateOverride ==
1316 Config::FrameRateOverride::AppOverrideNativeRefreshRates) {
1317 for (const auto& [_, mode] : mDisplayModes) {
ramindania04b8a52023-08-07 18:49:47 -07001318 mAppOverrideNativeRefreshRates.try_emplace(mode->getPeakFps(), ftl::unit);
Ady Abraham68636062022-11-16 17:07:25 -08001319 }
1320 }
1321
Ady Abrahamabc27602020-04-08 17:20:29 -07001322 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001323}
1324
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001325bool RefreshRateSelector::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001326 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001327 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
ramindania04b8a52023-08-07 18:49:47 -07001328 if (!policy.primaryRanges.physical.includes(mode->get()->getPeakFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001329 ALOGE("Default mode is not in the primary range.");
1330 return false;
1331 }
1332 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001333 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -07001334 return false;
1335 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001336
Ady Abraham68636062022-11-16 17:07:25 -08001337 const auto& primaryRanges = policy.primaryRanges;
1338 const auto& appRequestRanges = policy.appRequestRanges;
1339 ALOGE_IF(!appRequestRanges.physical.includes(primaryRanges.physical),
Ady Abraham08048ce2022-11-30 18:08:00 -08001340 "Physical range is invalid: primary: %s appRequest: %s",
1341 to_string(primaryRanges.physical).c_str(),
1342 to_string(appRequestRanges.physical).c_str());
1343 ALOGE_IF(!appRequestRanges.render.includes(primaryRanges.render),
1344 "Render range is invalid: primary: %s appRequest: %s",
1345 to_string(primaryRanges.render).c_str(), to_string(appRequestRanges.render).c_str());
Ady Abraham68636062022-11-16 17:07:25 -08001346
1347 return primaryRanges.valid() && appRequestRanges.valid();
Steven Thomasd4071902020-03-24 16:02:53 -07001348}
1349
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001350auto RefreshRateSelector::setPolicy(const PolicyVariant& policy) -> SetPolicyResult {
Dominik Laskowski36dced82022-09-02 09:24:00 -07001351 Policy oldPolicy;
Ady Abrahamace3d052022-11-17 16:25:05 -08001352 PhysicalDisplayId displayId;
Dominik Laskowski36dced82022-09-02 09:24:00 -07001353 {
1354 std::lock_guard lock(mLock);
1355 oldPolicy = *getCurrentPolicyLocked();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001356
Dominik Laskowski36dced82022-09-02 09:24:00 -07001357 const bool valid = ftl::match(
1358 policy,
1359 [this](const auto& policy) {
1360 ftl::FakeGuard guard(mLock);
1361 if (!isPolicyValidLocked(policy)) {
1362 ALOGE("Invalid policy: %s", policy.toString().c_str());
1363 return false;
1364 }
1365
1366 using T = std::decay_t<decltype(policy)>;
1367
1368 if constexpr (std::is_same_v<T, DisplayManagerPolicy>) {
1369 mDisplayManagerPolicy = policy;
1370 } else {
1371 static_assert(std::is_same_v<T, OverridePolicy>);
1372 mOverridePolicy = policy;
1373 }
1374 return true;
1375 },
1376 [this](NoOverridePolicy) {
1377 ftl::FakeGuard guard(mLock);
1378 mOverridePolicy.reset();
1379 return true;
1380 });
1381
1382 if (!valid) {
1383 return SetPolicyResult::Invalid;
1384 }
1385
Ady Abraham68636062022-11-16 17:07:25 -08001386 mGetRankedFrameRatesCache.reset();
Dominik Laskowski36dced82022-09-02 09:24:00 -07001387
1388 if (*getCurrentPolicyLocked() == oldPolicy) {
1389 return SetPolicyResult::Unchanged;
1390 }
1391 constructAvailableRefreshRates();
Ady Abrahamace3d052022-11-17 16:25:05 -08001392
1393 displayId = getActiveModeLocked().modePtr->getPhysicalDisplayId();
Steven Thomasd4071902020-03-24 16:02:53 -07001394 }
Dominik Laskowski36dced82022-09-02 09:24:00 -07001395
Dominik Laskowski36dced82022-09-02 09:24:00 -07001396 const unsigned numModeChanges = std::exchange(mNumModeSwitchesInPolicy, 0u);
1397
1398 ALOGI("Display %s policy changed\n"
1399 "Previous: %s\n"
1400 "Current: %s\n"
1401 "%u mode changes were performed under the previous policy",
1402 to_string(displayId).c_str(), oldPolicy.toString().c_str(), toString(policy).c_str(),
1403 numModeChanges);
1404
1405 return SetPolicyResult::Changed;
Steven Thomasd4071902020-03-24 16:02:53 -07001406}
1407
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001408auto RefreshRateSelector::getCurrentPolicyLocked() const -> const Policy* {
Steven Thomasd4071902020-03-24 16:02:53 -07001409 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
1410}
1411
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001412auto RefreshRateSelector::getCurrentPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001413 std::lock_guard lock(mLock);
1414 return *getCurrentPolicyLocked();
1415}
1416
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001417auto RefreshRateSelector::getDisplayManagerPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001418 std::lock_guard lock(mLock);
1419 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001420}
1421
Ady Abrahamace3d052022-11-17 16:25:05 -08001422bool RefreshRateSelector::isModeAllowed(const FrameRateMode& mode) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001423 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001424 return std::find(mAppRequestFrameRates.begin(), mAppRequestFrameRates.end(), mode) !=
1425 mAppRequestFrameRates.end();
Ady Abraham2139f732019-11-13 18:56:40 -08001426}
1427
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001428void RefreshRateSelector::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001429 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -07001430 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001431 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -07001432
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001433 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -08001434
Ady Abraham68636062022-11-16 17:07:25 -08001435 const auto filterRefreshRates = [&](const FpsRanges& ranges,
1436 const char* rangeName) REQUIRES(mLock) {
1437 const auto filterModes = [&](const DisplayMode& mode) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001438 return mode.getResolution() == defaultMode->getResolution() &&
1439 mode.getDpi() == defaultMode->getDpi() &&
1440 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
ramindania04b8a52023-08-07 18:49:47 -07001441 ranges.physical.includes(mode.getPeakFps()) &&
1442 (supportsFrameRateOverride() || ranges.render.includes(mode.getPeakFps()));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001443 };
Ady Abraham8a82ba62020-01-17 12:43:17 -08001444
Ady Abraham90f7fd22023-08-16 11:02:00 -07001445 auto frameRateModes = createFrameRateModes(*policy, filterModes, ranges.render);
Ady Abraham41bf7c62023-07-20 10:33:06 -07001446 if (frameRateModes.empty()) {
1447 ALOGW("No matching frame rate modes for %s range. policy: %s", rangeName,
1448 policy->toString().c_str());
1449 // TODO(b/292105422): Ideally DisplayManager should not send render ranges smaller than
1450 // the min supported. See b/292047939.
1451 // For not we just ignore the render ranges.
Ady Abraham90f7fd22023-08-16 11:02:00 -07001452 frameRateModes = createFrameRateModes(*policy, filterModes, {});
Ady Abraham41bf7c62023-07-20 10:33:06 -07001453 }
Ady Abraham68636062022-11-16 17:07:25 -08001454 LOG_ALWAYS_FATAL_IF(frameRateModes.empty(),
Ady Abraham41bf7c62023-07-20 10:33:06 -07001455 "No matching frame rate modes for %s range even after ignoring the "
1456 "render range. policy: %s",
1457 rangeName, policy->toString().c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -08001458
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001459 const auto stringifyModes = [&] {
1460 std::string str;
Ady Abraham68636062022-11-16 17:07:25 -08001461 for (const auto& frameRateMode : frameRateModes) {
1462 str += to_string(frameRateMode) + " ";
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001463 }
1464 return str;
1465 };
Rachel Lee45681982024-03-14 18:40:15 -07001466 ALOGV("%s render rates: %s, isVrrDevice? %d", rangeName, stringifyModes().c_str(),
1467 mIsVrrDevice);
Steven Thomasf734df42020-04-13 21:09:28 -07001468
Ady Abraham68636062022-11-16 17:07:25 -08001469 return frameRateModes;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001470 };
1471
Ady Abraham68636062022-11-16 17:07:25 -08001472 mPrimaryFrameRates = filterRefreshRates(policy->primaryRanges, "primary");
1473 mAppRequestFrameRates = filterRefreshRates(policy->appRequestRanges, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -08001474}
1475
Rachel Lee45681982024-03-14 18:40:15 -07001476bool RefreshRateSelector::isVrrDevice() const {
1477 std::lock_guard lock(mLock);
1478 return mIsVrrDevice;
1479}
1480
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001481Fps RefreshRateSelector::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001482 using namespace fps_approx_ops;
1483
1484 if (frameRate <= mKnownFrameRates.front()) {
1485 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001486 }
1487
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001488 if (frameRate >= mKnownFrameRates.back()) {
1489 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001490 }
1491
Marin Shalamanove8a663d2020-11-24 17:48:00 +01001492 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001493 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001494
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001495 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
1496 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001497 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
1498}
1499
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001500auto RefreshRateSelector::getIdleTimerAction() const -> KernelIdleTimerAction {
Ana Krulecb9afd792020-06-11 13:16:15 -07001501 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001502
ramindania04b8a52023-08-07 18:49:47 -07001503 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getPeakFps();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001504 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -07001505
1506 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
1507 // the min allowed refresh rate is higher than the device min, we do not want to enable the
1508 // timer.
ramindania04b8a52023-08-07 18:49:47 -07001509 if (isStrictlyLess(deviceMinFps, minByPolicy->getPeakFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001510 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001511 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001512
ramindanid72ba162022-09-09 21:33:40 +00001513 const DisplayModePtr& maxByPolicy =
Ady Abrahamace3d052022-11-17 16:25:05 -08001514 getMaxRefreshRateByPolicyLocked(getActiveModeLocked().modePtr->getGroup());
Ana Krulecb9afd792020-06-11 13:16:15 -07001515 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001516 // Turn on the timer when the min of the primary range is below the device min.
1517 if (const Policy* currentPolicy = getCurrentPolicyLocked();
Ady Abraham285f8c12022-10-11 17:12:14 -07001518 isApproxLess(currentPolicy->primaryRanges.physical.min, deviceMinFps)) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001519 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001520 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001521 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001522 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001523
Ana Krulecb9afd792020-06-11 13:16:15 -07001524 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001525 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001526}
1527
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001528int RefreshRateSelector::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -07001529 // This calculation needs to be in sync with the java code
1530 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001531
1532 // The threshold must be smaller than 0.001 in order to differentiate
1533 // between the fractional pairs (e.g. 59.94 and 60).
1534 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001535 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -07001536 const auto numPeriodsRounded = std::round(numPeriods);
1537 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001538 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -07001539 }
1540
Ady Abraham62f216c2020-10-13 19:07:23 -07001541 return static_cast<int>(numPeriodsRounded);
1542}
1543
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001544bool RefreshRateSelector::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001545 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001546 return isFractionalPairOrMultiple(bigger, smaller);
1547 }
1548
1549 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
1550 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001551 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
1552 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001553}
1554
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001555void RefreshRateSelector::dump(utils::Dumper& dumper) const {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001556 using namespace std::string_view_literals;
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001557
Marin Shalamanovba421a82020-11-10 21:49:26 +01001558 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +01001559
Ady Abrahamace3d052022-11-17 16:25:05 -08001560 const auto activeMode = getActiveModeLocked();
1561 dumper.dump("activeMode"sv, to_string(activeMode));
Marin Shalamanovba421a82020-11-10 21:49:26 +01001562
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001563 dumper.dump("displayModes"sv);
1564 {
1565 utils::Dumper::Indent indent(dumper);
1566 for (const auto& [id, mode] : mDisplayModes) {
1567 dumper.dump({}, to_string(*mode));
1568 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001569 }
1570
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001571 dumper.dump("displayManagerPolicy"sv, mDisplayManagerPolicy.toString());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001572
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001573 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
1574 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001575 dumper.dump("overridePolicy"sv, currentPolicy.toString());
ramindani32cf0602022-03-02 02:30:29 +00001576 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001577
Ady Abraham8ca643a2022-10-18 18:26:47 -07001578 dumper.dump("frameRateOverrideConfig"sv, *ftl::enum_name(mFrameRateOverrideConfig));
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001579
Dominik Laskowski03cfce82022-11-02 12:13:29 -04001580 dumper.dump("idleTimer"sv);
1581 {
1582 utils::Dumper::Indent indent(dumper);
1583 dumper.dump("interval"sv, mIdleTimer.transform(&OneShotTimer::interval));
1584 dumper.dump("controller"sv,
1585 mConfig.kernelIdleTimerController
1586 .and_then(&ftl::enum_name<KernelIdleTimerController>)
1587 .value_or("Platform"sv));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001588 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001589}
1590
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001591std::chrono::milliseconds RefreshRateSelector::getIdleTimerTimeout() {
ramindani32cf0602022-03-02 02:30:29 +00001592 return mConfig.idleTimerTimeout;
1593}
1594
Rachel Leece6e0042023-06-27 11:22:54 -07001595// TODO(b/293651105): Extract category FpsRange mapping to OEM-configurable config.
1596FpsRange RefreshRateSelector::getFrameRateCategoryRange(FrameRateCategory category) {
1597 switch (category) {
1598 case FrameRateCategory::High:
1599 return FpsRange{90_Hz, 120_Hz};
1600 case FrameRateCategory::Normal:
ramindani9a6cfce2024-03-05 13:00:26 -08001601 return FpsRange{60_Hz, 120_Hz};
Rachel Leece6e0042023-06-27 11:22:54 -07001602 case FrameRateCategory::Low:
ramindani9a6cfce2024-03-05 13:00:26 -08001603 return FpsRange{30_Hz, 120_Hz};
Rachel Lee9580ff12023-12-26 17:33:41 -08001604 case FrameRateCategory::HighHint:
Rachel Leece6e0042023-06-27 11:22:54 -07001605 case FrameRateCategory::NoPreference:
1606 case FrameRateCategory::Default:
1607 LOG_ALWAYS_FATAL("Should not get fps range for frame rate category: %s",
1608 ftl::enum_string(category).c_str());
Rachel Leece6e0042023-06-27 11:22:54 -07001609 default:
1610 LOG_ALWAYS_FATAL("Invalid frame rate category for range: %s",
1611 ftl::enum_string(category).c_str());
Rachel Leece6e0042023-06-27 11:22:54 -07001612 }
1613}
1614
Ady Abraham2139f732019-11-13 18:56:40 -08001615} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001616
1617// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001618#pragma clang diagnostic pop // ignored "-Wextra"