blob: bc0d448d458eb9f30efdb3803622d61ba2efed10 [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 Laskowski0acc3842022-04-07 11:23:42 -0700289 defaultMode.value(), allowGroupSwitching ? "true" : "false",
Ady Abraham285f8c12022-10-11 17:12:14 -0700290 to_string(primaryRanges).c_str(),
291 to_string(appRequestRanges).c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200292}
293
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400294std::pair<nsecs_t, nsecs_t> RefreshRateSelector::getDisplayFrames(nsecs_t layerPeriod,
295 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800296 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
297 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
298 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
299 quotient++;
300 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800301 }
302
Ady Abraham62a0be22020-12-08 16:54:10 -0800303 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800304}
305
Rachel Leece6e0042023-06-27 11:22:54 -0700306float RefreshRateSelector::calculateNonExactMatchingDefaultLayerScoreLocked(
307 nsecs_t displayPeriod, nsecs_t layerPeriod) const {
308 // Find the actual rate the layer will render, assuming
309 // that layerPeriod is the minimal period to render a frame.
310 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
311 // then the actualLayerPeriod will be 32ms, because it is the
312 // smallest multiple of the display period which is >= layerPeriod.
313 auto actualLayerPeriod = displayPeriod;
314 int multiplier = 1;
315 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
316 multiplier++;
317 actualLayerPeriod = displayPeriod * multiplier;
318 }
319
320 // Because of the threshold we used above it's possible that score is slightly
321 // above 1.
322 return std::min(1.0f, static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
323}
324
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400325float RefreshRateSelector::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
326 Fps refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200327 constexpr float kScoreForFractionalPairs = .8f;
328
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800329 const auto displayPeriod = refreshRate.getPeriodNsecs();
Ady Abraham62a0be22020-12-08 16:54:10 -0800330 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
331 if (layer.vote == LayerVoteType::ExplicitDefault) {
Rachel Leece6e0042023-06-27 11:22:54 -0700332 return calculateNonExactMatchingDefaultLayerScoreLocked(displayPeriod, layerPeriod);
Ady Abraham62a0be22020-12-08 16:54:10 -0800333 }
334
335 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
336 layer.vote == LayerVoteType::Heuristic) {
Ady Abrahambd44e8a2023-07-24 11:30:06 -0700337 using fps_approx_ops::operator<;
338 if (refreshRate < 60_Hz) {
339 const bool favorsAtLeast60 =
340 std::find_if(mFrameRatesThatFavorsAtLeast60.begin(),
341 mFrameRatesThatFavorsAtLeast60.end(), [&](Fps fps) {
342 using fps_approx_ops::operator==;
343 return fps == layer.desiredRefreshRate;
344 }) != mFrameRatesThatFavorsAtLeast60.end();
345 if (favorsAtLeast60) {
346 return 0;
347 }
348 }
349
Ady Abraham68636062022-11-16 17:07:25 -0800350 const float multiplier = refreshRate.getValue() / layer.desiredRefreshRate.getValue();
351
352 // We only want to score this layer as a fractional pair if the content is not
353 // significantly faster than the display rate, at it would cause a significant frame drop.
354 // It is more appropriate to choose a higher display rate even if
355 // a pull-down will be required.
Rachel Lee36426fa2023-03-08 20:13:52 -0800356 constexpr float kMinMultiplier = 0.75f;
Ady Abraham68636062022-11-16 17:07:25 -0800357 if (multiplier >= kMinMultiplier &&
358 isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700359 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200360 }
361
Ady Abraham62a0be22020-12-08 16:54:10 -0800362 // Calculate how many display vsyncs we need to present a single frame for this
363 // layer
364 const auto [displayFramesQuotient, displayFramesRemainder] =
365 getDisplayFrames(layerPeriod, displayPeriod);
366 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
367 if (displayFramesRemainder == 0) {
368 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700369 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800370 }
371
372 if (displayFramesQuotient == 0) {
373 // Layer desired refresh rate is higher than the display rate.
374 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
375 (1.0f / (MAX_FRAMES_TO_FIT + 1));
376 }
377
378 // Layer desired refresh rate is lower than the display rate. Check how well it fits
379 // the cadence.
380 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
381 int iter = 2;
382 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
383 diff = diff - (displayPeriod - diff);
384 iter++;
385 }
386
Ady Abraham05243be2021-09-16 15:58:52 -0700387 return (1.0f / iter);
388 }
389
390 return 0;
391}
392
Ady Abraham68636062022-11-16 17:07:25 -0800393float RefreshRateSelector::calculateDistanceScoreFromMax(Fps refreshRate) const {
394 const auto& maxFps = mAppRequestFrameRates.back().fps;
395 const float ratio = refreshRate.getValue() / maxFps.getValue();
ramindanid72ba162022-09-09 21:33:40 +0000396 // Use ratio^2 to get a lower score the more we get further from peak
397 return ratio * ratio;
398}
399
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400400float RefreshRateSelector::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
401 bool isSeamlessSwitch) const {
Ady Abraham05243be2021-09-16 15:58:52 -0700402 // Slightly prefer seamless switches.
403 constexpr float kSeamedSwitchPenalty = 0.95f;
404 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
405
Rachel Leece6e0042023-06-27 11:22:54 -0700406 if (layer.vote == LayerVoteType::ExplicitCategory) {
407 if (getFrameRateCategoryRange(layer.frameRateCategory).includes(refreshRate)) {
408 return 1.f;
409 }
410
411 FpsRange categoryRange = getFrameRateCategoryRange(layer.frameRateCategory);
412 using fps_approx_ops::operator<;
413 if (refreshRate < categoryRange.min) {
414 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
415 categoryRange.min
416 .getPeriodNsecs());
417 }
418 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
419 categoryRange.max.getPeriodNsecs());
420 }
421
Ady Abraham05243be2021-09-16 15:58:52 -0700422 // If the layer wants Max, give higher score to the higher refresh rate
423 if (layer.vote == LayerVoteType::Max) {
Ady Abraham68636062022-11-16 17:07:25 -0800424 return calculateDistanceScoreFromMax(refreshRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800425 }
426
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800427 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800428 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Ady Abraham68636062022-11-16 17:07:25 -0800429 if (supportsAppFrameRateOverrideByContent()) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800430 // Since we support frame rate override, allow refresh rates which are
431 // multiples of the layer's request, as those apps would be throttled
432 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800433 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800434 }
435
Ady Abrahamcc315492022-02-17 17:06:39 -0800436 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800437 }
438
Ady Abrahamcc315492022-02-17 17:06:39 -0800439 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700440 // the highest score.
Rachel Leece6e0042023-06-27 11:22:54 -0700441 if (layer.desiredRefreshRate.isValid() &&
442 getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700443 return 1.0f * seamlessness;
444 }
445
Ady Abrahamcc315492022-02-17 17:06:39 -0800446 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700447 // there is a small penalty attached to the score to favor the frame rates
448 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800449 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700450 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
451 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800452}
453
Ady Abraham68636062022-11-16 17:07:25 -0800454auto RefreshRateSelector::getRankedFrameRates(const std::vector<LayerRequirement>& layers,
455 GlobalSignals signals) const -> RankedFrameRates {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200456 std::lock_guard lock(mLock);
457
Ady Abraham68636062022-11-16 17:07:25 -0800458 if (mGetRankedFrameRatesCache &&
459 mGetRankedFrameRatesCache->arguments == std::make_pair(layers, signals)) {
460 return mGetRankedFrameRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200461 }
462
Ady Abraham68636062022-11-16 17:07:25 -0800463 const auto result = getRankedFrameRatesLocked(layers, signals);
464 mGetRankedFrameRatesCache = GetRankedFrameRatesCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200465 return result;
466}
467
Ady Abraham68636062022-11-16 17:07:25 -0800468auto RefreshRateSelector::getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
469 GlobalSignals signals) const
470 -> RankedFrameRates {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000471 using namespace fps_approx_ops;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800472 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800473 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700474
Ady Abrahamace3d052022-11-17 16:25:05 -0800475 const auto& activeMode = *getActiveModeLocked().modePtr;
ramindani38c84982022-08-29 18:02:57 +0000476
Ady Abraham68636062022-11-16 17:07:25 -0800477 // Keep the display at max frame rate for the duration of powering on the display.
ramindani38c84982022-08-29 18:02:57 +0000478 if (signals.powerOnImminent) {
479 ALOGV("Power On Imminent");
Ady Abrahamccf63862023-01-19 11:44:01 -0800480 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Descending);
481 ATRACE_FORMAT_INSTANT("%s (Power On Imminent)",
482 to_string(ranking.front().frameRateMode.fps).c_str());
483 return {ranking, GlobalSignals{.powerOnImminent = true}};
ramindani38c84982022-08-29 18:02:57 +0000484 }
485
Ady Abraham8a82ba62020-01-17 12:43:17 -0800486 int noVoteLayers = 0;
487 int minVoteLayers = 0;
488 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800489 int explicitDefaultVoteLayers = 0;
490 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800491 int explicitExact = 0;
Rachel Leece6e0042023-06-27 11:22:54 -0700492 int explicitCategoryVoteLayers = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100493 int seamedFocusedLayers = 0;
Rachel Lee67afbea2023-09-28 15:35:07 -0700494 int categorySmoothSwitchOnlyLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800495
Ady Abraham8a82ba62020-01-17 12:43:17 -0800496 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800497 switch (layer.vote) {
498 case LayerVoteType::NoVote:
499 noVoteLayers++;
500 break;
501 case LayerVoteType::Min:
502 minVoteLayers++;
503 break;
504 case LayerVoteType::Max:
505 maxVoteLayers++;
506 break;
507 case LayerVoteType::ExplicitDefault:
508 explicitDefaultVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800509 break;
510 case LayerVoteType::ExplicitExactOrMultiple:
511 explicitExactOrMultipleVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800512 break;
513 case LayerVoteType::ExplicitExact:
514 explicitExact++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800515 break;
Rachel Leece6e0042023-06-27 11:22:54 -0700516 case LayerVoteType::ExplicitCategory:
517 explicitCategoryVoteLayers++;
Rachel Leef377b362023-09-06 15:01:06 -0700518 if (layer.frameRateCategory == FrameRateCategory::NoPreference) {
519 // Count this layer for Min vote as well. The explicit vote avoids
520 // touch boost and idle for choosing a category, while Min vote is for correct
521 // behavior when all layers are Min or no vote.
522 minVoteLayers++;
523 }
Rachel Leece6e0042023-06-27 11:22:54 -0700524 break;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800525 case LayerVoteType::Heuristic:
526 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800527 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200528
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100529 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
530 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200531 }
Rachel Lee67afbea2023-09-28 15:35:07 -0700532 if (layer.frameRateCategorySmoothSwitchOnly) {
533 categorySmoothSwitchOnlyLayers++;
534 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800535 }
536
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800537 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
Rachel Leece6e0042023-06-27 11:22:54 -0700538 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0 ||
539 explicitCategoryVoteLayers > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700540
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200541 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800542 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700543
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200544 // If the default mode group is different from the group of current mode,
545 // this means a layer requesting a seamed mode switch just disappeared and
546 // we should switch back to the default group.
547 // However if a seamed layer is still present we anchor around the group
548 // of the current mode, in order to prevent unnecessary seamed mode switches
549 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800550 const auto anchorGroup =
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700551 seamedFocusedLayers > 0 ? activeMode.getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200552
Steven Thomasf734df42020-04-13 21:09:28 -0700553 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
554 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800555 if (signals.touch && !hasExplicitVoteLayers) {
ramindanid72ba162022-09-09 21:33:40 +0000556 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800557 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
558 ATRACE_FORMAT_INSTANT("%s (Touch Boost)",
559 to_string(ranking.front().frameRateMode.fps).c_str());
560 return {ranking, GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800561 }
562
Alec Mouri11232a22020-05-14 18:06:25 -0700563 // If the primary range consists of a single refresh rate then we can only
564 // move out the of range if layers explicitly request a different refresh
565 // rate.
Ady Abraham90f7fd22023-08-16 11:02:00 -0700566 if (!signals.touch && signals.idle &&
567 !(policy->primaryRangeIsSingleRate() && hasExplicitVoteLayers)) {
ramindanid72ba162022-09-09 21:33:40 +0000568 ALOGV("Idle");
Ady Abrahamccf63862023-01-19 11:44:01 -0800569 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending);
570 ATRACE_FORMAT_INSTANT("%s (Idle)", to_string(ranking.front().frameRateMode.fps).c_str());
571 return {ranking, GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700572 }
573
Steven Thomasdebafed2020-05-18 17:30:35 -0700574 if (layers.empty() || noVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000575 ALOGV("No layers with votes");
Ady Abrahamccf63862023-01-19 11:44:01 -0800576 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
577 ATRACE_FORMAT_INSTANT("%s (No layers with votes)",
578 to_string(ranking.front().frameRateMode.fps).c_str());
579 return {ranking, kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700580 }
581
Rachel Lee67afbea2023-09-28 15:35:07 -0700582 const bool smoothSwitchOnly = categorySmoothSwitchOnlyLayers > 0;
583 const DisplayModeId activeModeId = activeMode.getId();
584
Ady Abraham8a82ba62020-01-17 12:43:17 -0800585 // Only if all layers want Min we should return Min
586 if (noVoteLayers + minVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000587 ALOGV("All layers Min");
Rachel Lee67afbea2023-09-28 15:35:07 -0700588 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending,
589 std::nullopt, [&](FrameRateMode mode) {
590 return !smoothSwitchOnly ||
591 mode.modePtr->getId() == activeModeId;
592 });
Ady Abrahamccf63862023-01-19 11:44:01 -0800593 ATRACE_FORMAT_INSTANT("%s (All layers Min)",
594 to_string(ranking.front().frameRateMode.fps).c_str());
595 return {ranking, kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800596 }
597
Ady Abraham8a82ba62020-01-17 12:43:17 -0800598 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800599 std::vector<RefreshRateScore> scores;
Ady Abraham68636062022-11-16 17:07:25 -0800600 scores.reserve(mAppRequestFrameRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800601
Ady Abraham68636062022-11-16 17:07:25 -0800602 for (const FrameRateMode& it : mAppRequestFrameRates) {
603 scores.emplace_back(RefreshRateScore{it, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800604 }
605
606 for (const auto& layer : layers) {
Rachel Leece6e0042023-06-27 11:22:54 -0700607 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f, category %s) ",
608 layer.name.c_str(), ftl::enum_string(layer.vote).c_str(), layer.weight,
609 layer.desiredRefreshRate.getValue(),
610 ftl::enum_string(layer.frameRateCategory).c_str());
Rachel Leed0694bc2023-09-12 14:57:58 -0700611 if (layer.isNoVote() || layer.frameRateCategory == FrameRateCategory::NoPreference ||
612 layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800613 continue;
614 }
615
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800616 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800617
Ady Abraham68636062022-11-16 17:07:25 -0800618 for (auto& [mode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
619 const auto& [fps, modePtr] = mode;
620 const bool isSeamlessSwitch = modePtr->getGroup() == activeMode.getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200621
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100622 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100623 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800624 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700625 to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200626 continue;
627 }
628
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100629 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
630 !layer.focused) {
631 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100632 " Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800633 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700634 to_string(activeMode).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100635 continue;
636 }
637
Rachel Lee67afbea2023-09-28 15:35:07 -0700638 if (smoothSwitchOnly && modePtr->getId() != activeModeId) {
639 ALOGV("%s ignores %s because it's non-VRR and smooth switch only."
640 " Current mode = %s",
641 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
642 to_string(activeMode).c_str());
643 continue;
644 }
645
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100646 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100647 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100648 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100649 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
650 // disappeared.
Ady Abraham68636062022-11-16 17:07:25 -0800651 const bool isInPolicyForDefault = modePtr->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100652 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100653 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham68636062022-11-16 17:07:25 -0800654 to_string(*modePtr).c_str(), to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200655 continue;
656 }
657
Ady Abraham90f7fd22023-08-16 11:02:00 -0700658 const bool inPrimaryPhysicalRange =
ramindania04b8a52023-08-07 18:49:47 -0700659 policy->primaryRanges.physical.includes(modePtr->getPeakFps());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700660 const bool inPrimaryRenderRange = policy->primaryRanges.render.includes(fps);
661 if (((policy->primaryRangeIsSingleRate() && !inPrimaryPhysicalRange) ||
662 !inPrimaryRenderRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800663 !(layer.focused &&
664 (layer.vote == LayerVoteType::ExplicitDefault ||
665 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700666 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700667 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700668 continue;
669 }
670
Ady Abraham68636062022-11-16 17:07:25 -0800671 const float layerScore = calculateLayerScoreLocked(layer, fps, isSeamlessSwitch);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000672 const float weightedLayerScore = weight * layerScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800673
Ady Abraham13cfb362022-08-13 05:12:13 +0000674 // Layer with fixed source has a special consideration which depends on the
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000675 // mConfig.frameRateMultipleThreshold. We don't want these layers to score
676 // refresh rates above the threshold, but we also don't want to favor the lower
677 // ones by having a greater number of layers scoring them. Instead, we calculate
678 // the score independently for these layers and later decide which
679 // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
680 // score 120 Hz, but desired 60 fps should contribute to the score.
681 const bool fixedSourceLayer = [](LayerVoteType vote) {
682 switch (vote) {
683 case LayerVoteType::ExplicitExactOrMultiple:
684 case LayerVoteType::Heuristic:
685 return true;
686 case LayerVoteType::NoVote:
687 case LayerVoteType::Min:
688 case LayerVoteType::Max:
689 case LayerVoteType::ExplicitDefault:
690 case LayerVoteType::ExplicitExact:
Rachel Leece6e0042023-06-27 11:22:54 -0700691 case LayerVoteType::ExplicitCategory:
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000692 return false;
693 }
694 }(layer.vote);
Ady Abraham62f51d92022-08-24 22:20:22 +0000695 const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000696 layer.desiredRefreshRate <
697 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
Ady Abraham62f51d92022-08-24 22:20:22 +0000698 if (fixedSourceLayer && layerBelowThreshold) {
Ady Abraham13cfb362022-08-13 05:12:13 +0000699 const bool modeAboveThreshold =
ramindania04b8a52023-08-07 18:49:47 -0700700 modePtr->getPeakFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
Ady Abraham62f51d92022-08-24 22:20:22 +0000701 if (modeAboveThreshold) {
ramindania04b8a52023-08-07 18:49:47 -0700702 ALOGV("%s gives %s (%s(%s)) fixed source (above threshold) score of %.4f",
Ady Abraham68636062022-11-16 17:07:25 -0800703 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700704 to_string(modePtr->getPeakFps()).c_str(),
705 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000706 fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000707 } else {
ramindania04b8a52023-08-07 18:49:47 -0700708 ALOGV("%s gives %s (%s(%s)) fixed source (below threshold) score of %.4f",
Ady Abraham68636062022-11-16 17:07:25 -0800709 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700710 to_string(modePtr->getPeakFps()).c_str(),
711 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000712 fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000713 }
714 } else {
ramindania04b8a52023-08-07 18:49:47 -0700715 ALOGV("%s gives %s (%s(%s)) score of %.4f", formatLayerInfo(layer, weight).c_str(),
716 to_string(fps).c_str(), to_string(modePtr->getPeakFps()).c_str(),
717 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000718 overallScore += weightedLayerScore;
719 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800720 }
721 }
722
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000723 // We want to find the best refresh rate without the fixed source layers,
Ady Abraham62f51d92022-08-24 22:20:22 +0000724 // so we could know whether we should add the modeAboveThreshold scores or not.
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000725 // If the best refresh rate is already above the threshold, it means that
726 // some non-fixed source layers already scored it, so we can just add the score
727 // for all fixed source layers, even the ones that are above the threshold.
728 const bool maxScoreAboveThreshold = [&] {
729 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
730 return false;
731 }
732
733 const auto maxScoreIt =
734 std::max_element(scores.begin(), scores.end(),
735 [](RefreshRateScore max, RefreshRateScore current) {
Ady Abraham68636062022-11-16 17:07:25 -0800736 return current.overallScore > max.overallScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000737 });
ramindania04b8a52023-08-07 18:49:47 -0700738 ALOGV("%s (%s(%s)) is the best refresh rate without fixed source layers. It is %s the "
Ady Abraham68636062022-11-16 17:07:25 -0800739 "threshold for "
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000740 "refresh rate multiples",
Ady Abraham68636062022-11-16 17:07:25 -0800741 to_string(maxScoreIt->frameRateMode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700742 to_string(maxScoreIt->frameRateMode.modePtr->getPeakFps()).c_str(),
743 to_string(maxScoreIt->frameRateMode.modePtr->getVsyncRate()).c_str(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000744 maxScoreAboveThreshold ? "above" : "below");
ramindania04b8a52023-08-07 18:49:47 -0700745 return maxScoreIt->frameRateMode.modePtr->getPeakFps() >=
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000746 Fps::fromValue(mConfig.frameRateMultipleThreshold);
747 }();
748
749 // Now we can add the fixed rate layers score
Ady Abraham68636062022-11-16 17:07:25 -0800750 for (auto& [frameRateMode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000751 overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000752 if (maxScoreAboveThreshold) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000753 overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000754 }
ramindania04b8a52023-08-07 18:49:47 -0700755 ALOGV("%s (%s(%s)) adjusted overallScore is %.4f", to_string(frameRateMode.fps).c_str(),
756 to_string(frameRateMode.modePtr->getPeakFps()).c_str(),
757 to_string(frameRateMode.modePtr->getVsyncRate()).c_str(), overallScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000758 }
759
760 // Now that we scored all the refresh rates we need to pick the one that got the highest
ramindanid72ba162022-09-09 21:33:40 +0000761 // overallScore. Sort the scores based on their overallScore in descending order of priority.
762 const RefreshRateOrder refreshRateOrder =
763 maxVoteLayers > 0 ? RefreshRateOrder::Descending : RefreshRateOrder::Ascending;
764 std::sort(scores.begin(), scores.end(),
765 RefreshRateScoreComparator{.refreshRateOrder = refreshRateOrder});
ramindanid72ba162022-09-09 21:33:40 +0000766
Ady Abraham68636062022-11-16 17:07:25 -0800767 FrameRateRanking ranking;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400768 ranking.reserve(scores.size());
769
770 std::transform(scores.begin(), scores.end(), back_inserter(ranking),
ramindanid72ba162022-09-09 21:33:40 +0000771 [](const RefreshRateScore& score) {
Ady Abraham68636062022-11-16 17:07:25 -0800772 return ScoredFrameRate{score.frameRateMode, score.overallScore};
ramindanid72ba162022-09-09 21:33:40 +0000773 });
Ady Abraham34702102020-02-10 14:12:05 -0800774
Ady Abraham37d46922022-10-05 13:08:51 -0700775 const bool noLayerScore = std::all_of(scores.begin(), scores.end(), [](RefreshRateScore score) {
776 return score.overallScore == 0;
777 });
778
Ady Abraham90f7fd22023-08-16 11:02:00 -0700779 if (policy->primaryRangeIsSingleRate()) {
Alec Mouri11232a22020-05-14 18:06:25 -0700780 // If we never scored any layers, then choose the rate from the primary
781 // range instead of picking a random score from the app range.
Ady Abraham37d46922022-10-05 13:08:51 -0700782 if (noLayerScore) {
ramindanid72ba162022-09-09 21:33:40 +0000783 ALOGV("Layers not scored");
Ady Abrahamccf63862023-01-19 11:44:01 -0800784 const auto descending = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
785 ATRACE_FORMAT_INSTANT("%s (Layers not scored)",
786 to_string(descending.front().frameRateMode.fps).c_str());
787 return {descending, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700788 } else {
Rachel Lee67afbea2023-09-28 15:35:07 -0700789 ALOGV("primaryRangeIsSingleRate");
Ady Abrahamccf63862023-01-19 11:44:01 -0800790 ATRACE_FORMAT_INSTANT("%s (primaryRangeIsSingleRate)",
791 to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400792 return {ranking, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700793 }
794 }
795
Steven Thomasf734df42020-04-13 21:09:28 -0700796 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
797 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
798 // vote we should not change it if we get a touch event. Only apply touch boost if it will
799 // actually increase the refresh rate over the normal selection.
Ady Abraham5e4e9832021-06-14 13:40:56 -0700800 const bool touchBoostForExplicitExact = [&] {
Ady Abraham68636062022-11-16 17:07:25 -0800801 if (supportsAppFrameRateOverrideByContent()) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700802 // Enable touch boost if there are other layers besides exact
803 return explicitExact + noVoteLayers != layers.size();
804 } else {
805 // Enable touch boost if there are no exact layers
806 return explicitExact == 0;
807 }
808 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700809
Ady Abraham68636062022-11-16 17:07:25 -0800810 const auto touchRefreshRates = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700811 using fps_approx_ops::operator<;
812
Rachel Leece6e0042023-06-27 11:22:54 -0700813 if (signals.touch && explicitDefaultVoteLayers == 0 && explicitCategoryVoteLayers == 0 &&
814 touchBoostForExplicitExact &&
Ady Abraham68636062022-11-16 17:07:25 -0800815 scores.front().frameRateMode.fps < touchRefreshRates.front().frameRateMode.fps) {
ramindanid72ba162022-09-09 21:33:40 +0000816 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800817 ATRACE_FORMAT_INSTANT("%s (Touch Boost [late])",
818 to_string(touchRefreshRates.front().frameRateMode.fps).c_str());
ramindanid72ba162022-09-09 21:33:40 +0000819 return {touchRefreshRates, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700820 }
821
Ady Abraham37d46922022-10-05 13:08:51 -0700822 // If we never scored any layers, and we don't favor high refresh rates, prefer to stay with the
823 // current config
824 if (noLayerScore && refreshRateOrder == RefreshRateOrder::Ascending) {
Rachel Lee67afbea2023-09-28 15:35:07 -0700825 ALOGV("preferredDisplayMode");
Ady Abrahamccf63862023-01-19 11:44:01 -0800826 const auto ascendingWithPreferred =
827 rankFrameRates(anchorGroup, RefreshRateOrder::Ascending, activeMode.getId());
828 ATRACE_FORMAT_INSTANT("%s (preferredDisplayMode)",
829 to_string(ascendingWithPreferred.front().frameRateMode.fps).c_str());
830 return {ascendingWithPreferred, kNoSignals};
Ady Abraham37d46922022-10-05 13:08:51 -0700831 }
832
Rachel Lee67afbea2023-09-28 15:35:07 -0700833 ALOGV("%s (scored))", to_string(ranking.front().frameRateMode.fps).c_str());
Ady Abrahamccf63862023-01-19 11:44:01 -0800834 ATRACE_FORMAT_INSTANT("%s (scored))", to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400835 return {ranking, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800836}
837
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400838using LayerRequirementPtrs = std::vector<const RefreshRateSelector::LayerRequirement*>;
839using PerUidLayerRequirements = std::unordered_map<uid_t, LayerRequirementPtrs>;
840
841PerUidLayerRequirements groupLayersByUid(
842 const std::vector<RefreshRateSelector::LayerRequirement>& layers) {
843 PerUidLayerRequirements layersByUid;
Ady Abraham62a0be22020-12-08 16:54:10 -0800844 for (const auto& layer : layers) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400845 const auto it = layersByUid.emplace(layer.ownerUid, LayerRequirementPtrs()).first;
846 auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800847 layersWithSameUid.push_back(&layer);
848 }
849
850 // Remove uids that can't have a frame rate override
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400851 for (auto it = layersByUid.begin(); it != layersByUid.end();) {
852 const auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800853 bool skipUid = false;
854 for (const auto& layer : layersWithSameUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400855 using LayerVoteType = RefreshRateSelector::LayerVoteType;
856
857 if (layer->vote == LayerVoteType::Max || layer->vote == LayerVoteType::Heuristic) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800858 skipUid = true;
859 break;
860 }
861 }
862 if (skipUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400863 it = layersByUid.erase(it);
Ady Abraham62a0be22020-12-08 16:54:10 -0800864 } else {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400865 ++it;
Ady Abraham62a0be22020-12-08 16:54:10 -0800866 }
867 }
868
869 return layersByUid;
870}
871
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400872auto RefreshRateSelector::getFrameRateOverrides(const std::vector<LayerRequirement>& layers,
873 Fps displayRefreshRate,
874 GlobalSignals globalSignals) const
875 -> UidToFrameRateOverride {
Ady Abraham62a0be22020-12-08 16:54:10 -0800876 ATRACE_CALL();
Ady Abraham68636062022-11-16 17:07:25 -0800877 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Disabled) {
878 return {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800879 }
880
Ady Abraham68636062022-11-16 17:07:25 -0800881 ALOGV("%s: %zu layers", __func__, layers.size());
882 std::lock_guard lock(mLock);
883
Ady Abraham8ca643a2022-10-18 18:26:47 -0700884 const auto* policyPtr = getCurrentPolicyLocked();
885 // We don't want to run lower than 30fps
ramindania04b8a52023-08-07 18:49:47 -0700886 // TODO(b/297600226): revise this for dVRR
Ady Abraham8ca643a2022-10-18 18:26:47 -0700887 const Fps minFrameRate = std::max(policyPtr->appRequestRanges.render.min, 30_Hz, isApproxLess);
888
889 using fps_approx_ops::operator/;
890 const unsigned numMultiples = displayRefreshRate / minFrameRate;
891
892 std::vector<std::pair<Fps, float>> scoredFrameRates;
893 scoredFrameRates.reserve(numMultiples);
894
895 for (unsigned n = numMultiples; n > 0; n--) {
896 const Fps divisor = displayRefreshRate / n;
897 if (mConfig.enableFrameRateOverride ==
Ady Abraham68636062022-11-16 17:07:25 -0800898 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
899 !isNativeRefreshRate(divisor)) {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700900 continue;
901 }
902
903 if (policyPtr->appRequestRanges.render.includes(divisor)) {
904 ALOGV("%s: adding %s as a potential frame rate", __func__, to_string(divisor).c_str());
905 scoredFrameRates.emplace_back(divisor, 0);
906 }
907 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800908
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400909 const auto layersByUid = groupLayersByUid(layers);
Ady Abraham62a0be22020-12-08 16:54:10 -0800910 UidToFrameRateOverride frameRateOverrides;
911 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800912 // Layers with ExplicitExactOrMultiple expect touch boost
913 const bool hasExplicitExactOrMultiple =
914 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
915 [](const auto& layer) {
916 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
917 });
918
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700919 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800920 continue;
921 }
922
Ady Abraham8ca643a2022-10-18 18:26:47 -0700923 for (auto& [_, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800924 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -0800925 }
926
927 for (const auto& layer : layersWithSameUid) {
Rachel Lee47adfcf2023-09-15 17:36:56 -0700928 if (layer->isNoVote() || layer->frameRateCategory == FrameRateCategory::NoPreference ||
929 layer->vote == LayerVoteType::Min) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800930 continue;
931 }
932
933 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Rachel Leece6e0042023-06-27 11:22:54 -0700934 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
935 layer->vote != LayerVoteType::ExplicitExact &&
936 layer->vote != LayerVoteType::ExplicitCategory,
937 "Invalid layer vote type for frame rate overrides");
Ady Abraham8ca643a2022-10-18 18:26:47 -0700938 for (auto& [fps, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800939 constexpr bool isSeamlessSwitch = true;
Ady Abraham8ca643a2022-10-18 18:26:47 -0700940 const auto layerScore = calculateLayerScoreLocked(*layer, fps, isSeamlessSwitch);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800941 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -0800942 }
943 }
944
Ady Abraham62a0be22020-12-08 16:54:10 -0800945 // If we never scored any layers, we don't have a preferred frame rate
Ady Abraham8ca643a2022-10-18 18:26:47 -0700946 if (std::all_of(scoredFrameRates.begin(), scoredFrameRates.end(),
947 [](const auto& scoredFrameRate) {
948 const auto [_, score] = scoredFrameRate;
949 return score == 0;
950 })) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800951 continue;
952 }
953
ramindanid72ba162022-09-09 21:33:40 +0000954 // Now that we scored all the refresh rates we need to pick the lowest refresh rate
955 // that got the highest score.
Ady Abraham8ca643a2022-10-18 18:26:47 -0700956 const auto [overrideFps, _] =
957 *std::max_element(scoredFrameRates.begin(), scoredFrameRates.end(),
958 [](const auto& lhsPair, const auto& rhsPair) {
959 const float lhs = lhsPair.second;
960 const float rhs = rhsPair.second;
Ady Abraham68636062022-11-16 17:07:25 -0800961 return lhs < rhs && !ScoredFrameRate::scoresEqual(lhs, rhs);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700962 });
963 ALOGV("%s: overriding to %s for uid=%d", __func__, to_string(overrideFps).c_str(), uid);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700964 ATRACE_FORMAT_INSTANT("%s: overriding to %s for uid=%d", __func__,
965 to_string(overrideFps).c_str(), uid);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700966 frameRateOverrides.emplace(uid, overrideFps);
Ady Abraham62a0be22020-12-08 16:54:10 -0800967 }
968
969 return frameRateOverrides;
970}
971
Ady Abraham0aa373a2022-11-22 13:56:50 -0800972ftl::Optional<FrameRateMode> RefreshRateSelector::onKernelTimerChanged(
Dominik Laskowski59746512023-11-19 09:30:24 -0500973 ftl::Optional<DisplayModeId> desiredModeIdOpt, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800974 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100975
Ady Abraham0aa373a2022-11-22 13:56:50 -0800976 const auto current = [&]() REQUIRES(mLock) -> FrameRateMode {
Dominik Laskowski59746512023-11-19 09:30:24 -0500977 if (desiredModeIdOpt) {
978 const auto& modePtr = mDisplayModes.get(*desiredModeIdOpt)->get();
ramindania04b8a52023-08-07 18:49:47 -0700979 return FrameRateMode{modePtr->getPeakFps(), ftl::as_non_null(modePtr)};
Ady Abraham0aa373a2022-11-22 13:56:50 -0800980 }
981
982 return getActiveModeLocked();
983 }();
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100984
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800985 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
Ady Abraham0aa373a2022-11-22 13:56:50 -0800986 if (current.modePtr->getId() == min->getId()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800987 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100988 }
989
ramindania04b8a52023-08-07 18:49:47 -0700990 return timerExpired ? FrameRateMode{min->getPeakFps(), ftl::as_non_null(min)} : current;
Steven Thomasf734df42020-04-13 21:09:28 -0700991}
992
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400993const DisplayModePtr& RefreshRateSelector::getMinRefreshRateByPolicyLocked() const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800994 const auto& activeMode = *getActiveModeLocked().modePtr;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700995
Ady Abraham68636062022-11-16 17:07:25 -0800996 for (const FrameRateMode& mode : mPrimaryFrameRates) {
997 if (activeMode.getGroup() == mode.modePtr->getGroup()) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800998 return mode.modePtr.get();
Marin Shalamanov46084422020-10-13 12:33:42 +0200999 }
1000 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001001
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001002 ALOGE("Can't find min refresh rate by policy with the same mode group as the current mode %s",
1003 to_string(activeMode).c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001004
1005 // Default to the lowest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -08001006 return mPrimaryFrameRates.front().modePtr.get();
Ady Abraham2139f732019-11-13 18:56:40 -08001007}
1008
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001009const DisplayModePtr& RefreshRateSelector::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Ady Abrahamace3d052022-11-17 16:25:05 -08001010 const ftl::NonNull<DisplayModePtr>* maxByAnchor = &mPrimaryFrameRates.back().modePtr;
1011 const ftl::NonNull<DisplayModePtr>* max = &mPrimaryFrameRates.back().modePtr;
Ady Abraham68636062022-11-16 17:07:25 -08001012
1013 bool maxByAnchorFound = false;
1014 for (auto it = mPrimaryFrameRates.rbegin(); it != mPrimaryFrameRates.rend(); ++it) {
1015 using namespace fps_approx_ops;
ramindania04b8a52023-08-07 18:49:47 -07001016 if (it->modePtr->getPeakFps() > (*max)->getPeakFps()) {
Ady Abraham68636062022-11-16 17:07:25 -08001017 max = &it->modePtr;
Marin Shalamanov46084422020-10-13 12:33:42 +02001018 }
Ady Abraham68636062022-11-16 17:07:25 -08001019
1020 if (anchorGroup == it->modePtr->getGroup() &&
ramindania04b8a52023-08-07 18:49:47 -07001021 it->modePtr->getPeakFps() >= (*maxByAnchor)->getPeakFps()) {
Ady Abraham68636062022-11-16 17:07:25 -08001022 maxByAnchorFound = true;
1023 maxByAnchor = &it->modePtr;
1024 }
1025 }
1026
1027 if (maxByAnchorFound) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001028 return maxByAnchor->get();
Marin Shalamanov46084422020-10-13 12:33:42 +02001029 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001030
ramindanid72ba162022-09-09 21:33:40 +00001031 ALOGE("Can't find max refresh rate by policy with the same group %d", anchorGroup);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001032
1033 // Default to the highest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -08001034 return max->get();
Ady Abraham2139f732019-11-13 18:56:40 -08001035}
1036
Ady Abraham68636062022-11-16 17:07:25 -08001037auto RefreshRateSelector::rankFrameRates(std::optional<int> anchorGroupOpt,
1038 RefreshRateOrder refreshRateOrder,
Rachel Lee67afbea2023-09-28 15:35:07 -07001039 std::optional<DisplayModeId> preferredDisplayModeOpt,
1040 const RankFrameRatesPredicate& predicate) const
Ady Abraham68636062022-11-16 17:07:25 -08001041 -> FrameRateRanking {
Ady Abrahama5992df2023-01-27 21:10:57 -08001042 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -08001043 const char* const whence = __func__;
Ady Abrahama5992df2023-01-27 21:10:57 -08001044
1045 // find the highest frame rate for each display mode
1046 ftl::SmallMap<DisplayModeId, Fps, 8> maxRenderRateForMode;
1047 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
1048 if (ascending) {
1049 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1050 // use a lower frame rate when we want Ascending frame rates.
1051 for (const auto& frameRateMode : mPrimaryFrameRates) {
1052 if (anchorGroupOpt && frameRateMode.modePtr->getGroup() != anchorGroupOpt) {
1053 continue;
1054 }
1055
1056 const auto [iter, _] = maxRenderRateForMode.try_emplace(frameRateMode.modePtr->getId(),
1057 frameRateMode.fps);
1058 if (iter->second < frameRateMode.fps) {
1059 iter->second = frameRateMode.fps;
1060 }
1061 }
1062 }
1063
Ady Abraham68636062022-11-16 17:07:25 -08001064 std::deque<ScoredFrameRate> ranking;
1065 const auto rankFrameRate = [&](const FrameRateMode& frameRateMode) REQUIRES(mLock) {
1066 const auto& modePtr = frameRateMode.modePtr;
Rachel Lee67afbea2023-09-28 15:35:07 -07001067 if ((anchorGroupOpt && modePtr->getGroup() != anchorGroupOpt) ||
1068 !predicate(frameRateMode)) {
Ady Abraham37d46922022-10-05 13:08:51 -07001069 return;
ramindanid72ba162022-09-09 21:33:40 +00001070 }
Ady Abraham37d46922022-10-05 13:08:51 -07001071
Ady Abraham3f965922023-01-23 17:18:29 -08001072 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
ramindanif7075202023-03-10 00:24:34 +00001073 const auto id = modePtr->getId();
Ady Abrahama5992df2023-01-27 21:10:57 -08001074 if (ascending && frameRateMode.fps < *maxRenderRateForMode.get(id)) {
Ady Abraham3f965922023-01-23 17:18:29 -08001075 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1076 // use a lower frame rate when we want Ascending frame rates.
1077 return;
1078 }
1079
Ady Abraham68636062022-11-16 17:07:25 -08001080 float score = calculateDistanceScoreFromMax(frameRateMode.fps);
Ady Abraham3f965922023-01-23 17:18:29 -08001081
1082 if (ascending) {
Ady Abraham37d46922022-10-05 13:08:51 -07001083 score = 1.0f / score;
1084 }
ramindanif7075202023-03-10 00:24:34 +00001085
1086 constexpr float kScore = std::numeric_limits<float>::max();
Ady Abraham37d46922022-10-05 13:08:51 -07001087 if (preferredDisplayModeOpt) {
Ady Abraham68636062022-11-16 17:07:25 -08001088 if (*preferredDisplayModeOpt == modePtr->getId()) {
Ady Abraham68636062022-11-16 17:07:25 -08001089 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
Ady Abraham37d46922022-10-05 13:08:51 -07001090 return;
1091 }
1092 constexpr float kNonPreferredModePenalty = 0.95f;
1093 score *= kNonPreferredModePenalty;
ramindanif7075202023-03-10 00:24:34 +00001094 } else if (ascending && id == getMinRefreshRateByPolicyLocked()->getId()) {
1095 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround
1096 // and actually use a lower frame rate when we want Ascending frame rates.
1097 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
1098 return;
Ady Abraham37d46922022-10-05 13:08:51 -07001099 }
Ady Abraham3f965922023-01-23 17:18:29 -08001100
ramindania04b8a52023-08-07 18:49:47 -07001101 ALOGV("%s(%s) %s (%s(%s)) scored %.2f", whence, ftl::enum_string(refreshRateOrder).c_str(),
1102 to_string(frameRateMode.fps).c_str(), to_string(modePtr->getPeakFps()).c_str(),
1103 to_string(modePtr->getVsyncRate()).c_str(), score);
Ady Abraham68636062022-11-16 17:07:25 -08001104 ranking.emplace_back(ScoredFrameRate{frameRateMode, score});
ramindanid72ba162022-09-09 21:33:40 +00001105 };
1106
1107 if (refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abraham68636062022-11-16 17:07:25 -08001108 std::for_each(mPrimaryFrameRates.begin(), mPrimaryFrameRates.end(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001109 } else {
Ady Abraham68636062022-11-16 17:07:25 -08001110 std::for_each(mPrimaryFrameRates.rbegin(), mPrimaryFrameRates.rend(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001111 }
1112
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001113 if (!ranking.empty() || !anchorGroupOpt) {
1114 return {ranking.begin(), ranking.end()};
ramindanid72ba162022-09-09 21:33:40 +00001115 }
1116
1117 ALOGW("Can't find %s refresh rate by policy with the same mode group"
1118 " as the mode group %d",
1119 refreshRateOrder == RefreshRateOrder::Ascending ? "min" : "max", anchorGroupOpt.value());
1120
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001121 constexpr std::optional<int> kNoAnchorGroup = std::nullopt;
Ady Abraham68636062022-11-16 17:07:25 -08001122 return rankFrameRates(kNoAnchorGroup, refreshRateOrder, preferredDisplayModeOpt);
ramindanid72ba162022-09-09 21:33:40 +00001123}
1124
Ady Abrahamace3d052022-11-17 16:25:05 -08001125FrameRateMode RefreshRateSelector::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -08001126 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001127 return getActiveModeLocked();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001128}
1129
Ady Abrahamace3d052022-11-17 16:25:05 -08001130const FrameRateMode& RefreshRateSelector::getActiveModeLocked() const {
1131 return *mActiveModeOpt;
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001132}
1133
Ady Abrahamace3d052022-11-17 16:25:05 -08001134void RefreshRateSelector::setActiveMode(DisplayModeId modeId, Fps renderFrameRate) {
Ady Abraham2139f732019-11-13 18:56:40 -08001135 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001136
Ady Abraham68636062022-11-16 17:07:25 -08001137 // Invalidate the cached invocation to getRankedFrameRates. This forces
1138 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1139 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001140
Ady Abrahamace3d052022-11-17 16:25:05 -08001141 const auto activeModeOpt = mDisplayModes.get(modeId);
1142 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1143
1144 mActiveModeOpt.emplace(FrameRateMode{renderFrameRate, ftl::as_non_null(activeModeOpt->get())});
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001145}
1146
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001147RefreshRateSelector::RefreshRateSelector(DisplayModes modes, DisplayModeId activeModeId,
1148 Config config)
rnlee3bd610662021-06-23 16:27:57 -07001149 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001150 initializeIdleTimer();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001151 FTL_FAKE_GUARD(kMainThreadContext, updateDisplayModes(std::move(modes), activeModeId));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001152}
1153
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001154void RefreshRateSelector::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +00001155 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001156 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +00001157 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001158 [this] {
1159 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1160 if (const auto callbacks = getIdleTimerCallbacks()) {
1161 callbacks->onReset();
1162 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001163 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001164 [this] {
1165 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1166 if (const auto callbacks = getIdleTimerCallbacks()) {
1167 callbacks->onExpired();
1168 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001169 });
Ady Abraham9a2ea342021-09-03 17:32:34 -07001170 }
1171}
1172
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001173void RefreshRateSelector::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001174 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001175
Ady Abraham68636062022-11-16 17:07:25 -08001176 // Invalidate the cached invocation to getRankedFrameRates. This forces
1177 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1178 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001179
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001180 mDisplayModes = std::move(modes);
Ady Abrahamace3d052022-11-17 16:25:05 -08001181 const auto activeModeOpt = mDisplayModes.get(activeModeId);
1182 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
ramindania04b8a52023-08-07 18:49:47 -07001183 mActiveModeOpt = FrameRateMode{activeModeOpt->get()->getPeakFps(),
1184 ftl::as_non_null(activeModeOpt->get())};
Ady Abrahamabc27602020-04-08 17:20:29 -07001185
Ady Abraham68636062022-11-16 17:07:25 -08001186 const auto sortedModes = sortByRefreshRate(mDisplayModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001187 mMinRefreshRateModeIt = sortedModes.front();
1188 mMaxRefreshRateModeIt = sortedModes.back();
1189
Marin Shalamanov75f37252021-02-10 21:43:57 +01001190 // Reset the policy because the old one may no longer be valid.
1191 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001192 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -08001193
Ady Abraham8ca643a2022-10-18 18:26:47 -07001194 mFrameRateOverrideConfig = [&] {
1195 switch (mConfig.enableFrameRateOverride) {
1196 case Config::FrameRateOverride::Disabled:
Ady Abraham68636062022-11-16 17:07:25 -08001197 case Config::FrameRateOverride::AppOverride:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001198 case Config::FrameRateOverride::Enabled:
1199 return mConfig.enableFrameRateOverride;
Ady Abraham68636062022-11-16 17:07:25 -08001200 case Config::FrameRateOverride::AppOverrideNativeRefreshRates:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001201 return shouldEnableFrameRateOverride(sortedModes)
Ady Abraham68636062022-11-16 17:07:25 -08001202 ? Config::FrameRateOverride::AppOverrideNativeRefreshRates
Ady Abraham8ca643a2022-10-18 18:26:47 -07001203 : Config::FrameRateOverride::Disabled;
1204 }
1205 }();
Ady Abraham4899ff82021-01-06 13:53:29 -08001206
Ady Abraham68636062022-11-16 17:07:25 -08001207 if (mConfig.enableFrameRateOverride ==
1208 Config::FrameRateOverride::AppOverrideNativeRefreshRates) {
1209 for (const auto& [_, mode] : mDisplayModes) {
ramindania04b8a52023-08-07 18:49:47 -07001210 mAppOverrideNativeRefreshRates.try_emplace(mode->getPeakFps(), ftl::unit);
Ady Abraham68636062022-11-16 17:07:25 -08001211 }
1212 }
1213
Ady Abrahamabc27602020-04-08 17:20:29 -07001214 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001215}
1216
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001217bool RefreshRateSelector::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001218 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001219 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
ramindania04b8a52023-08-07 18:49:47 -07001220 if (!policy.primaryRanges.physical.includes(mode->get()->getPeakFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001221 ALOGE("Default mode is not in the primary range.");
1222 return false;
1223 }
1224 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001225 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -07001226 return false;
1227 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001228
Ady Abraham68636062022-11-16 17:07:25 -08001229 const auto& primaryRanges = policy.primaryRanges;
1230 const auto& appRequestRanges = policy.appRequestRanges;
1231 ALOGE_IF(!appRequestRanges.physical.includes(primaryRanges.physical),
Ady Abraham08048ce2022-11-30 18:08:00 -08001232 "Physical range is invalid: primary: %s appRequest: %s",
1233 to_string(primaryRanges.physical).c_str(),
1234 to_string(appRequestRanges.physical).c_str());
1235 ALOGE_IF(!appRequestRanges.render.includes(primaryRanges.render),
1236 "Render range is invalid: primary: %s appRequest: %s",
1237 to_string(primaryRanges.render).c_str(), to_string(appRequestRanges.render).c_str());
Ady Abraham68636062022-11-16 17:07:25 -08001238
1239 return primaryRanges.valid() && appRequestRanges.valid();
Steven Thomasd4071902020-03-24 16:02:53 -07001240}
1241
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001242auto RefreshRateSelector::setPolicy(const PolicyVariant& policy) -> SetPolicyResult {
Dominik Laskowski36dced82022-09-02 09:24:00 -07001243 Policy oldPolicy;
Ady Abrahamace3d052022-11-17 16:25:05 -08001244 PhysicalDisplayId displayId;
Dominik Laskowski36dced82022-09-02 09:24:00 -07001245 {
1246 std::lock_guard lock(mLock);
1247 oldPolicy = *getCurrentPolicyLocked();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001248
Dominik Laskowski36dced82022-09-02 09:24:00 -07001249 const bool valid = ftl::match(
1250 policy,
1251 [this](const auto& policy) {
1252 ftl::FakeGuard guard(mLock);
1253 if (!isPolicyValidLocked(policy)) {
1254 ALOGE("Invalid policy: %s", policy.toString().c_str());
1255 return false;
1256 }
1257
1258 using T = std::decay_t<decltype(policy)>;
1259
1260 if constexpr (std::is_same_v<T, DisplayManagerPolicy>) {
1261 mDisplayManagerPolicy = policy;
1262 } else {
1263 static_assert(std::is_same_v<T, OverridePolicy>);
1264 mOverridePolicy = policy;
1265 }
1266 return true;
1267 },
1268 [this](NoOverridePolicy) {
1269 ftl::FakeGuard guard(mLock);
1270 mOverridePolicy.reset();
1271 return true;
1272 });
1273
1274 if (!valid) {
1275 return SetPolicyResult::Invalid;
1276 }
1277
Ady Abraham68636062022-11-16 17:07:25 -08001278 mGetRankedFrameRatesCache.reset();
Dominik Laskowski36dced82022-09-02 09:24:00 -07001279
1280 if (*getCurrentPolicyLocked() == oldPolicy) {
1281 return SetPolicyResult::Unchanged;
1282 }
1283 constructAvailableRefreshRates();
Ady Abrahamace3d052022-11-17 16:25:05 -08001284
1285 displayId = getActiveModeLocked().modePtr->getPhysicalDisplayId();
Steven Thomasd4071902020-03-24 16:02:53 -07001286 }
Dominik Laskowski36dced82022-09-02 09:24:00 -07001287
Dominik Laskowski36dced82022-09-02 09:24:00 -07001288 const unsigned numModeChanges = std::exchange(mNumModeSwitchesInPolicy, 0u);
1289
1290 ALOGI("Display %s policy changed\n"
1291 "Previous: %s\n"
1292 "Current: %s\n"
1293 "%u mode changes were performed under the previous policy",
1294 to_string(displayId).c_str(), oldPolicy.toString().c_str(), toString(policy).c_str(),
1295 numModeChanges);
1296
1297 return SetPolicyResult::Changed;
Steven Thomasd4071902020-03-24 16:02:53 -07001298}
1299
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001300auto RefreshRateSelector::getCurrentPolicyLocked() const -> const Policy* {
Steven Thomasd4071902020-03-24 16:02:53 -07001301 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
1302}
1303
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001304auto RefreshRateSelector::getCurrentPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001305 std::lock_guard lock(mLock);
1306 return *getCurrentPolicyLocked();
1307}
1308
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001309auto RefreshRateSelector::getDisplayManagerPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001310 std::lock_guard lock(mLock);
1311 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001312}
1313
Ady Abrahamace3d052022-11-17 16:25:05 -08001314bool RefreshRateSelector::isModeAllowed(const FrameRateMode& mode) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001315 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001316 return std::find(mAppRequestFrameRates.begin(), mAppRequestFrameRates.end(), mode) !=
1317 mAppRequestFrameRates.end();
Ady Abraham2139f732019-11-13 18:56:40 -08001318}
1319
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001320void RefreshRateSelector::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001321 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -07001322 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001323 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -07001324
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001325 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -08001326
Ady Abraham68636062022-11-16 17:07:25 -08001327 const auto filterRefreshRates = [&](const FpsRanges& ranges,
1328 const char* rangeName) REQUIRES(mLock) {
1329 const auto filterModes = [&](const DisplayMode& mode) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001330 return mode.getResolution() == defaultMode->getResolution() &&
1331 mode.getDpi() == defaultMode->getDpi() &&
1332 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
ramindania04b8a52023-08-07 18:49:47 -07001333 ranges.physical.includes(mode.getPeakFps()) &&
1334 (supportsFrameRateOverride() || ranges.render.includes(mode.getPeakFps()));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001335 };
Ady Abraham8a82ba62020-01-17 12:43:17 -08001336
Ady Abraham90f7fd22023-08-16 11:02:00 -07001337 auto frameRateModes = createFrameRateModes(*policy, filterModes, ranges.render);
Ady Abraham41bf7c62023-07-20 10:33:06 -07001338 if (frameRateModes.empty()) {
1339 ALOGW("No matching frame rate modes for %s range. policy: %s", rangeName,
1340 policy->toString().c_str());
1341 // TODO(b/292105422): Ideally DisplayManager should not send render ranges smaller than
1342 // the min supported. See b/292047939.
1343 // For not we just ignore the render ranges.
Ady Abraham90f7fd22023-08-16 11:02:00 -07001344 frameRateModes = createFrameRateModes(*policy, filterModes, {});
Ady Abraham41bf7c62023-07-20 10:33:06 -07001345 }
Ady Abraham68636062022-11-16 17:07:25 -08001346 LOG_ALWAYS_FATAL_IF(frameRateModes.empty(),
Ady Abraham41bf7c62023-07-20 10:33:06 -07001347 "No matching frame rate modes for %s range even after ignoring the "
1348 "render range. policy: %s",
1349 rangeName, policy->toString().c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -08001350
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001351 const auto stringifyModes = [&] {
1352 std::string str;
Ady Abraham68636062022-11-16 17:07:25 -08001353 for (const auto& frameRateMode : frameRateModes) {
1354 str += to_string(frameRateMode) + " ";
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001355 }
1356 return str;
1357 };
Ady Abraham68636062022-11-16 17:07:25 -08001358 ALOGV("%s render rates: %s", rangeName, stringifyModes().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -07001359
Ady Abraham68636062022-11-16 17:07:25 -08001360 return frameRateModes;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001361 };
1362
Ady Abraham68636062022-11-16 17:07:25 -08001363 mPrimaryFrameRates = filterRefreshRates(policy->primaryRanges, "primary");
1364 mAppRequestFrameRates = filterRefreshRates(policy->appRequestRanges, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -08001365}
1366
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001367Fps RefreshRateSelector::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001368 using namespace fps_approx_ops;
1369
1370 if (frameRate <= mKnownFrameRates.front()) {
1371 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001372 }
1373
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001374 if (frameRate >= mKnownFrameRates.back()) {
1375 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001376 }
1377
Marin Shalamanove8a663d2020-11-24 17:48:00 +01001378 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001379 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001380
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001381 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
1382 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001383 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
1384}
1385
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001386auto RefreshRateSelector::getIdleTimerAction() const -> KernelIdleTimerAction {
Ana Krulecb9afd792020-06-11 13:16:15 -07001387 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001388
ramindania04b8a52023-08-07 18:49:47 -07001389 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getPeakFps();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001390 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -07001391
1392 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
1393 // the min allowed refresh rate is higher than the device min, we do not want to enable the
1394 // timer.
ramindania04b8a52023-08-07 18:49:47 -07001395 if (isStrictlyLess(deviceMinFps, minByPolicy->getPeakFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001396 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001397 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001398
ramindanid72ba162022-09-09 21:33:40 +00001399 const DisplayModePtr& maxByPolicy =
Ady Abrahamace3d052022-11-17 16:25:05 -08001400 getMaxRefreshRateByPolicyLocked(getActiveModeLocked().modePtr->getGroup());
Ana Krulecb9afd792020-06-11 13:16:15 -07001401 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001402 // Turn on the timer when the min of the primary range is below the device min.
1403 if (const Policy* currentPolicy = getCurrentPolicyLocked();
Ady Abraham285f8c12022-10-11 17:12:14 -07001404 isApproxLess(currentPolicy->primaryRanges.physical.min, deviceMinFps)) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001405 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001406 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001407 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001408 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001409
Ana Krulecb9afd792020-06-11 13:16:15 -07001410 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001411 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001412}
1413
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001414int RefreshRateSelector::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -07001415 // This calculation needs to be in sync with the java code
1416 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001417
1418 // The threshold must be smaller than 0.001 in order to differentiate
1419 // between the fractional pairs (e.g. 59.94 and 60).
1420 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001421 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -07001422 const auto numPeriodsRounded = std::round(numPeriods);
1423 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001424 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -07001425 }
1426
Ady Abraham62f216c2020-10-13 19:07:23 -07001427 return static_cast<int>(numPeriodsRounded);
1428}
1429
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001430bool RefreshRateSelector::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001431 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001432 return isFractionalPairOrMultiple(bigger, smaller);
1433 }
1434
1435 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
1436 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001437 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
1438 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001439}
1440
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001441void RefreshRateSelector::dump(utils::Dumper& dumper) const {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001442 using namespace std::string_view_literals;
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001443
Marin Shalamanovba421a82020-11-10 21:49:26 +01001444 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +01001445
Ady Abrahamace3d052022-11-17 16:25:05 -08001446 const auto activeMode = getActiveModeLocked();
1447 dumper.dump("activeMode"sv, to_string(activeMode));
Marin Shalamanovba421a82020-11-10 21:49:26 +01001448
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001449 dumper.dump("displayModes"sv);
1450 {
1451 utils::Dumper::Indent indent(dumper);
1452 for (const auto& [id, mode] : mDisplayModes) {
1453 dumper.dump({}, to_string(*mode));
1454 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001455 }
1456
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001457 dumper.dump("displayManagerPolicy"sv, mDisplayManagerPolicy.toString());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001458
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001459 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
1460 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001461 dumper.dump("overridePolicy"sv, currentPolicy.toString());
ramindani32cf0602022-03-02 02:30:29 +00001462 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001463
Ady Abraham8ca643a2022-10-18 18:26:47 -07001464 dumper.dump("frameRateOverrideConfig"sv, *ftl::enum_name(mFrameRateOverrideConfig));
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001465
Dominik Laskowski03cfce82022-11-02 12:13:29 -04001466 dumper.dump("idleTimer"sv);
1467 {
1468 utils::Dumper::Indent indent(dumper);
1469 dumper.dump("interval"sv, mIdleTimer.transform(&OneShotTimer::interval));
1470 dumper.dump("controller"sv,
1471 mConfig.kernelIdleTimerController
1472 .and_then(&ftl::enum_name<KernelIdleTimerController>)
1473 .value_or("Platform"sv));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001474 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001475}
1476
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001477std::chrono::milliseconds RefreshRateSelector::getIdleTimerTimeout() {
ramindani32cf0602022-03-02 02:30:29 +00001478 return mConfig.idleTimerTimeout;
1479}
1480
Rachel Leece6e0042023-06-27 11:22:54 -07001481// TODO(b/293651105): Extract category FpsRange mapping to OEM-configurable config.
1482FpsRange RefreshRateSelector::getFrameRateCategoryRange(FrameRateCategory category) {
1483 switch (category) {
1484 case FrameRateCategory::High:
1485 return FpsRange{90_Hz, 120_Hz};
1486 case FrameRateCategory::Normal:
1487 return FpsRange{60_Hz, 90_Hz};
1488 case FrameRateCategory::Low:
1489 return FpsRange{30_Hz, 60_Hz};
1490 case FrameRateCategory::NoPreference:
1491 case FrameRateCategory::Default:
1492 LOG_ALWAYS_FATAL("Should not get fps range for frame rate category: %s",
1493 ftl::enum_string(category).c_str());
1494 return FpsRange{0_Hz, 0_Hz};
1495 default:
1496 LOG_ALWAYS_FATAL("Invalid frame rate category for range: %s",
1497 ftl::enum_string(category).c_str());
1498 return FpsRange{0_Hz, 0_Hz};
1499 }
1500}
1501
Ady Abraham2139f732019-11-13 18:56:40 -08001502} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001503
1504// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001505#pragma clang diagnostic pop // ignored "-Wextra"