blob: e378946f1b1fbfa107e1f33f72c94f7efadefd7b [file] [log] [blame]
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001/*
2 * Copyright 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Ady Abraham2139f732019-11-13 18:56:40 -080016
Ady Abraham8a82ba62020-01-17 12:43:17 -080017// #define LOG_NDEBUG 0
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020// TODO(b/129481165): remove the #pragma below and fix conversion issues
21#pragma clang diagnostic push
22#pragma clang diagnostic ignored "-Wextra"
23
Ady Abraham8a82ba62020-01-17 12:43:17 -080024#include <chrono>
25#include <cmath>
Dominik Laskowski530d6bd2022-10-10 16:55:54 -040026#include <deque>
Ady Abraham68636062022-11-16 17:07:25 -080027#include <map>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070028
29#include <android-base/properties.h>
30#include <android-base/stringprintf.h>
31#include <ftl/enum.h>
Dominik Laskowskif8734e02022-08-26 09:06:59 -070032#include <ftl/fake_guard.h>
Dominik Laskowski36dced82022-09-02 09:24:00 -070033#include <ftl/match.h>
Ady Abraham8ca643a2022-10-18 18:26:47 -070034#include <ftl/unit.h>
Ady Abrahamccf63862023-01-19 11:44:01 -080035#include <gui/TraceUtils.h>
Ady Abraham68636062022-11-16 17:07:25 -080036#include <scheduler/FrameRateMode.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070037#include <utils/Trace.h>
38
Ady Abraham4899ff82021-01-06 13:53:29 -080039#include "../SurfaceFlingerProperties.h"
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040040#include "RefreshRateSelector.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080041
ramindania04b8a52023-08-07 18:49:47 -070042#include <com_android_graphics_surfaceflinger_flags.h>
43
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080044#undef LOG_TAG
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040045#define LOG_TAG "RefreshRateSelector"
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080046
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080047namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010048namespace {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070049
ramindania04b8a52023-08-07 18:49:47 -070050using namespace com::android::graphics::surfaceflinger;
51
Dominik Laskowskib0054a22022-03-03 09:03:06 -080052struct RefreshRateScore {
Ady Abraham68636062022-11-16 17:07:25 -080053 FrameRateMode frameRateMode;
Ady Abrahamae2e3c72022-08-13 05:12:13 +000054 float overallScore;
55 struct {
Ady Abraham62f51d92022-08-24 22:20:22 +000056 float modeBelowThreshold;
57 float modeAboveThreshold;
58 } fixedRateBelowThresholdLayersScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -080059};
60
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040061constexpr RefreshRateSelector::GlobalSignals kNoSignals;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080062
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040063std::string formatLayerInfo(const RefreshRateSelector::LayerRequirement& layer, float weight) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080064 return base::StringPrintf("%s (type=%s, weight=%.2f, seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070065 ftl::enum_string(layer.vote).c_str(), weight,
66 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010067 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010068}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010069
Marin Shalamanova7fe3042021-01-29 21:02:08 +010070std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070071 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010072 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010073
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070074 // Add all supported refresh rates.
Dominik Laskowskib0054a22022-03-03 09:03:06 -080075 for (const auto& [id, mode] : modes) {
ramindania04b8a52023-08-07 18:49:47 -070076 knownFrameRates.push_back(mode->getPeakFps());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010077 }
78
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070079 // Sort and remove duplicates.
80 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010081 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070082 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010083 knownFrameRates.end());
84 return knownFrameRates;
85}
86
Ady Abraham68636062022-11-16 17:07:25 -080087std::vector<DisplayModeIterator> sortByRefreshRate(const DisplayModes& modes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080088 std::vector<DisplayModeIterator> sortedModes;
89 sortedModes.reserve(modes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -080090 for (auto it = modes.begin(); it != modes.end(); ++it) {
Ady Abraham68636062022-11-16 17:07:25 -080091 sortedModes.push_back(it);
Dominik Laskowskib0054a22022-03-03 09:03:06 -080092 }
93
94 std::sort(sortedModes.begin(), sortedModes.end(), [](auto it1, auto it2) {
95 const auto& mode1 = it1->second;
96 const auto& mode2 = it2->second;
97
ramindania04b8a52023-08-07 18:49:47 -070098 if (mode1->getVsyncRate().getPeriodNsecs() == mode2->getVsyncRate().getPeriodNsecs()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080099 return mode1->getGroup() > mode2->getGroup();
100 }
101
ramindania04b8a52023-08-07 18:49:47 -0700102 return mode1->getVsyncRate().getPeriodNsecs() > mode2->getVsyncRate().getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800103 });
104
105 return sortedModes;
Marin Shalamanov46084422020-10-13 12:33:42 +0200106}
107
ramindania04b8a52023-08-07 18:49:47 -0700108std::pair<unsigned, unsigned> divisorRange(Fps vsyncRate, Fps peakFps, FpsRange range,
Ady Abraham68636062022-11-16 17:07:25 -0800109 RefreshRateSelector::Config::FrameRateOverride config) {
110 if (config != RefreshRateSelector::Config::FrameRateOverride::Enabled) {
111 return {1, 1};
112 }
113
114 using fps_approx_ops::operator/;
Ady Abraham08048ce2022-11-30 18:08:00 -0800115 // use signed type as `fps / range.max` might be 0
ramindania04b8a52023-08-07 18:49:47 -0700116 auto start = std::max(1, static_cast<int>(peakFps / range.max) - 1);
117 if (flags::vrr_config()) {
118 start = std::max(1,
119 static_cast<int>(vsyncRate /
120 std::min(range.max, peakFps, fps_approx_ops::operator<)) -
121 1);
122 }
123 const auto end = vsyncRate /
Ady Abraham68636062022-11-16 17:07:25 -0800124 std::max(range.min, RefreshRateSelector::kMinSupportedFrameRate,
125 fps_approx_ops::operator<);
126
127 return {start, end};
128}
129
Ady Abraham8ca643a2022-10-18 18:26:47 -0700130bool shouldEnableFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800131 for (const auto it1 : sortedModes) {
132 const auto& mode1 = it1->second;
133 for (const auto it2 : sortedModes) {
134 const auto& mode2 = it2->second;
135
ramindania04b8a52023-08-07 18:49:47 -0700136 if (RefreshRateSelector::getFrameRateDivisor(mode1->getPeakFps(),
137 mode2->getPeakFps()) >= 2) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800138 return true;
139 }
140 }
141 }
142 return false;
143}
144
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400145std::string toString(const RefreshRateSelector::PolicyVariant& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700146 using namespace std::string_literals;
147
148 return ftl::match(
149 policy,
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400150 [](const RefreshRateSelector::DisplayManagerPolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700151 return "DisplayManagerPolicy"s + policy.toString();
152 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400153 [](const RefreshRateSelector::OverridePolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700154 return "OverridePolicy"s + policy.toString();
155 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400156 [](RefreshRateSelector::NoOverridePolicy) { return "NoOverridePolicy"s; });
Dominik Laskowski36dced82022-09-02 09:24:00 -0700157}
158
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800159} // namespace
160
Ady Abraham68636062022-11-16 17:07:25 -0800161auto RefreshRateSelector::createFrameRateModes(
Ady Abraham90f7fd22023-08-16 11:02:00 -0700162 const Policy& policy, std::function<bool(const DisplayMode&)>&& filterModes,
163 const FpsRange& renderRange) const -> std::vector<FrameRateMode> {
Ady Abraham68636062022-11-16 17:07:25 -0800164 struct Key {
165 Fps fps;
166 int32_t group;
167 };
168
169 struct KeyLess {
170 bool operator()(const Key& a, const Key& b) const {
171 using namespace fps_approx_ops;
172 if (a.fps != b.fps) {
173 return a.fps < b.fps;
174 }
175
176 // For the same fps the order doesn't really matter, but we still
177 // want the behaviour of a strictly less operator.
178 // We use the group id as the secondary ordering for that.
179 return a.group < b.group;
180 }
181 };
182
183 std::map<Key, DisplayModeIterator, KeyLess> ratesMap;
184 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
185 const auto& [id, mode] = *it;
186
187 if (!filterModes(*mode)) {
188 continue;
189 }
ramindania04b8a52023-08-07 18:49:47 -0700190 const auto vsyncRate = mode->getVsyncRate();
191 const auto peakFps = mode->getPeakFps();
Ady Abraham68636062022-11-16 17:07:25 -0800192 const auto [start, end] =
ramindania04b8a52023-08-07 18:49:47 -0700193 divisorRange(vsyncRate, peakFps, renderRange, mConfig.enableFrameRateOverride);
Ady Abraham68636062022-11-16 17:07:25 -0800194 for (auto divisor = start; divisor <= end; divisor++) {
ramindania04b8a52023-08-07 18:49:47 -0700195 const auto fps = vsyncRate / divisor;
Ady Abraham68636062022-11-16 17:07:25 -0800196 using fps_approx_ops::operator<;
Ady Abrahamdc0b3a72023-01-04 16:58:27 -0800197 if (divisor > 1 && fps < kMinSupportedFrameRate) {
Ady Abraham68636062022-11-16 17:07:25 -0800198 break;
199 }
200
201 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Enabled &&
202 !renderRange.includes(fps)) {
203 continue;
204 }
205
206 if (mConfig.enableFrameRateOverride ==
207 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
208 !isNativeRefreshRate(fps)) {
209 continue;
210 }
211
212 const auto [existingIter, emplaceHappened] =
213 ratesMap.try_emplace(Key{fps, mode->getGroup()}, it);
214 if (emplaceHappened) {
ramindania04b8a52023-08-07 18:49:47 -0700215 ALOGV("%s: including %s (%s(%s))", __func__, to_string(fps).c_str(),
216 to_string(peakFps).c_str(), to_string(vsyncRate).c_str());
Ady Abraham68636062022-11-16 17:07:25 -0800217 } else {
Ady Abraham90f7fd22023-08-16 11:02:00 -0700218 // If the primary physical range is a single rate, prefer to stay in that rate
219 // even if there is a lower physical refresh rate available. This would cause more
220 // cases to stay within the primary physical range
ramindania04b8a52023-08-07 18:49:47 -0700221 const Fps existingModeFps = existingIter->second->second->getPeakFps();
Ady Abraham90f7fd22023-08-16 11:02:00 -0700222 const bool existingModeIsPrimaryRange = policy.primaryRangeIsSingleRate() &&
223 policy.primaryRanges.physical.includes(existingModeFps);
224 const bool newModeIsPrimaryRange = policy.primaryRangeIsSingleRate() &&
ramindania04b8a52023-08-07 18:49:47 -0700225 policy.primaryRanges.physical.includes(mode->getPeakFps());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700226 if (newModeIsPrimaryRange == existingModeIsPrimaryRange) {
227 // We might need to update the map as we found a lower refresh rate
ramindania04b8a52023-08-07 18:49:47 -0700228 if (isStrictlyLess(mode->getPeakFps(), existingModeFps)) {
Ady Abraham90f7fd22023-08-16 11:02:00 -0700229 existingIter->second = it;
ramindania04b8a52023-08-07 18:49:47 -0700230 ALOGV("%s: changing %s (%s(%s)) as we found a lower physical rate",
231 __func__, to_string(fps).c_str(), to_string(peakFps).c_str(),
232 to_string(vsyncRate).c_str());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700233 }
234 } else if (newModeIsPrimaryRange) {
Ady Abraham68636062022-11-16 17:07:25 -0800235 existingIter->second = it;
ramindania04b8a52023-08-07 18:49:47 -0700236 ALOGV("%s: changing %s (%s(%s)) to stay in the primary range", __func__,
237 to_string(fps).c_str(), to_string(peakFps).c_str(),
238 to_string(vsyncRate).c_str());
Ady Abraham68636062022-11-16 17:07:25 -0800239 }
240 }
241 }
242 }
243
244 std::vector<FrameRateMode> frameRateModes;
245 frameRateModes.reserve(ratesMap.size());
246 for (const auto& [key, mode] : ratesMap) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800247 frameRateModes.emplace_back(FrameRateMode{key.fps, ftl::as_non_null(mode->second)});
Ady Abraham68636062022-11-16 17:07:25 -0800248 }
249
250 // We always want that the lowest frame rate will be corresponding to the
251 // lowest mode for power saving.
252 const auto lowestRefreshRateIt =
253 std::min_element(frameRateModes.begin(), frameRateModes.end(),
254 [](const FrameRateMode& lhs, const FrameRateMode& rhs) {
ramindania04b8a52023-08-07 18:49:47 -0700255 return isStrictlyLess(lhs.modePtr->getVsyncRate(),
256 rhs.modePtr->getVsyncRate());
Ady Abraham68636062022-11-16 17:07:25 -0800257 });
258 frameRateModes.erase(frameRateModes.begin(), lowestRefreshRateIt);
259
260 return frameRateModes;
261}
262
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400263struct RefreshRateSelector::RefreshRateScoreComparator {
ramindanid72ba162022-09-09 21:33:40 +0000264 bool operator()(const RefreshRateScore& lhs, const RefreshRateScore& rhs) const {
Ady Abraham68636062022-11-16 17:07:25 -0800265 const auto& [frameRateMode, overallScore, _] = lhs;
ramindanid72ba162022-09-09 21:33:40 +0000266
Ady Abraham68636062022-11-16 17:07:25 -0800267 std::string name = to_string(frameRateMode);
268
ramindanid72ba162022-09-09 21:33:40 +0000269 ALOGV("%s sorting scores %.2f", name.c_str(), overallScore);
ramindanid72ba162022-09-09 21:33:40 +0000270
Ady Abraham68636062022-11-16 17:07:25 -0800271 if (!ScoredFrameRate::scoresEqual(overallScore, rhs.overallScore)) {
ramindanid72ba162022-09-09 21:33:40 +0000272 return overallScore > rhs.overallScore;
273 }
274
ramindanid72ba162022-09-09 21:33:40 +0000275 if (refreshRateOrder == RefreshRateOrder::Descending) {
276 using fps_approx_ops::operator>;
Ady Abraham68636062022-11-16 17:07:25 -0800277 return frameRateMode.fps > rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000278 } else {
279 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -0800280 return frameRateMode.fps < rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000281 }
282 }
283
284 const RefreshRateOrder refreshRateOrder;
285};
286
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400287std::string RefreshRateSelector::Policy::toString() const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700288 return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
Ady Abraham285f8c12022-10-11 17:12:14 -0700289 ", primaryRanges=%s, appRequestRanges=%s}",
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700290 defaultMode.value(), allowGroupSwitching ? "true" : "false",
Ady Abraham285f8c12022-10-11 17:12:14 -0700291 to_string(primaryRanges).c_str(),
292 to_string(appRequestRanges).c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200293}
294
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400295std::pair<nsecs_t, nsecs_t> RefreshRateSelector::getDisplayFrames(nsecs_t layerPeriod,
296 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800297 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
298 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
299 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
300 quotient++;
301 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800302 }
303
Ady Abraham62a0be22020-12-08 16:54:10 -0800304 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800305}
306
Rachel Leece6e0042023-06-27 11:22:54 -0700307float RefreshRateSelector::calculateNonExactMatchingDefaultLayerScoreLocked(
308 nsecs_t displayPeriod, nsecs_t layerPeriod) const {
309 // Find the actual rate the layer will render, assuming
310 // that layerPeriod is the minimal period to render a frame.
311 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
312 // then the actualLayerPeriod will be 32ms, because it is the
313 // smallest multiple of the display period which is >= layerPeriod.
314 auto actualLayerPeriod = displayPeriod;
315 int multiplier = 1;
316 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
317 multiplier++;
318 actualLayerPeriod = displayPeriod * multiplier;
319 }
320
321 // Because of the threshold we used above it's possible that score is slightly
322 // above 1.
323 return std::min(1.0f, static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
324}
325
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400326float RefreshRateSelector::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
327 Fps refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200328 constexpr float kScoreForFractionalPairs = .8f;
329
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800330 const auto displayPeriod = refreshRate.getPeriodNsecs();
Ady Abraham62a0be22020-12-08 16:54:10 -0800331 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
332 if (layer.vote == LayerVoteType::ExplicitDefault) {
Rachel Leece6e0042023-06-27 11:22:54 -0700333 return calculateNonExactMatchingDefaultLayerScoreLocked(displayPeriod, layerPeriod);
Ady Abraham62a0be22020-12-08 16:54:10 -0800334 }
335
336 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
337 layer.vote == LayerVoteType::Heuristic) {
Ady Abrahambd44e8a2023-07-24 11:30:06 -0700338 using fps_approx_ops::operator<;
339 if (refreshRate < 60_Hz) {
340 const bool favorsAtLeast60 =
341 std::find_if(mFrameRatesThatFavorsAtLeast60.begin(),
342 mFrameRatesThatFavorsAtLeast60.end(), [&](Fps fps) {
343 using fps_approx_ops::operator==;
344 return fps == layer.desiredRefreshRate;
345 }) != mFrameRatesThatFavorsAtLeast60.end();
346 if (favorsAtLeast60) {
347 return 0;
348 }
349 }
350
Ady Abraham68636062022-11-16 17:07:25 -0800351 const float multiplier = refreshRate.getValue() / layer.desiredRefreshRate.getValue();
352
353 // We only want to score this layer as a fractional pair if the content is not
354 // significantly faster than the display rate, at it would cause a significant frame drop.
355 // It is more appropriate to choose a higher display rate even if
356 // a pull-down will be required.
Rachel Lee36426fa2023-03-08 20:13:52 -0800357 constexpr float kMinMultiplier = 0.75f;
Ady Abraham68636062022-11-16 17:07:25 -0800358 if (multiplier >= kMinMultiplier &&
359 isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700360 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200361 }
362
Ady Abraham62a0be22020-12-08 16:54:10 -0800363 // Calculate how many display vsyncs we need to present a single frame for this
364 // layer
365 const auto [displayFramesQuotient, displayFramesRemainder] =
366 getDisplayFrames(layerPeriod, displayPeriod);
367 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
368 if (displayFramesRemainder == 0) {
369 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700370 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800371 }
372
373 if (displayFramesQuotient == 0) {
374 // Layer desired refresh rate is higher than the display rate.
375 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
376 (1.0f / (MAX_FRAMES_TO_FIT + 1));
377 }
378
379 // Layer desired refresh rate is lower than the display rate. Check how well it fits
380 // the cadence.
381 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
382 int iter = 2;
383 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
384 diff = diff - (displayPeriod - diff);
385 iter++;
386 }
387
Ady Abraham05243be2021-09-16 15:58:52 -0700388 return (1.0f / iter);
389 }
390
391 return 0;
392}
393
Ady Abraham68636062022-11-16 17:07:25 -0800394float RefreshRateSelector::calculateDistanceScoreFromMax(Fps refreshRate) const {
395 const auto& maxFps = mAppRequestFrameRates.back().fps;
396 const float ratio = refreshRate.getValue() / maxFps.getValue();
ramindanid72ba162022-09-09 21:33:40 +0000397 // Use ratio^2 to get a lower score the more we get further from peak
398 return ratio * ratio;
399}
400
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400401float RefreshRateSelector::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
402 bool isSeamlessSwitch) const {
Ady Abraham73c3df52023-01-12 18:09:31 -0800403 ATRACE_CALL();
Ady Abraham05243be2021-09-16 15:58:52 -0700404 // Slightly prefer seamless switches.
405 constexpr float kSeamedSwitchPenalty = 0.95f;
406 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
407
Rachel Leece6e0042023-06-27 11:22:54 -0700408 if (layer.vote == LayerVoteType::ExplicitCategory) {
409 if (getFrameRateCategoryRange(layer.frameRateCategory).includes(refreshRate)) {
410 return 1.f;
411 }
412
413 FpsRange categoryRange = getFrameRateCategoryRange(layer.frameRateCategory);
414 using fps_approx_ops::operator<;
415 if (refreshRate < categoryRange.min) {
416 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
417 categoryRange.min
418 .getPeriodNsecs());
419 }
420 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
421 categoryRange.max.getPeriodNsecs());
422 }
423
Ady Abraham05243be2021-09-16 15:58:52 -0700424 // If the layer wants Max, give higher score to the higher refresh rate
425 if (layer.vote == LayerVoteType::Max) {
Ady Abraham68636062022-11-16 17:07:25 -0800426 return calculateDistanceScoreFromMax(refreshRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800427 }
428
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800429 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800430 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Ady Abraham68636062022-11-16 17:07:25 -0800431 if (supportsAppFrameRateOverrideByContent()) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800432 // Since we support frame rate override, allow refresh rates which are
433 // multiples of the layer's request, as those apps would be throttled
434 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800435 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800436 }
437
Ady Abrahamcc315492022-02-17 17:06:39 -0800438 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800439 }
440
Ady Abrahamcc315492022-02-17 17:06:39 -0800441 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700442 // the highest score.
Rachel Leece6e0042023-06-27 11:22:54 -0700443 if (layer.desiredRefreshRate.isValid() &&
444 getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700445 return 1.0f * seamlessness;
446 }
447
Ady Abrahamcc315492022-02-17 17:06:39 -0800448 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700449 // there is a small penalty attached to the score to favor the frame rates
450 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800451 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700452 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
453 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800454}
455
Ady Abraham68636062022-11-16 17:07:25 -0800456auto RefreshRateSelector::getRankedFrameRates(const std::vector<LayerRequirement>& layers,
457 GlobalSignals signals) const -> RankedFrameRates {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200458 std::lock_guard lock(mLock);
459
Ady Abraham68636062022-11-16 17:07:25 -0800460 if (mGetRankedFrameRatesCache &&
461 mGetRankedFrameRatesCache->arguments == std::make_pair(layers, signals)) {
462 return mGetRankedFrameRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200463 }
464
Ady Abraham68636062022-11-16 17:07:25 -0800465 const auto result = getRankedFrameRatesLocked(layers, signals);
466 mGetRankedFrameRatesCache = GetRankedFrameRatesCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200467 return result;
468}
469
Ady Abraham68636062022-11-16 17:07:25 -0800470auto RefreshRateSelector::getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
471 GlobalSignals signals) const
472 -> RankedFrameRates {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000473 using namespace fps_approx_ops;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800474 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800475 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700476
Ady Abrahamace3d052022-11-17 16:25:05 -0800477 const auto& activeMode = *getActiveModeLocked().modePtr;
ramindani38c84982022-08-29 18:02:57 +0000478
Ady Abraham68636062022-11-16 17:07:25 -0800479 // Keep the display at max frame rate for the duration of powering on the display.
ramindani38c84982022-08-29 18:02:57 +0000480 if (signals.powerOnImminent) {
481 ALOGV("Power On Imminent");
Ady Abrahamccf63862023-01-19 11:44:01 -0800482 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Descending);
483 ATRACE_FORMAT_INSTANT("%s (Power On Imminent)",
484 to_string(ranking.front().frameRateMode.fps).c_str());
485 return {ranking, GlobalSignals{.powerOnImminent = true}};
ramindani38c84982022-08-29 18:02:57 +0000486 }
487
Ady Abraham8a82ba62020-01-17 12:43:17 -0800488 int noVoteLayers = 0;
489 int minVoteLayers = 0;
490 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800491 int explicitDefaultVoteLayers = 0;
492 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800493 int explicitExact = 0;
Rachel Leece6e0042023-06-27 11:22:54 -0700494 int explicitCategoryVoteLayers = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100495 int seamedFocusedLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800496
Ady Abraham8a82ba62020-01-17 12:43:17 -0800497 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800498 switch (layer.vote) {
499 case LayerVoteType::NoVote:
500 noVoteLayers++;
501 break;
502 case LayerVoteType::Min:
503 minVoteLayers++;
504 break;
505 case LayerVoteType::Max:
506 maxVoteLayers++;
507 break;
508 case LayerVoteType::ExplicitDefault:
509 explicitDefaultVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800510 break;
511 case LayerVoteType::ExplicitExactOrMultiple:
512 explicitExactOrMultipleVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800513 break;
514 case LayerVoteType::ExplicitExact:
515 explicitExact++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800516 break;
Rachel Leece6e0042023-06-27 11:22:54 -0700517 case LayerVoteType::ExplicitCategory:
518 explicitCategoryVoteLayers++;
Rachel Leef377b362023-09-06 15:01:06 -0700519 if (layer.frameRateCategory == FrameRateCategory::NoPreference) {
520 // Count this layer for Min vote as well. The explicit vote avoids
521 // touch boost and idle for choosing a category, while Min vote is for correct
522 // behavior when all layers are Min or no vote.
523 minVoteLayers++;
524 }
Rachel Leece6e0042023-06-27 11:22:54 -0700525 break;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800526 case LayerVoteType::Heuristic:
527 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800528 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200529
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100530 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
531 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200532 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800533 }
534
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800535 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
Rachel Leece6e0042023-06-27 11:22:54 -0700536 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0 ||
537 explicitCategoryVoteLayers > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700538
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200539 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800540 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700541
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200542 // If the default mode group is different from the group of current mode,
543 // this means a layer requesting a seamed mode switch just disappeared and
544 // we should switch back to the default group.
545 // However if a seamed layer is still present we anchor around the group
546 // of the current mode, in order to prevent unnecessary seamed mode switches
547 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800548 const auto anchorGroup =
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700549 seamedFocusedLayers > 0 ? activeMode.getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200550
Steven Thomasf734df42020-04-13 21:09:28 -0700551 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
552 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800553 if (signals.touch && !hasExplicitVoteLayers) {
ramindanid72ba162022-09-09 21:33:40 +0000554 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800555 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
556 ATRACE_FORMAT_INSTANT("%s (Touch Boost)",
557 to_string(ranking.front().frameRateMode.fps).c_str());
558 return {ranking, GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800559 }
560
Alec Mouri11232a22020-05-14 18:06:25 -0700561 // If the primary range consists of a single refresh rate then we can only
562 // move out the of range if layers explicitly request a different refresh
563 // rate.
Ady Abraham90f7fd22023-08-16 11:02:00 -0700564 if (!signals.touch && signals.idle &&
565 !(policy->primaryRangeIsSingleRate() && hasExplicitVoteLayers)) {
ramindanid72ba162022-09-09 21:33:40 +0000566 ALOGV("Idle");
Ady Abrahamccf63862023-01-19 11:44:01 -0800567 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending);
568 ATRACE_FORMAT_INSTANT("%s (Idle)", to_string(ranking.front().frameRateMode.fps).c_str());
569 return {ranking, GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700570 }
571
Steven Thomasdebafed2020-05-18 17:30:35 -0700572 if (layers.empty() || noVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000573 ALOGV("No layers with votes");
Ady Abrahamccf63862023-01-19 11:44:01 -0800574 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
575 ATRACE_FORMAT_INSTANT("%s (No layers with votes)",
576 to_string(ranking.front().frameRateMode.fps).c_str());
577 return {ranking, kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700578 }
579
Ady Abraham8a82ba62020-01-17 12:43:17 -0800580 // Only if all layers want Min we should return Min
581 if (noVoteLayers + minVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000582 ALOGV("All layers Min");
Ady Abrahamccf63862023-01-19 11:44:01 -0800583 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending);
584 ATRACE_FORMAT_INSTANT("%s (All layers Min)",
585 to_string(ranking.front().frameRateMode.fps).c_str());
586 return {ranking, kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800587 }
588
Ady Abraham8a82ba62020-01-17 12:43:17 -0800589 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800590 std::vector<RefreshRateScore> scores;
Ady Abraham68636062022-11-16 17:07:25 -0800591 scores.reserve(mAppRequestFrameRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800592
Ady Abraham68636062022-11-16 17:07:25 -0800593 for (const FrameRateMode& it : mAppRequestFrameRates) {
594 scores.emplace_back(RefreshRateScore{it, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800595 }
596
597 for (const auto& layer : layers) {
Rachel Leece6e0042023-06-27 11:22:54 -0700598 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f, category %s) ",
599 layer.name.c_str(), ftl::enum_string(layer.vote).c_str(), layer.weight,
600 layer.desiredRefreshRate.getValue(),
601 ftl::enum_string(layer.frameRateCategory).c_str());
Rachel Leed0694bc2023-09-12 14:57:58 -0700602 if (layer.isNoVote() || layer.frameRateCategory == FrameRateCategory::NoPreference ||
603 layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800604 continue;
605 }
606
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800607 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800608
Ady Abraham68636062022-11-16 17:07:25 -0800609 for (auto& [mode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
610 const auto& [fps, modePtr] = mode;
611 const bool isSeamlessSwitch = modePtr->getGroup() == activeMode.getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200612
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100613 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100614 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800615 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700616 to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200617 continue;
618 }
619
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100620 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
621 !layer.focused) {
622 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100623 " 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 Shalamanov53fc11d2020-11-20 14:00:13 +0100626 continue;
627 }
628
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100629 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100630 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100631 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100632 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
633 // disappeared.
Ady Abraham68636062022-11-16 17:07:25 -0800634 const bool isInPolicyForDefault = modePtr->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100635 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100636 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham68636062022-11-16 17:07:25 -0800637 to_string(*modePtr).c_str(), to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200638 continue;
639 }
640
Ady Abraham90f7fd22023-08-16 11:02:00 -0700641 const bool inPrimaryPhysicalRange =
ramindania04b8a52023-08-07 18:49:47 -0700642 policy->primaryRanges.physical.includes(modePtr->getPeakFps());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700643 const bool inPrimaryRenderRange = policy->primaryRanges.render.includes(fps);
644 if (((policy->primaryRangeIsSingleRate() && !inPrimaryPhysicalRange) ||
645 !inPrimaryRenderRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800646 !(layer.focused &&
647 (layer.vote == LayerVoteType::ExplicitDefault ||
648 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700649 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700650 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700651 continue;
652 }
653
Ady Abraham68636062022-11-16 17:07:25 -0800654 const float layerScore = calculateLayerScoreLocked(layer, fps, isSeamlessSwitch);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000655 const float weightedLayerScore = weight * layerScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800656
Ady Abraham13cfb362022-08-13 05:12:13 +0000657 // Layer with fixed source has a special consideration which depends on the
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000658 // mConfig.frameRateMultipleThreshold. We don't want these layers to score
659 // refresh rates above the threshold, but we also don't want to favor the lower
660 // ones by having a greater number of layers scoring them. Instead, we calculate
661 // the score independently for these layers and later decide which
662 // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
663 // score 120 Hz, but desired 60 fps should contribute to the score.
664 const bool fixedSourceLayer = [](LayerVoteType vote) {
665 switch (vote) {
666 case LayerVoteType::ExplicitExactOrMultiple:
667 case LayerVoteType::Heuristic:
668 return true;
669 case LayerVoteType::NoVote:
670 case LayerVoteType::Min:
671 case LayerVoteType::Max:
672 case LayerVoteType::ExplicitDefault:
673 case LayerVoteType::ExplicitExact:
Rachel Leece6e0042023-06-27 11:22:54 -0700674 case LayerVoteType::ExplicitCategory:
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000675 return false;
676 }
677 }(layer.vote);
Ady Abraham62f51d92022-08-24 22:20:22 +0000678 const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000679 layer.desiredRefreshRate <
680 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
Ady Abraham62f51d92022-08-24 22:20:22 +0000681 if (fixedSourceLayer && layerBelowThreshold) {
Ady Abraham13cfb362022-08-13 05:12:13 +0000682 const bool modeAboveThreshold =
ramindania04b8a52023-08-07 18:49:47 -0700683 modePtr->getPeakFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
Ady Abraham62f51d92022-08-24 22:20:22 +0000684 if (modeAboveThreshold) {
ramindania04b8a52023-08-07 18:49:47 -0700685 ALOGV("%s gives %s (%s(%s)) fixed source (above threshold) score of %.4f",
Ady Abraham68636062022-11-16 17:07:25 -0800686 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700687 to_string(modePtr->getPeakFps()).c_str(),
688 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000689 fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000690 } else {
ramindania04b8a52023-08-07 18:49:47 -0700691 ALOGV("%s gives %s (%s(%s)) fixed source (below threshold) score of %.4f",
Ady Abraham68636062022-11-16 17:07:25 -0800692 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700693 to_string(modePtr->getPeakFps()).c_str(),
694 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000695 fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000696 }
697 } else {
ramindania04b8a52023-08-07 18:49:47 -0700698 ALOGV("%s gives %s (%s(%s)) score of %.4f", formatLayerInfo(layer, weight).c_str(),
699 to_string(fps).c_str(), to_string(modePtr->getPeakFps()).c_str(),
700 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000701 overallScore += weightedLayerScore;
702 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800703 }
704 }
705
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000706 // We want to find the best refresh rate without the fixed source layers,
Ady Abraham62f51d92022-08-24 22:20:22 +0000707 // so we could know whether we should add the modeAboveThreshold scores or not.
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000708 // If the best refresh rate is already above the threshold, it means that
709 // some non-fixed source layers already scored it, so we can just add the score
710 // for all fixed source layers, even the ones that are above the threshold.
711 const bool maxScoreAboveThreshold = [&] {
712 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
713 return false;
714 }
715
716 const auto maxScoreIt =
717 std::max_element(scores.begin(), scores.end(),
718 [](RefreshRateScore max, RefreshRateScore current) {
Ady Abraham68636062022-11-16 17:07:25 -0800719 return current.overallScore > max.overallScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000720 });
ramindania04b8a52023-08-07 18:49:47 -0700721 ALOGV("%s (%s(%s)) is the best refresh rate without fixed source layers. It is %s the "
Ady Abraham68636062022-11-16 17:07:25 -0800722 "threshold for "
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000723 "refresh rate multiples",
Ady Abraham68636062022-11-16 17:07:25 -0800724 to_string(maxScoreIt->frameRateMode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700725 to_string(maxScoreIt->frameRateMode.modePtr->getPeakFps()).c_str(),
726 to_string(maxScoreIt->frameRateMode.modePtr->getVsyncRate()).c_str(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000727 maxScoreAboveThreshold ? "above" : "below");
ramindania04b8a52023-08-07 18:49:47 -0700728 return maxScoreIt->frameRateMode.modePtr->getPeakFps() >=
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000729 Fps::fromValue(mConfig.frameRateMultipleThreshold);
730 }();
731
732 // Now we can add the fixed rate layers score
Ady Abraham68636062022-11-16 17:07:25 -0800733 for (auto& [frameRateMode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000734 overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000735 if (maxScoreAboveThreshold) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000736 overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000737 }
ramindania04b8a52023-08-07 18:49:47 -0700738 ALOGV("%s (%s(%s)) adjusted overallScore is %.4f", to_string(frameRateMode.fps).c_str(),
739 to_string(frameRateMode.modePtr->getPeakFps()).c_str(),
740 to_string(frameRateMode.modePtr->getVsyncRate()).c_str(), overallScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000741 }
742
743 // Now that we scored all the refresh rates we need to pick the one that got the highest
ramindanid72ba162022-09-09 21:33:40 +0000744 // overallScore. Sort the scores based on their overallScore in descending order of priority.
745 const RefreshRateOrder refreshRateOrder =
746 maxVoteLayers > 0 ? RefreshRateOrder::Descending : RefreshRateOrder::Ascending;
747 std::sort(scores.begin(), scores.end(),
748 RefreshRateScoreComparator{.refreshRateOrder = refreshRateOrder});
ramindanid72ba162022-09-09 21:33:40 +0000749
Ady Abraham68636062022-11-16 17:07:25 -0800750 FrameRateRanking ranking;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400751 ranking.reserve(scores.size());
752
753 std::transform(scores.begin(), scores.end(), back_inserter(ranking),
ramindanid72ba162022-09-09 21:33:40 +0000754 [](const RefreshRateScore& score) {
Ady Abraham68636062022-11-16 17:07:25 -0800755 return ScoredFrameRate{score.frameRateMode, score.overallScore};
ramindanid72ba162022-09-09 21:33:40 +0000756 });
Ady Abraham34702102020-02-10 14:12:05 -0800757
Ady Abraham37d46922022-10-05 13:08:51 -0700758 const bool noLayerScore = std::all_of(scores.begin(), scores.end(), [](RefreshRateScore score) {
759 return score.overallScore == 0;
760 });
761
Ady Abraham90f7fd22023-08-16 11:02:00 -0700762 if (policy->primaryRangeIsSingleRate()) {
Alec Mouri11232a22020-05-14 18:06:25 -0700763 // If we never scored any layers, then choose the rate from the primary
764 // range instead of picking a random score from the app range.
Ady Abraham37d46922022-10-05 13:08:51 -0700765 if (noLayerScore) {
ramindanid72ba162022-09-09 21:33:40 +0000766 ALOGV("Layers not scored");
Ady Abrahamccf63862023-01-19 11:44:01 -0800767 const auto descending = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
768 ATRACE_FORMAT_INSTANT("%s (Layers not scored)",
769 to_string(descending.front().frameRateMode.fps).c_str());
770 return {descending, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700771 } else {
Ady Abrahamccf63862023-01-19 11:44:01 -0800772 ATRACE_FORMAT_INSTANT("%s (primaryRangeIsSingleRate)",
773 to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400774 return {ranking, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700775 }
776 }
777
Steven Thomasf734df42020-04-13 21:09:28 -0700778 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
779 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
780 // vote we should not change it if we get a touch event. Only apply touch boost if it will
781 // actually increase the refresh rate over the normal selection.
Ady Abraham5e4e9832021-06-14 13:40:56 -0700782 const bool touchBoostForExplicitExact = [&] {
Ady Abraham68636062022-11-16 17:07:25 -0800783 if (supportsAppFrameRateOverrideByContent()) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700784 // Enable touch boost if there are other layers besides exact
785 return explicitExact + noVoteLayers != layers.size();
786 } else {
787 // Enable touch boost if there are no exact layers
788 return explicitExact == 0;
789 }
790 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700791
Ady Abraham68636062022-11-16 17:07:25 -0800792 const auto touchRefreshRates = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700793 using fps_approx_ops::operator<;
794
Rachel Leece6e0042023-06-27 11:22:54 -0700795 if (signals.touch && explicitDefaultVoteLayers == 0 && explicitCategoryVoteLayers == 0 &&
796 touchBoostForExplicitExact &&
Ady Abraham68636062022-11-16 17:07:25 -0800797 scores.front().frameRateMode.fps < touchRefreshRates.front().frameRateMode.fps) {
ramindanid72ba162022-09-09 21:33:40 +0000798 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800799 ATRACE_FORMAT_INSTANT("%s (Touch Boost [late])",
800 to_string(touchRefreshRates.front().frameRateMode.fps).c_str());
ramindanid72ba162022-09-09 21:33:40 +0000801 return {touchRefreshRates, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700802 }
803
Ady Abraham37d46922022-10-05 13:08:51 -0700804 // If we never scored any layers, and we don't favor high refresh rates, prefer to stay with the
805 // current config
806 if (noLayerScore && refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abrahamccf63862023-01-19 11:44:01 -0800807 const auto ascendingWithPreferred =
808 rankFrameRates(anchorGroup, RefreshRateOrder::Ascending, activeMode.getId());
809 ATRACE_FORMAT_INSTANT("%s (preferredDisplayMode)",
810 to_string(ascendingWithPreferred.front().frameRateMode.fps).c_str());
811 return {ascendingWithPreferred, kNoSignals};
Ady Abraham37d46922022-10-05 13:08:51 -0700812 }
813
Ady Abrahamccf63862023-01-19 11:44:01 -0800814 ATRACE_FORMAT_INSTANT("%s (scored))", to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400815 return {ranking, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800816}
817
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400818using LayerRequirementPtrs = std::vector<const RefreshRateSelector::LayerRequirement*>;
819using PerUidLayerRequirements = std::unordered_map<uid_t, LayerRequirementPtrs>;
820
821PerUidLayerRequirements groupLayersByUid(
822 const std::vector<RefreshRateSelector::LayerRequirement>& layers) {
823 PerUidLayerRequirements layersByUid;
Ady Abraham62a0be22020-12-08 16:54:10 -0800824 for (const auto& layer : layers) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400825 const auto it = layersByUid.emplace(layer.ownerUid, LayerRequirementPtrs()).first;
826 auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800827 layersWithSameUid.push_back(&layer);
828 }
829
830 // Remove uids that can't have a frame rate override
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400831 for (auto it = layersByUid.begin(); it != layersByUid.end();) {
832 const auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800833 bool skipUid = false;
834 for (const auto& layer : layersWithSameUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400835 using LayerVoteType = RefreshRateSelector::LayerVoteType;
836
837 if (layer->vote == LayerVoteType::Max || layer->vote == LayerVoteType::Heuristic) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800838 skipUid = true;
839 break;
840 }
841 }
842 if (skipUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400843 it = layersByUid.erase(it);
Ady Abraham62a0be22020-12-08 16:54:10 -0800844 } else {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400845 ++it;
Ady Abraham62a0be22020-12-08 16:54:10 -0800846 }
847 }
848
849 return layersByUid;
850}
851
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400852auto RefreshRateSelector::getFrameRateOverrides(const std::vector<LayerRequirement>& layers,
853 Fps displayRefreshRate,
854 GlobalSignals globalSignals) const
855 -> UidToFrameRateOverride {
Ady Abraham62a0be22020-12-08 16:54:10 -0800856 ATRACE_CALL();
Ady Abraham68636062022-11-16 17:07:25 -0800857 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Disabled) {
858 return {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800859 }
860
Ady Abraham68636062022-11-16 17:07:25 -0800861 ALOGV("%s: %zu layers", __func__, layers.size());
862 std::lock_guard lock(mLock);
863
Ady Abraham8ca643a2022-10-18 18:26:47 -0700864 const auto* policyPtr = getCurrentPolicyLocked();
865 // We don't want to run lower than 30fps
ramindania04b8a52023-08-07 18:49:47 -0700866 // TODO(b/297600226): revise this for dVRR
Ady Abraham8ca643a2022-10-18 18:26:47 -0700867 const Fps minFrameRate = std::max(policyPtr->appRequestRanges.render.min, 30_Hz, isApproxLess);
868
869 using fps_approx_ops::operator/;
870 const unsigned numMultiples = displayRefreshRate / minFrameRate;
871
872 std::vector<std::pair<Fps, float>> scoredFrameRates;
873 scoredFrameRates.reserve(numMultiples);
874
875 for (unsigned n = numMultiples; n > 0; n--) {
876 const Fps divisor = displayRefreshRate / n;
877 if (mConfig.enableFrameRateOverride ==
Ady Abraham68636062022-11-16 17:07:25 -0800878 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
879 !isNativeRefreshRate(divisor)) {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700880 continue;
881 }
882
883 if (policyPtr->appRequestRanges.render.includes(divisor)) {
884 ALOGV("%s: adding %s as a potential frame rate", __func__, to_string(divisor).c_str());
885 scoredFrameRates.emplace_back(divisor, 0);
886 }
887 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800888
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400889 const auto layersByUid = groupLayersByUid(layers);
Ady Abraham62a0be22020-12-08 16:54:10 -0800890 UidToFrameRateOverride frameRateOverrides;
891 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800892 // Layers with ExplicitExactOrMultiple expect touch boost
893 const bool hasExplicitExactOrMultiple =
894 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
895 [](const auto& layer) {
896 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
897 });
898
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700899 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800900 continue;
901 }
902
Ady Abraham8ca643a2022-10-18 18:26:47 -0700903 for (auto& [_, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800904 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -0800905 }
906
907 for (const auto& layer : layersWithSameUid) {
Rachel Lee47adfcf2023-09-15 17:36:56 -0700908 if (layer->isNoVote() || layer->frameRateCategory == FrameRateCategory::NoPreference ||
909 layer->vote == LayerVoteType::Min) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800910 continue;
911 }
912
913 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Rachel Leece6e0042023-06-27 11:22:54 -0700914 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
915 layer->vote != LayerVoteType::ExplicitExact &&
916 layer->vote != LayerVoteType::ExplicitCategory,
917 "Invalid layer vote type for frame rate overrides");
Ady Abraham8ca643a2022-10-18 18:26:47 -0700918 for (auto& [fps, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800919 constexpr bool isSeamlessSwitch = true;
Ady Abraham8ca643a2022-10-18 18:26:47 -0700920 const auto layerScore = calculateLayerScoreLocked(*layer, fps, isSeamlessSwitch);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800921 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -0800922 }
923 }
924
Ady Abraham62a0be22020-12-08 16:54:10 -0800925 // If we never scored any layers, we don't have a preferred frame rate
Ady Abraham8ca643a2022-10-18 18:26:47 -0700926 if (std::all_of(scoredFrameRates.begin(), scoredFrameRates.end(),
927 [](const auto& scoredFrameRate) {
928 const auto [_, score] = scoredFrameRate;
929 return score == 0;
930 })) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800931 continue;
932 }
933
ramindanid72ba162022-09-09 21:33:40 +0000934 // Now that we scored all the refresh rates we need to pick the lowest refresh rate
935 // that got the highest score.
Ady Abraham8ca643a2022-10-18 18:26:47 -0700936 const auto [overrideFps, _] =
937 *std::max_element(scoredFrameRates.begin(), scoredFrameRates.end(),
938 [](const auto& lhsPair, const auto& rhsPair) {
939 const float lhs = lhsPair.second;
940 const float rhs = rhsPair.second;
Ady Abraham68636062022-11-16 17:07:25 -0800941 return lhs < rhs && !ScoredFrameRate::scoresEqual(lhs, rhs);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700942 });
943 ALOGV("%s: overriding to %s for uid=%d", __func__, to_string(overrideFps).c_str(), uid);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700944 ATRACE_FORMAT_INSTANT("%s: overriding to %s for uid=%d", __func__,
945 to_string(overrideFps).c_str(), uid);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700946 frameRateOverrides.emplace(uid, overrideFps);
Ady Abraham62a0be22020-12-08 16:54:10 -0800947 }
948
949 return frameRateOverrides;
950}
951
Ady Abraham0aa373a2022-11-22 13:56:50 -0800952ftl::Optional<FrameRateMode> RefreshRateSelector::onKernelTimerChanged(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800953 std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800954 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100955
Ady Abraham0aa373a2022-11-22 13:56:50 -0800956 const auto current = [&]() REQUIRES(mLock) -> FrameRateMode {
957 if (desiredActiveModeId) {
958 const auto& modePtr = mDisplayModes.get(*desiredActiveModeId)->get();
ramindania04b8a52023-08-07 18:49:47 -0700959 return FrameRateMode{modePtr->getPeakFps(), ftl::as_non_null(modePtr)};
Ady Abraham0aa373a2022-11-22 13:56:50 -0800960 }
961
962 return getActiveModeLocked();
963 }();
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100964
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800965 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
Ady Abraham0aa373a2022-11-22 13:56:50 -0800966 if (current.modePtr->getId() == min->getId()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800967 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100968 }
969
ramindania04b8a52023-08-07 18:49:47 -0700970 return timerExpired ? FrameRateMode{min->getPeakFps(), ftl::as_non_null(min)} : current;
Steven Thomasf734df42020-04-13 21:09:28 -0700971}
972
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400973const DisplayModePtr& RefreshRateSelector::getMinRefreshRateByPolicyLocked() const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800974 const auto& activeMode = *getActiveModeLocked().modePtr;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700975
Ady Abraham68636062022-11-16 17:07:25 -0800976 for (const FrameRateMode& mode : mPrimaryFrameRates) {
977 if (activeMode.getGroup() == mode.modePtr->getGroup()) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800978 return mode.modePtr.get();
Marin Shalamanov46084422020-10-13 12:33:42 +0200979 }
980 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800981
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700982 ALOGE("Can't find min refresh rate by policy with the same mode group as the current mode %s",
983 to_string(activeMode).c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800984
985 // Default to the lowest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -0800986 return mPrimaryFrameRates.front().modePtr.get();
Ady Abraham2139f732019-11-13 18:56:40 -0800987}
988
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400989const DisplayModePtr& RefreshRateSelector::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800990 const ftl::NonNull<DisplayModePtr>* maxByAnchor = &mPrimaryFrameRates.back().modePtr;
991 const ftl::NonNull<DisplayModePtr>* max = &mPrimaryFrameRates.back().modePtr;
Ady Abraham68636062022-11-16 17:07:25 -0800992
993 bool maxByAnchorFound = false;
994 for (auto it = mPrimaryFrameRates.rbegin(); it != mPrimaryFrameRates.rend(); ++it) {
995 using namespace fps_approx_ops;
ramindania04b8a52023-08-07 18:49:47 -0700996 if (it->modePtr->getPeakFps() > (*max)->getPeakFps()) {
Ady Abraham68636062022-11-16 17:07:25 -0800997 max = &it->modePtr;
Marin Shalamanov46084422020-10-13 12:33:42 +0200998 }
Ady Abraham68636062022-11-16 17:07:25 -0800999
1000 if (anchorGroup == it->modePtr->getGroup() &&
ramindania04b8a52023-08-07 18:49:47 -07001001 it->modePtr->getPeakFps() >= (*maxByAnchor)->getPeakFps()) {
Ady Abraham68636062022-11-16 17:07:25 -08001002 maxByAnchorFound = true;
1003 maxByAnchor = &it->modePtr;
1004 }
1005 }
1006
1007 if (maxByAnchorFound) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001008 return maxByAnchor->get();
Marin Shalamanov46084422020-10-13 12:33:42 +02001009 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001010
ramindanid72ba162022-09-09 21:33:40 +00001011 ALOGE("Can't find max refresh rate by policy with the same group %d", anchorGroup);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001012
1013 // Default to the highest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -08001014 return max->get();
Ady Abraham2139f732019-11-13 18:56:40 -08001015}
1016
Ady Abraham68636062022-11-16 17:07:25 -08001017auto RefreshRateSelector::rankFrameRates(std::optional<int> anchorGroupOpt,
1018 RefreshRateOrder refreshRateOrder,
1019 std::optional<DisplayModeId> preferredDisplayModeOpt) const
1020 -> FrameRateRanking {
Ady Abrahama5992df2023-01-27 21:10:57 -08001021 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -08001022 const char* const whence = __func__;
Ady Abrahama5992df2023-01-27 21:10:57 -08001023
1024 // find the highest frame rate for each display mode
1025 ftl::SmallMap<DisplayModeId, Fps, 8> maxRenderRateForMode;
1026 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
1027 if (ascending) {
1028 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1029 // use a lower frame rate when we want Ascending frame rates.
1030 for (const auto& frameRateMode : mPrimaryFrameRates) {
1031 if (anchorGroupOpt && frameRateMode.modePtr->getGroup() != anchorGroupOpt) {
1032 continue;
1033 }
1034
1035 const auto [iter, _] = maxRenderRateForMode.try_emplace(frameRateMode.modePtr->getId(),
1036 frameRateMode.fps);
1037 if (iter->second < frameRateMode.fps) {
1038 iter->second = frameRateMode.fps;
1039 }
1040 }
1041 }
1042
Ady Abraham68636062022-11-16 17:07:25 -08001043 std::deque<ScoredFrameRate> ranking;
1044 const auto rankFrameRate = [&](const FrameRateMode& frameRateMode) REQUIRES(mLock) {
1045 const auto& modePtr = frameRateMode.modePtr;
1046 if (anchorGroupOpt && modePtr->getGroup() != anchorGroupOpt) {
Ady Abraham37d46922022-10-05 13:08:51 -07001047 return;
ramindanid72ba162022-09-09 21:33:40 +00001048 }
Ady Abraham37d46922022-10-05 13:08:51 -07001049
Ady Abraham3f965922023-01-23 17:18:29 -08001050 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
ramindanif7075202023-03-10 00:24:34 +00001051 const auto id = modePtr->getId();
Ady Abrahama5992df2023-01-27 21:10:57 -08001052 if (ascending && frameRateMode.fps < *maxRenderRateForMode.get(id)) {
Ady Abraham3f965922023-01-23 17:18:29 -08001053 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1054 // use a lower frame rate when we want Ascending frame rates.
1055 return;
1056 }
1057
Ady Abraham68636062022-11-16 17:07:25 -08001058 float score = calculateDistanceScoreFromMax(frameRateMode.fps);
Ady Abraham3f965922023-01-23 17:18:29 -08001059
1060 if (ascending) {
Ady Abraham37d46922022-10-05 13:08:51 -07001061 score = 1.0f / score;
1062 }
ramindanif7075202023-03-10 00:24:34 +00001063
1064 constexpr float kScore = std::numeric_limits<float>::max();
Ady Abraham37d46922022-10-05 13:08:51 -07001065 if (preferredDisplayModeOpt) {
Ady Abraham68636062022-11-16 17:07:25 -08001066 if (*preferredDisplayModeOpt == modePtr->getId()) {
Ady Abraham68636062022-11-16 17:07:25 -08001067 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
Ady Abraham37d46922022-10-05 13:08:51 -07001068 return;
1069 }
1070 constexpr float kNonPreferredModePenalty = 0.95f;
1071 score *= kNonPreferredModePenalty;
ramindanif7075202023-03-10 00:24:34 +00001072 } else if (ascending && id == getMinRefreshRateByPolicyLocked()->getId()) {
1073 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround
1074 // and actually use a lower frame rate when we want Ascending frame rates.
1075 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
1076 return;
Ady Abraham37d46922022-10-05 13:08:51 -07001077 }
Ady Abraham3f965922023-01-23 17:18:29 -08001078
ramindania04b8a52023-08-07 18:49:47 -07001079 ALOGV("%s(%s) %s (%s(%s)) scored %.2f", whence, ftl::enum_string(refreshRateOrder).c_str(),
1080 to_string(frameRateMode.fps).c_str(), to_string(modePtr->getPeakFps()).c_str(),
1081 to_string(modePtr->getVsyncRate()).c_str(), score);
Ady Abraham68636062022-11-16 17:07:25 -08001082 ranking.emplace_back(ScoredFrameRate{frameRateMode, score});
ramindanid72ba162022-09-09 21:33:40 +00001083 };
1084
1085 if (refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abraham68636062022-11-16 17:07:25 -08001086 std::for_each(mPrimaryFrameRates.begin(), mPrimaryFrameRates.end(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001087 } else {
Ady Abraham68636062022-11-16 17:07:25 -08001088 std::for_each(mPrimaryFrameRates.rbegin(), mPrimaryFrameRates.rend(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001089 }
1090
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001091 if (!ranking.empty() || !anchorGroupOpt) {
1092 return {ranking.begin(), ranking.end()};
ramindanid72ba162022-09-09 21:33:40 +00001093 }
1094
1095 ALOGW("Can't find %s refresh rate by policy with the same mode group"
1096 " as the mode group %d",
1097 refreshRateOrder == RefreshRateOrder::Ascending ? "min" : "max", anchorGroupOpt.value());
1098
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001099 constexpr std::optional<int> kNoAnchorGroup = std::nullopt;
Ady Abraham68636062022-11-16 17:07:25 -08001100 return rankFrameRates(kNoAnchorGroup, refreshRateOrder, preferredDisplayModeOpt);
ramindanid72ba162022-09-09 21:33:40 +00001101}
1102
Ady Abrahamace3d052022-11-17 16:25:05 -08001103FrameRateMode RefreshRateSelector::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -08001104 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001105 return getActiveModeLocked();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001106}
1107
Ady Abrahamace3d052022-11-17 16:25:05 -08001108const FrameRateMode& RefreshRateSelector::getActiveModeLocked() const {
1109 return *mActiveModeOpt;
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001110}
1111
Ady Abrahamace3d052022-11-17 16:25:05 -08001112void RefreshRateSelector::setActiveMode(DisplayModeId modeId, Fps renderFrameRate) {
Ady Abraham2139f732019-11-13 18:56:40 -08001113 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001114
Ady Abraham68636062022-11-16 17:07:25 -08001115 // Invalidate the cached invocation to getRankedFrameRates. This forces
1116 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1117 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001118
Ady Abrahamace3d052022-11-17 16:25:05 -08001119 const auto activeModeOpt = mDisplayModes.get(modeId);
1120 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1121
1122 mActiveModeOpt.emplace(FrameRateMode{renderFrameRate, ftl::as_non_null(activeModeOpt->get())});
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001123}
1124
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001125RefreshRateSelector::RefreshRateSelector(DisplayModes modes, DisplayModeId activeModeId,
1126 Config config)
rnlee3bd610662021-06-23 16:27:57 -07001127 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001128 initializeIdleTimer();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001129 FTL_FAKE_GUARD(kMainThreadContext, updateDisplayModes(std::move(modes), activeModeId));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001130}
1131
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001132void RefreshRateSelector::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +00001133 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001134 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +00001135 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001136 [this] {
1137 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1138 if (const auto callbacks = getIdleTimerCallbacks()) {
1139 callbacks->onReset();
1140 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001141 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001142 [this] {
1143 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1144 if (const auto callbacks = getIdleTimerCallbacks()) {
1145 callbacks->onExpired();
1146 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001147 });
Ady Abraham9a2ea342021-09-03 17:32:34 -07001148 }
1149}
1150
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001151void RefreshRateSelector::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001152 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001153
Ady Abraham68636062022-11-16 17:07:25 -08001154 // Invalidate the cached invocation to getRankedFrameRates. This forces
1155 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1156 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001157
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001158 mDisplayModes = std::move(modes);
Ady Abrahamace3d052022-11-17 16:25:05 -08001159 const auto activeModeOpt = mDisplayModes.get(activeModeId);
1160 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
ramindania04b8a52023-08-07 18:49:47 -07001161 mActiveModeOpt = FrameRateMode{activeModeOpt->get()->getPeakFps(),
1162 ftl::as_non_null(activeModeOpt->get())};
Ady Abrahamabc27602020-04-08 17:20:29 -07001163
Ady Abraham68636062022-11-16 17:07:25 -08001164 const auto sortedModes = sortByRefreshRate(mDisplayModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001165 mMinRefreshRateModeIt = sortedModes.front();
1166 mMaxRefreshRateModeIt = sortedModes.back();
1167
Marin Shalamanov75f37252021-02-10 21:43:57 +01001168 // Reset the policy because the old one may no longer be valid.
1169 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001170 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -08001171
Ady Abraham8ca643a2022-10-18 18:26:47 -07001172 mFrameRateOverrideConfig = [&] {
1173 switch (mConfig.enableFrameRateOverride) {
1174 case Config::FrameRateOverride::Disabled:
Ady Abraham68636062022-11-16 17:07:25 -08001175 case Config::FrameRateOverride::AppOverride:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001176 case Config::FrameRateOverride::Enabled:
1177 return mConfig.enableFrameRateOverride;
Ady Abraham68636062022-11-16 17:07:25 -08001178 case Config::FrameRateOverride::AppOverrideNativeRefreshRates:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001179 return shouldEnableFrameRateOverride(sortedModes)
Ady Abraham68636062022-11-16 17:07:25 -08001180 ? Config::FrameRateOverride::AppOverrideNativeRefreshRates
Ady Abraham8ca643a2022-10-18 18:26:47 -07001181 : Config::FrameRateOverride::Disabled;
1182 }
1183 }();
Ady Abraham4899ff82021-01-06 13:53:29 -08001184
Ady Abraham68636062022-11-16 17:07:25 -08001185 if (mConfig.enableFrameRateOverride ==
1186 Config::FrameRateOverride::AppOverrideNativeRefreshRates) {
1187 for (const auto& [_, mode] : mDisplayModes) {
ramindania04b8a52023-08-07 18:49:47 -07001188 mAppOverrideNativeRefreshRates.try_emplace(mode->getPeakFps(), ftl::unit);
Ady Abraham68636062022-11-16 17:07:25 -08001189 }
1190 }
1191
Ady Abrahamabc27602020-04-08 17:20:29 -07001192 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001193}
1194
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001195bool RefreshRateSelector::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001196 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001197 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
ramindania04b8a52023-08-07 18:49:47 -07001198 if (!policy.primaryRanges.physical.includes(mode->get()->getPeakFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001199 ALOGE("Default mode is not in the primary range.");
1200 return false;
1201 }
1202 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001203 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -07001204 return false;
1205 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001206
Ady Abraham68636062022-11-16 17:07:25 -08001207 const auto& primaryRanges = policy.primaryRanges;
1208 const auto& appRequestRanges = policy.appRequestRanges;
1209 ALOGE_IF(!appRequestRanges.physical.includes(primaryRanges.physical),
Ady Abraham08048ce2022-11-30 18:08:00 -08001210 "Physical range is invalid: primary: %s appRequest: %s",
1211 to_string(primaryRanges.physical).c_str(),
1212 to_string(appRequestRanges.physical).c_str());
1213 ALOGE_IF(!appRequestRanges.render.includes(primaryRanges.render),
1214 "Render range is invalid: primary: %s appRequest: %s",
1215 to_string(primaryRanges.render).c_str(), to_string(appRequestRanges.render).c_str());
Ady Abraham68636062022-11-16 17:07:25 -08001216
1217 return primaryRanges.valid() && appRequestRanges.valid();
Steven Thomasd4071902020-03-24 16:02:53 -07001218}
1219
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001220auto RefreshRateSelector::setPolicy(const PolicyVariant& policy) -> SetPolicyResult {
Dominik Laskowski36dced82022-09-02 09:24:00 -07001221 Policy oldPolicy;
Ady Abrahamace3d052022-11-17 16:25:05 -08001222 PhysicalDisplayId displayId;
Dominik Laskowski36dced82022-09-02 09:24:00 -07001223 {
1224 std::lock_guard lock(mLock);
1225 oldPolicy = *getCurrentPolicyLocked();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001226
Dominik Laskowski36dced82022-09-02 09:24:00 -07001227 const bool valid = ftl::match(
1228 policy,
1229 [this](const auto& policy) {
1230 ftl::FakeGuard guard(mLock);
1231 if (!isPolicyValidLocked(policy)) {
1232 ALOGE("Invalid policy: %s", policy.toString().c_str());
1233 return false;
1234 }
1235
1236 using T = std::decay_t<decltype(policy)>;
1237
1238 if constexpr (std::is_same_v<T, DisplayManagerPolicy>) {
1239 mDisplayManagerPolicy = policy;
1240 } else {
1241 static_assert(std::is_same_v<T, OverridePolicy>);
1242 mOverridePolicy = policy;
1243 }
1244 return true;
1245 },
1246 [this](NoOverridePolicy) {
1247 ftl::FakeGuard guard(mLock);
1248 mOverridePolicy.reset();
1249 return true;
1250 });
1251
1252 if (!valid) {
1253 return SetPolicyResult::Invalid;
1254 }
1255
Ady Abraham68636062022-11-16 17:07:25 -08001256 mGetRankedFrameRatesCache.reset();
Dominik Laskowski36dced82022-09-02 09:24:00 -07001257
1258 if (*getCurrentPolicyLocked() == oldPolicy) {
1259 return SetPolicyResult::Unchanged;
1260 }
1261 constructAvailableRefreshRates();
Ady Abrahamace3d052022-11-17 16:25:05 -08001262
1263 displayId = getActiveModeLocked().modePtr->getPhysicalDisplayId();
Steven Thomasd4071902020-03-24 16:02:53 -07001264 }
Dominik Laskowski36dced82022-09-02 09:24:00 -07001265
Dominik Laskowski36dced82022-09-02 09:24:00 -07001266 const unsigned numModeChanges = std::exchange(mNumModeSwitchesInPolicy, 0u);
1267
1268 ALOGI("Display %s policy changed\n"
1269 "Previous: %s\n"
1270 "Current: %s\n"
1271 "%u mode changes were performed under the previous policy",
1272 to_string(displayId).c_str(), oldPolicy.toString().c_str(), toString(policy).c_str(),
1273 numModeChanges);
1274
1275 return SetPolicyResult::Changed;
Steven Thomasd4071902020-03-24 16:02:53 -07001276}
1277
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001278auto RefreshRateSelector::getCurrentPolicyLocked() const -> const Policy* {
Steven Thomasd4071902020-03-24 16:02:53 -07001279 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
1280}
1281
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001282auto RefreshRateSelector::getCurrentPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001283 std::lock_guard lock(mLock);
1284 return *getCurrentPolicyLocked();
1285}
1286
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001287auto RefreshRateSelector::getDisplayManagerPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001288 std::lock_guard lock(mLock);
1289 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001290}
1291
Ady Abrahamace3d052022-11-17 16:25:05 -08001292bool RefreshRateSelector::isModeAllowed(const FrameRateMode& mode) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001293 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001294 return std::find(mAppRequestFrameRates.begin(), mAppRequestFrameRates.end(), mode) !=
1295 mAppRequestFrameRates.end();
Ady Abraham2139f732019-11-13 18:56:40 -08001296}
1297
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001298void RefreshRateSelector::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001299 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -07001300 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001301 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -07001302
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001303 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -08001304
Ady Abraham68636062022-11-16 17:07:25 -08001305 const auto filterRefreshRates = [&](const FpsRanges& ranges,
1306 const char* rangeName) REQUIRES(mLock) {
1307 const auto filterModes = [&](const DisplayMode& mode) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001308 return mode.getResolution() == defaultMode->getResolution() &&
1309 mode.getDpi() == defaultMode->getDpi() &&
1310 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
ramindania04b8a52023-08-07 18:49:47 -07001311 ranges.physical.includes(mode.getPeakFps()) &&
1312 (supportsFrameRateOverride() || ranges.render.includes(mode.getPeakFps()));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001313 };
Ady Abraham8a82ba62020-01-17 12:43:17 -08001314
Ady Abraham90f7fd22023-08-16 11:02:00 -07001315 auto frameRateModes = createFrameRateModes(*policy, filterModes, ranges.render);
Ady Abraham41bf7c62023-07-20 10:33:06 -07001316 if (frameRateModes.empty()) {
1317 ALOGW("No matching frame rate modes for %s range. policy: %s", rangeName,
1318 policy->toString().c_str());
1319 // TODO(b/292105422): Ideally DisplayManager should not send render ranges smaller than
1320 // the min supported. See b/292047939.
1321 // For not we just ignore the render ranges.
Ady Abraham90f7fd22023-08-16 11:02:00 -07001322 frameRateModes = createFrameRateModes(*policy, filterModes, {});
Ady Abraham41bf7c62023-07-20 10:33:06 -07001323 }
Ady Abraham68636062022-11-16 17:07:25 -08001324 LOG_ALWAYS_FATAL_IF(frameRateModes.empty(),
Ady Abraham41bf7c62023-07-20 10:33:06 -07001325 "No matching frame rate modes for %s range even after ignoring the "
1326 "render range. policy: %s",
1327 rangeName, policy->toString().c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -08001328
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001329 const auto stringifyModes = [&] {
1330 std::string str;
Ady Abraham68636062022-11-16 17:07:25 -08001331 for (const auto& frameRateMode : frameRateModes) {
1332 str += to_string(frameRateMode) + " ";
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001333 }
1334 return str;
1335 };
Ady Abraham68636062022-11-16 17:07:25 -08001336 ALOGV("%s render rates: %s", rangeName, stringifyModes().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -07001337
Ady Abraham68636062022-11-16 17:07:25 -08001338 return frameRateModes;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001339 };
1340
Ady Abraham68636062022-11-16 17:07:25 -08001341 mPrimaryFrameRates = filterRefreshRates(policy->primaryRanges, "primary");
1342 mAppRequestFrameRates = filterRefreshRates(policy->appRequestRanges, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -08001343}
1344
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001345Fps RefreshRateSelector::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001346 using namespace fps_approx_ops;
1347
1348 if (frameRate <= mKnownFrameRates.front()) {
1349 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001350 }
1351
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001352 if (frameRate >= mKnownFrameRates.back()) {
1353 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001354 }
1355
Marin Shalamanove8a663d2020-11-24 17:48:00 +01001356 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001357 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001358
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001359 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
1360 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001361 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
1362}
1363
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001364auto RefreshRateSelector::getIdleTimerAction() const -> KernelIdleTimerAction {
Ana Krulecb9afd792020-06-11 13:16:15 -07001365 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001366
ramindania04b8a52023-08-07 18:49:47 -07001367 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getPeakFps();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001368 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -07001369
1370 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
1371 // the min allowed refresh rate is higher than the device min, we do not want to enable the
1372 // timer.
ramindania04b8a52023-08-07 18:49:47 -07001373 if (isStrictlyLess(deviceMinFps, minByPolicy->getPeakFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001374 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001375 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001376
ramindanid72ba162022-09-09 21:33:40 +00001377 const DisplayModePtr& maxByPolicy =
Ady Abrahamace3d052022-11-17 16:25:05 -08001378 getMaxRefreshRateByPolicyLocked(getActiveModeLocked().modePtr->getGroup());
Ana Krulecb9afd792020-06-11 13:16:15 -07001379 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001380 // Turn on the timer when the min of the primary range is below the device min.
1381 if (const Policy* currentPolicy = getCurrentPolicyLocked();
Ady Abraham285f8c12022-10-11 17:12:14 -07001382 isApproxLess(currentPolicy->primaryRanges.physical.min, deviceMinFps)) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001383 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001384 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001385 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001386 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001387
Ana Krulecb9afd792020-06-11 13:16:15 -07001388 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001389 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001390}
1391
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001392int RefreshRateSelector::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -07001393 // This calculation needs to be in sync with the java code
1394 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001395
1396 // The threshold must be smaller than 0.001 in order to differentiate
1397 // between the fractional pairs (e.g. 59.94 and 60).
1398 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001399 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -07001400 const auto numPeriodsRounded = std::round(numPeriods);
1401 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001402 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -07001403 }
1404
Ady Abraham62f216c2020-10-13 19:07:23 -07001405 return static_cast<int>(numPeriodsRounded);
1406}
1407
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001408bool RefreshRateSelector::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001409 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001410 return isFractionalPairOrMultiple(bigger, smaller);
1411 }
1412
1413 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
1414 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001415 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
1416 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001417}
1418
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001419void RefreshRateSelector::dump(utils::Dumper& dumper) const {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001420 using namespace std::string_view_literals;
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001421
Marin Shalamanovba421a82020-11-10 21:49:26 +01001422 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +01001423
Ady Abrahamace3d052022-11-17 16:25:05 -08001424 const auto activeMode = getActiveModeLocked();
1425 dumper.dump("activeMode"sv, to_string(activeMode));
Marin Shalamanovba421a82020-11-10 21:49:26 +01001426
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001427 dumper.dump("displayModes"sv);
1428 {
1429 utils::Dumper::Indent indent(dumper);
1430 for (const auto& [id, mode] : mDisplayModes) {
1431 dumper.dump({}, to_string(*mode));
1432 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001433 }
1434
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001435 dumper.dump("displayManagerPolicy"sv, mDisplayManagerPolicy.toString());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001436
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001437 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
1438 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001439 dumper.dump("overridePolicy"sv, currentPolicy.toString());
ramindani32cf0602022-03-02 02:30:29 +00001440 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001441
Ady Abraham8ca643a2022-10-18 18:26:47 -07001442 dumper.dump("frameRateOverrideConfig"sv, *ftl::enum_name(mFrameRateOverrideConfig));
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001443
Dominik Laskowski03cfce82022-11-02 12:13:29 -04001444 dumper.dump("idleTimer"sv);
1445 {
1446 utils::Dumper::Indent indent(dumper);
1447 dumper.dump("interval"sv, mIdleTimer.transform(&OneShotTimer::interval));
1448 dumper.dump("controller"sv,
1449 mConfig.kernelIdleTimerController
1450 .and_then(&ftl::enum_name<KernelIdleTimerController>)
1451 .value_or("Platform"sv));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001452 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001453}
1454
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001455std::chrono::milliseconds RefreshRateSelector::getIdleTimerTimeout() {
ramindani32cf0602022-03-02 02:30:29 +00001456 return mConfig.idleTimerTimeout;
1457}
1458
Rachel Leece6e0042023-06-27 11:22:54 -07001459// TODO(b/293651105): Extract category FpsRange mapping to OEM-configurable config.
1460FpsRange RefreshRateSelector::getFrameRateCategoryRange(FrameRateCategory category) {
1461 switch (category) {
1462 case FrameRateCategory::High:
1463 return FpsRange{90_Hz, 120_Hz};
1464 case FrameRateCategory::Normal:
1465 return FpsRange{60_Hz, 90_Hz};
1466 case FrameRateCategory::Low:
1467 return FpsRange{30_Hz, 60_Hz};
1468 case FrameRateCategory::NoPreference:
1469 case FrameRateCategory::Default:
1470 LOG_ALWAYS_FATAL("Should not get fps range for frame rate category: %s",
1471 ftl::enum_string(category).c_str());
1472 return FpsRange{0_Hz, 0_Hz};
1473 default:
1474 LOG_ALWAYS_FATAL("Invalid frame rate category for range: %s",
1475 ftl::enum_string(category).c_str());
1476 return FpsRange{0_Hz, 0_Hz};
1477 }
1478}
1479
Ady Abraham2139f732019-11-13 18:56:40 -08001480} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001481
1482// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001483#pragma clang diagnostic pop // ignored "-Wextra"