blob: 1d23fb5f38eb044b6bea9c0229da3fdc09a7be44 [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"
ramindani9b085322023-09-19 17:18:37 -070041#include "Utils/FlagUtils.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080042
ramindania04b8a52023-08-07 18:49:47 -070043#include <com_android_graphics_surfaceflinger_flags.h>
44
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080045#undef LOG_TAG
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040046#define LOG_TAG "RefreshRateSelector"
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080047
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080048namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010049namespace {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070050
ramindania04b8a52023-08-07 18:49:47 -070051using namespace com::android::graphics::surfaceflinger;
52
Dominik Laskowskib0054a22022-03-03 09:03:06 -080053struct RefreshRateScore {
Ady Abraham68636062022-11-16 17:07:25 -080054 FrameRateMode frameRateMode;
Ady Abrahamae2e3c72022-08-13 05:12:13 +000055 float overallScore;
56 struct {
Ady Abraham62f51d92022-08-24 22:20:22 +000057 float modeBelowThreshold;
58 float modeAboveThreshold;
59 } fixedRateBelowThresholdLayersScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -080060};
61
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040062constexpr RefreshRateSelector::GlobalSignals kNoSignals;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -080063
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040064std::string formatLayerInfo(const RefreshRateSelector::LayerRequirement& layer, float weight) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080065 return base::StringPrintf("%s (type=%s, weight=%.2f, seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070066 ftl::enum_string(layer.vote).c_str(), weight,
67 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010068 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010069}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010070
Marin Shalamanova7fe3042021-01-29 21:02:08 +010071std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070072 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010073 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010074
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070075 // Add all supported refresh rates.
Dominik Laskowskib0054a22022-03-03 09:03:06 -080076 for (const auto& [id, mode] : modes) {
ramindania04b8a52023-08-07 18:49:47 -070077 knownFrameRates.push_back(mode->getPeakFps());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010078 }
79
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070080 // Sort and remove duplicates.
81 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010082 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070083 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010084 knownFrameRates.end());
85 return knownFrameRates;
86}
87
Ady Abraham68636062022-11-16 17:07:25 -080088std::vector<DisplayModeIterator> sortByRefreshRate(const DisplayModes& modes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -080089 std::vector<DisplayModeIterator> sortedModes;
90 sortedModes.reserve(modes.size());
Dominik Laskowskib0054a22022-03-03 09:03:06 -080091 for (auto it = modes.begin(); it != modes.end(); ++it) {
Ady Abraham68636062022-11-16 17:07:25 -080092 sortedModes.push_back(it);
Dominik Laskowskib0054a22022-03-03 09:03:06 -080093 }
94
95 std::sort(sortedModes.begin(), sortedModes.end(), [](auto it1, auto it2) {
96 const auto& mode1 = it1->second;
97 const auto& mode2 = it2->second;
98
ramindania04b8a52023-08-07 18:49:47 -070099 if (mode1->getVsyncRate().getPeriodNsecs() == mode2->getVsyncRate().getPeriodNsecs()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800100 return mode1->getGroup() > mode2->getGroup();
101 }
102
ramindania04b8a52023-08-07 18:49:47 -0700103 return mode1->getVsyncRate().getPeriodNsecs() > mode2->getVsyncRate().getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800104 });
105
106 return sortedModes;
Marin Shalamanov46084422020-10-13 12:33:42 +0200107}
108
ramindania04b8a52023-08-07 18:49:47 -0700109std::pair<unsigned, unsigned> divisorRange(Fps vsyncRate, Fps peakFps, FpsRange range,
Ady Abraham68636062022-11-16 17:07:25 -0800110 RefreshRateSelector::Config::FrameRateOverride config) {
111 if (config != RefreshRateSelector::Config::FrameRateOverride::Enabled) {
112 return {1, 1};
113 }
114
115 using fps_approx_ops::operator/;
Ady Abraham08048ce2022-11-30 18:08:00 -0800116 // use signed type as `fps / range.max` might be 0
ramindania04b8a52023-08-07 18:49:47 -0700117 auto start = std::max(1, static_cast<int>(peakFps / range.max) - 1);
ramindani9b085322023-09-19 17:18:37 -0700118 if (flagutils::vrrConfigEnabled()) {
ramindania04b8a52023-08-07 18:49:47 -0700119 start = std::max(1,
120 static_cast<int>(vsyncRate /
121 std::min(range.max, peakFps, fps_approx_ops::operator<)) -
122 1);
123 }
124 const auto end = vsyncRate /
Ady Abraham68636062022-11-16 17:07:25 -0800125 std::max(range.min, RefreshRateSelector::kMinSupportedFrameRate,
126 fps_approx_ops::operator<);
127
128 return {start, end};
129}
130
Ady Abraham8ca643a2022-10-18 18:26:47 -0700131bool shouldEnableFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800132 for (const auto it1 : sortedModes) {
133 const auto& mode1 = it1->second;
134 for (const auto it2 : sortedModes) {
135 const auto& mode2 = it2->second;
136
ramindania04b8a52023-08-07 18:49:47 -0700137 if (RefreshRateSelector::getFrameRateDivisor(mode1->getPeakFps(),
138 mode2->getPeakFps()) >= 2) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800139 return true;
140 }
141 }
142 }
143 return false;
144}
145
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400146std::string toString(const RefreshRateSelector::PolicyVariant& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700147 using namespace std::string_literals;
148
149 return ftl::match(
150 policy,
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400151 [](const RefreshRateSelector::DisplayManagerPolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700152 return "DisplayManagerPolicy"s + policy.toString();
153 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400154 [](const RefreshRateSelector::OverridePolicy& policy) {
Dominik Laskowski36dced82022-09-02 09:24:00 -0700155 return "OverridePolicy"s + policy.toString();
156 },
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400157 [](RefreshRateSelector::NoOverridePolicy) { return "NoOverridePolicy"s; });
Dominik Laskowski36dced82022-09-02 09:24:00 -0700158}
159
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800160} // namespace
161
Ady Abraham68636062022-11-16 17:07:25 -0800162auto RefreshRateSelector::createFrameRateModes(
Ady Abraham90f7fd22023-08-16 11:02:00 -0700163 const Policy& policy, std::function<bool(const DisplayMode&)>&& filterModes,
164 const FpsRange& renderRange) const -> std::vector<FrameRateMode> {
Ady Abraham68636062022-11-16 17:07:25 -0800165 struct Key {
166 Fps fps;
167 int32_t group;
168 };
169
170 struct KeyLess {
171 bool operator()(const Key& a, const Key& b) const {
172 using namespace fps_approx_ops;
173 if (a.fps != b.fps) {
174 return a.fps < b.fps;
175 }
176
177 // For the same fps the order doesn't really matter, but we still
178 // want the behaviour of a strictly less operator.
179 // We use the group id as the secondary ordering for that.
180 return a.group < b.group;
181 }
182 };
183
184 std::map<Key, DisplayModeIterator, KeyLess> ratesMap;
185 for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
186 const auto& [id, mode] = *it;
187
188 if (!filterModes(*mode)) {
189 continue;
190 }
ramindania04b8a52023-08-07 18:49:47 -0700191 const auto vsyncRate = mode->getVsyncRate();
192 const auto peakFps = mode->getPeakFps();
Ady Abraham68636062022-11-16 17:07:25 -0800193 const auto [start, end] =
ramindania04b8a52023-08-07 18:49:47 -0700194 divisorRange(vsyncRate, peakFps, renderRange, mConfig.enableFrameRateOverride);
Ady Abraham68636062022-11-16 17:07:25 -0800195 for (auto divisor = start; divisor <= end; divisor++) {
ramindania04b8a52023-08-07 18:49:47 -0700196 const auto fps = vsyncRate / divisor;
Ady Abraham68636062022-11-16 17:07:25 -0800197 using fps_approx_ops::operator<;
Ady Abrahamdc0b3a72023-01-04 16:58:27 -0800198 if (divisor > 1 && fps < kMinSupportedFrameRate) {
Ady Abraham68636062022-11-16 17:07:25 -0800199 break;
200 }
201
202 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Enabled &&
203 !renderRange.includes(fps)) {
204 continue;
205 }
206
207 if (mConfig.enableFrameRateOverride ==
208 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
209 !isNativeRefreshRate(fps)) {
210 continue;
211 }
212
213 const auto [existingIter, emplaceHappened] =
214 ratesMap.try_emplace(Key{fps, mode->getGroup()}, it);
215 if (emplaceHappened) {
ramindania04b8a52023-08-07 18:49:47 -0700216 ALOGV("%s: including %s (%s(%s))", __func__, to_string(fps).c_str(),
217 to_string(peakFps).c_str(), to_string(vsyncRate).c_str());
Ady Abraham68636062022-11-16 17:07:25 -0800218 } else {
Ady Abraham90f7fd22023-08-16 11:02:00 -0700219 // If the primary physical range is a single rate, prefer to stay in that rate
220 // even if there is a lower physical refresh rate available. This would cause more
221 // cases to stay within the primary physical range
ramindania04b8a52023-08-07 18:49:47 -0700222 const Fps existingModeFps = existingIter->second->second->getPeakFps();
Ady Abraham90f7fd22023-08-16 11:02:00 -0700223 const bool existingModeIsPrimaryRange = policy.primaryRangeIsSingleRate() &&
224 policy.primaryRanges.physical.includes(existingModeFps);
225 const bool newModeIsPrimaryRange = policy.primaryRangeIsSingleRate() &&
ramindania04b8a52023-08-07 18:49:47 -0700226 policy.primaryRanges.physical.includes(mode->getPeakFps());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700227 if (newModeIsPrimaryRange == existingModeIsPrimaryRange) {
228 // We might need to update the map as we found a lower refresh rate
ramindania04b8a52023-08-07 18:49:47 -0700229 if (isStrictlyLess(mode->getPeakFps(), existingModeFps)) {
Ady Abraham90f7fd22023-08-16 11:02:00 -0700230 existingIter->second = it;
ramindania04b8a52023-08-07 18:49:47 -0700231 ALOGV("%s: changing %s (%s(%s)) as we found a lower physical rate",
232 __func__, to_string(fps).c_str(), to_string(peakFps).c_str(),
233 to_string(vsyncRate).c_str());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700234 }
235 } else if (newModeIsPrimaryRange) {
Ady Abraham68636062022-11-16 17:07:25 -0800236 existingIter->second = it;
ramindania04b8a52023-08-07 18:49:47 -0700237 ALOGV("%s: changing %s (%s(%s)) to stay in the primary range", __func__,
238 to_string(fps).c_str(), to_string(peakFps).c_str(),
239 to_string(vsyncRate).c_str());
Ady Abraham68636062022-11-16 17:07:25 -0800240 }
241 }
242 }
243 }
244
245 std::vector<FrameRateMode> frameRateModes;
246 frameRateModes.reserve(ratesMap.size());
247 for (const auto& [key, mode] : ratesMap) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800248 frameRateModes.emplace_back(FrameRateMode{key.fps, ftl::as_non_null(mode->second)});
Ady Abraham68636062022-11-16 17:07:25 -0800249 }
250
251 // We always want that the lowest frame rate will be corresponding to the
252 // lowest mode for power saving.
253 const auto lowestRefreshRateIt =
254 std::min_element(frameRateModes.begin(), frameRateModes.end(),
255 [](const FrameRateMode& lhs, const FrameRateMode& rhs) {
ramindania04b8a52023-08-07 18:49:47 -0700256 return isStrictlyLess(lhs.modePtr->getVsyncRate(),
257 rhs.modePtr->getVsyncRate());
Ady Abraham68636062022-11-16 17:07:25 -0800258 });
259 frameRateModes.erase(frameRateModes.begin(), lowestRefreshRateIt);
260
261 return frameRateModes;
262}
263
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400264struct RefreshRateSelector::RefreshRateScoreComparator {
ramindanid72ba162022-09-09 21:33:40 +0000265 bool operator()(const RefreshRateScore& lhs, const RefreshRateScore& rhs) const {
Ady Abraham68636062022-11-16 17:07:25 -0800266 const auto& [frameRateMode, overallScore, _] = lhs;
ramindanid72ba162022-09-09 21:33:40 +0000267
Ady Abraham68636062022-11-16 17:07:25 -0800268 std::string name = to_string(frameRateMode);
269
ramindanid72ba162022-09-09 21:33:40 +0000270 ALOGV("%s sorting scores %.2f", name.c_str(), overallScore);
ramindanid72ba162022-09-09 21:33:40 +0000271
Ady Abraham68636062022-11-16 17:07:25 -0800272 if (!ScoredFrameRate::scoresEqual(overallScore, rhs.overallScore)) {
ramindanid72ba162022-09-09 21:33:40 +0000273 return overallScore > rhs.overallScore;
274 }
275
ramindanid72ba162022-09-09 21:33:40 +0000276 if (refreshRateOrder == RefreshRateOrder::Descending) {
277 using fps_approx_ops::operator>;
Ady Abraham68636062022-11-16 17:07:25 -0800278 return frameRateMode.fps > rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000279 } else {
280 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -0800281 return frameRateMode.fps < rhs.frameRateMode.fps;
ramindanid72ba162022-09-09 21:33:40 +0000282 }
283 }
284
285 const RefreshRateOrder refreshRateOrder;
286};
287
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400288std::string RefreshRateSelector::Policy::toString() const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700289 return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
Ady Abraham285f8c12022-10-11 17:12:14 -0700290 ", primaryRanges=%s, appRequestRanges=%s}",
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700291 defaultMode.value(), allowGroupSwitching ? "true" : "false",
Ady Abraham285f8c12022-10-11 17:12:14 -0700292 to_string(primaryRanges).c_str(),
293 to_string(appRequestRanges).c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200294}
295
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400296std::pair<nsecs_t, nsecs_t> RefreshRateSelector::getDisplayFrames(nsecs_t layerPeriod,
297 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800298 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
299 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
300 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
301 quotient++;
302 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800303 }
304
Ady Abraham62a0be22020-12-08 16:54:10 -0800305 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800306}
307
Rachel Leece6e0042023-06-27 11:22:54 -0700308float RefreshRateSelector::calculateNonExactMatchingDefaultLayerScoreLocked(
309 nsecs_t displayPeriod, nsecs_t layerPeriod) const {
310 // Find the actual rate the layer will render, assuming
311 // that layerPeriod is the minimal period to render a frame.
312 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
313 // then the actualLayerPeriod will be 32ms, because it is the
314 // smallest multiple of the display period which is >= layerPeriod.
315 auto actualLayerPeriod = displayPeriod;
316 int multiplier = 1;
317 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
318 multiplier++;
319 actualLayerPeriod = displayPeriod * multiplier;
320 }
321
322 // Because of the threshold we used above it's possible that score is slightly
323 // above 1.
324 return std::min(1.0f, static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
325}
326
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400327float RefreshRateSelector::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
328 Fps refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200329 constexpr float kScoreForFractionalPairs = .8f;
330
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800331 const auto displayPeriod = refreshRate.getPeriodNsecs();
Ady Abraham62a0be22020-12-08 16:54:10 -0800332 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
333 if (layer.vote == LayerVoteType::ExplicitDefault) {
Rachel Leece6e0042023-06-27 11:22:54 -0700334 return calculateNonExactMatchingDefaultLayerScoreLocked(displayPeriod, layerPeriod);
Ady Abraham62a0be22020-12-08 16:54:10 -0800335 }
336
337 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
338 layer.vote == LayerVoteType::Heuristic) {
Ady Abrahambd44e8a2023-07-24 11:30:06 -0700339 using fps_approx_ops::operator<;
340 if (refreshRate < 60_Hz) {
341 const bool favorsAtLeast60 =
342 std::find_if(mFrameRatesThatFavorsAtLeast60.begin(),
343 mFrameRatesThatFavorsAtLeast60.end(), [&](Fps fps) {
344 using fps_approx_ops::operator==;
345 return fps == layer.desiredRefreshRate;
346 }) != mFrameRatesThatFavorsAtLeast60.end();
347 if (favorsAtLeast60) {
348 return 0;
349 }
350 }
351
Ady Abraham68636062022-11-16 17:07:25 -0800352 const float multiplier = refreshRate.getValue() / layer.desiredRefreshRate.getValue();
353
354 // We only want to score this layer as a fractional pair if the content is not
355 // significantly faster than the display rate, at it would cause a significant frame drop.
356 // It is more appropriate to choose a higher display rate even if
357 // a pull-down will be required.
Rachel Lee36426fa2023-03-08 20:13:52 -0800358 constexpr float kMinMultiplier = 0.75f;
Ady Abraham68636062022-11-16 17:07:25 -0800359 if (multiplier >= kMinMultiplier &&
360 isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700361 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200362 }
363
Ady Abraham62a0be22020-12-08 16:54:10 -0800364 // Calculate how many display vsyncs we need to present a single frame for this
365 // layer
366 const auto [displayFramesQuotient, displayFramesRemainder] =
367 getDisplayFrames(layerPeriod, displayPeriod);
368 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
369 if (displayFramesRemainder == 0) {
370 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700371 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800372 }
373
374 if (displayFramesQuotient == 0) {
375 // Layer desired refresh rate is higher than the display rate.
376 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
377 (1.0f / (MAX_FRAMES_TO_FIT + 1));
378 }
379
380 // Layer desired refresh rate is lower than the display rate. Check how well it fits
381 // the cadence.
382 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
383 int iter = 2;
384 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
385 diff = diff - (displayPeriod - diff);
386 iter++;
387 }
388
Ady Abraham05243be2021-09-16 15:58:52 -0700389 return (1.0f / iter);
390 }
391
392 return 0;
393}
394
Ady Abraham68636062022-11-16 17:07:25 -0800395float RefreshRateSelector::calculateDistanceScoreFromMax(Fps refreshRate) const {
396 const auto& maxFps = mAppRequestFrameRates.back().fps;
397 const float ratio = refreshRate.getValue() / maxFps.getValue();
ramindanid72ba162022-09-09 21:33:40 +0000398 // Use ratio^2 to get a lower score the more we get further from peak
399 return ratio * ratio;
400}
401
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400402float RefreshRateSelector::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
403 bool isSeamlessSwitch) const {
Ady Abraham73c3df52023-01-12 18:09:31 -0800404 ATRACE_CALL();
Ady Abraham05243be2021-09-16 15:58:52 -0700405 // Slightly prefer seamless switches.
406 constexpr float kSeamedSwitchPenalty = 0.95f;
407 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
408
Rachel Leece6e0042023-06-27 11:22:54 -0700409 if (layer.vote == LayerVoteType::ExplicitCategory) {
410 if (getFrameRateCategoryRange(layer.frameRateCategory).includes(refreshRate)) {
411 return 1.f;
412 }
413
414 FpsRange categoryRange = getFrameRateCategoryRange(layer.frameRateCategory);
415 using fps_approx_ops::operator<;
416 if (refreshRate < categoryRange.min) {
417 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
418 categoryRange.min
419 .getPeriodNsecs());
420 }
421 return calculateNonExactMatchingDefaultLayerScoreLocked(refreshRate.getPeriodNsecs(),
422 categoryRange.max.getPeriodNsecs());
423 }
424
Ady Abraham05243be2021-09-16 15:58:52 -0700425 // If the layer wants Max, give higher score to the higher refresh rate
426 if (layer.vote == LayerVoteType::Max) {
Ady Abraham68636062022-11-16 17:07:25 -0800427 return calculateDistanceScoreFromMax(refreshRate);
Ady Abraham62a0be22020-12-08 16:54:10 -0800428 }
429
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800430 if (layer.vote == LayerVoteType::ExplicitExact) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800431 const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
Ady Abraham68636062022-11-16 17:07:25 -0800432 if (supportsAppFrameRateOverrideByContent()) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800433 // Since we support frame rate override, allow refresh rates which are
434 // multiples of the layer's request, as those apps would be throttled
435 // down to run at the desired refresh rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800436 return divisor > 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800437 }
438
Ady Abrahamcc315492022-02-17 17:06:39 -0800439 return divisor == 1;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800440 }
441
Ady Abrahamcc315492022-02-17 17:06:39 -0800442 // If the layer frame rate is a divisor of the refresh rate it should score
Ady Abraham05243be2021-09-16 15:58:52 -0700443 // the highest score.
Rachel Leece6e0042023-06-27 11:22:54 -0700444 if (layer.desiredRefreshRate.isValid() &&
445 getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
Ady Abraham05243be2021-09-16 15:58:52 -0700446 return 1.0f * seamlessness;
447 }
448
Ady Abrahamcc315492022-02-17 17:06:39 -0800449 // The layer frame rate is not a divisor of the refresh rate,
Ady Abraham05243be2021-09-16 15:58:52 -0700450 // there is a small penalty attached to the score to favor the frame rates
451 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800452 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700453 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
454 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800455}
456
Ady Abraham68636062022-11-16 17:07:25 -0800457auto RefreshRateSelector::getRankedFrameRates(const std::vector<LayerRequirement>& layers,
458 GlobalSignals signals) const -> RankedFrameRates {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200459 std::lock_guard lock(mLock);
460
Ady Abraham68636062022-11-16 17:07:25 -0800461 if (mGetRankedFrameRatesCache &&
462 mGetRankedFrameRatesCache->arguments == std::make_pair(layers, signals)) {
463 return mGetRankedFrameRatesCache->result;
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200464 }
465
Ady Abraham68636062022-11-16 17:07:25 -0800466 const auto result = getRankedFrameRatesLocked(layers, signals);
467 mGetRankedFrameRatesCache = GetRankedFrameRatesCache{{layers, signals}, result};
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200468 return result;
469}
470
Ady Abraham68636062022-11-16 17:07:25 -0800471auto RefreshRateSelector::getRankedFrameRatesLocked(const std::vector<LayerRequirement>& layers,
472 GlobalSignals signals) const
473 -> RankedFrameRates {
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000474 using namespace fps_approx_ops;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800475 ATRACE_CALL();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800476 ALOGV("%s: %zu layers", __func__, layers.size());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700477
Ady Abrahamace3d052022-11-17 16:25:05 -0800478 const auto& activeMode = *getActiveModeLocked().modePtr;
ramindani38c84982022-08-29 18:02:57 +0000479
Ady Abraham68636062022-11-16 17:07:25 -0800480 // Keep the display at max frame rate for the duration of powering on the display.
ramindani38c84982022-08-29 18:02:57 +0000481 if (signals.powerOnImminent) {
482 ALOGV("Power On Imminent");
Ady Abrahamccf63862023-01-19 11:44:01 -0800483 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Descending);
484 ATRACE_FORMAT_INSTANT("%s (Power On Imminent)",
485 to_string(ranking.front().frameRateMode.fps).c_str());
486 return {ranking, GlobalSignals{.powerOnImminent = true}};
ramindani38c84982022-08-29 18:02:57 +0000487 }
488
Ady Abraham8a82ba62020-01-17 12:43:17 -0800489 int noVoteLayers = 0;
490 int minVoteLayers = 0;
491 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800492 int explicitDefaultVoteLayers = 0;
493 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800494 int explicitExact = 0;
Rachel Leece6e0042023-06-27 11:22:54 -0700495 int explicitCategoryVoteLayers = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100496 int seamedFocusedLayers = 0;
Rachel Lee67afbea2023-09-28 15:35:07 -0700497 int categorySmoothSwitchOnlyLayers = 0;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800498
Ady Abraham8a82ba62020-01-17 12:43:17 -0800499 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800500 switch (layer.vote) {
501 case LayerVoteType::NoVote:
502 noVoteLayers++;
503 break;
504 case LayerVoteType::Min:
505 minVoteLayers++;
506 break;
507 case LayerVoteType::Max:
508 maxVoteLayers++;
509 break;
510 case LayerVoteType::ExplicitDefault:
511 explicitDefaultVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800512 break;
513 case LayerVoteType::ExplicitExactOrMultiple:
514 explicitExactOrMultipleVoteLayers++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800515 break;
516 case LayerVoteType::ExplicitExact:
517 explicitExact++;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800518 break;
Rachel Leece6e0042023-06-27 11:22:54 -0700519 case LayerVoteType::ExplicitCategory:
520 explicitCategoryVoteLayers++;
Rachel Leef377b362023-09-06 15:01:06 -0700521 if (layer.frameRateCategory == FrameRateCategory::NoPreference) {
522 // Count this layer for Min vote as well. The explicit vote avoids
523 // touch boost and idle for choosing a category, while Min vote is for correct
524 // behavior when all layers are Min or no vote.
525 minVoteLayers++;
526 }
Rachel Leece6e0042023-06-27 11:22:54 -0700527 break;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800528 case LayerVoteType::Heuristic:
529 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800530 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200531
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100532 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
533 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200534 }
Rachel Lee67afbea2023-09-28 15:35:07 -0700535 if (layer.frameRateCategorySmoothSwitchOnly) {
536 categorySmoothSwitchOnlyLayers++;
537 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800538 }
539
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800540 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
Rachel Leece6e0042023-06-27 11:22:54 -0700541 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0 ||
542 explicitCategoryVoteLayers > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700543
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200544 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800545 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700546
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200547 // If the default mode group is different from the group of current mode,
548 // this means a layer requesting a seamed mode switch just disappeared and
549 // we should switch back to the default group.
550 // However if a seamed layer is still present we anchor around the group
551 // of the current mode, in order to prevent unnecessary seamed mode switches
552 // (e.g. when pausing a video playback).
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800553 const auto anchorGroup =
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700554 seamedFocusedLayers > 0 ? activeMode.getGroup() : defaultMode->getGroup();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200555
Steven Thomasf734df42020-04-13 21:09:28 -0700556 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
557 // selected a refresh rate to see if we should apply touch boost.
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800558 if (signals.touch && !hasExplicitVoteLayers) {
ramindanid72ba162022-09-09 21:33:40 +0000559 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800560 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
561 ATRACE_FORMAT_INSTANT("%s (Touch Boost)",
562 to_string(ranking.front().frameRateMode.fps).c_str());
563 return {ranking, GlobalSignals{.touch = true}};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800564 }
565
Alec Mouri11232a22020-05-14 18:06:25 -0700566 // If the primary range consists of a single refresh rate then we can only
567 // move out the of range if layers explicitly request a different refresh
568 // rate.
Ady Abraham90f7fd22023-08-16 11:02:00 -0700569 if (!signals.touch && signals.idle &&
570 !(policy->primaryRangeIsSingleRate() && hasExplicitVoteLayers)) {
ramindanid72ba162022-09-09 21:33:40 +0000571 ALOGV("Idle");
Ady Abrahamccf63862023-01-19 11:44:01 -0800572 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending);
573 ATRACE_FORMAT_INSTANT("%s (Idle)", to_string(ranking.front().frameRateMode.fps).c_str());
574 return {ranking, GlobalSignals{.idle = true}};
Steven Thomasbb374322020-04-28 22:47:16 -0700575 }
576
Steven Thomasdebafed2020-05-18 17:30:35 -0700577 if (layers.empty() || noVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000578 ALOGV("No layers with votes");
Ady Abrahamccf63862023-01-19 11:44:01 -0800579 const auto ranking = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
580 ATRACE_FORMAT_INSTANT("%s (No layers with votes)",
581 to_string(ranking.front().frameRateMode.fps).c_str());
582 return {ranking, kNoSignals};
Steven Thomasbb374322020-04-28 22:47:16 -0700583 }
584
Rachel Lee67afbea2023-09-28 15:35:07 -0700585 const bool smoothSwitchOnly = categorySmoothSwitchOnlyLayers > 0;
586 const DisplayModeId activeModeId = activeMode.getId();
587
Ady Abraham8a82ba62020-01-17 12:43:17 -0800588 // Only if all layers want Min we should return Min
589 if (noVoteLayers + minVoteLayers == layers.size()) {
ramindanid72ba162022-09-09 21:33:40 +0000590 ALOGV("All layers Min");
Rachel Lee67afbea2023-09-28 15:35:07 -0700591 const auto ranking = rankFrameRates(activeMode.getGroup(), RefreshRateOrder::Ascending,
592 std::nullopt, [&](FrameRateMode mode) {
593 return !smoothSwitchOnly ||
594 mode.modePtr->getId() == activeModeId;
595 });
Ady Abrahamccf63862023-01-19 11:44:01 -0800596 ATRACE_FORMAT_INSTANT("%s (All layers Min)",
597 to_string(ranking.front().frameRateMode.fps).c_str());
598 return {ranking, kNoSignals};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800599 }
600
Ady Abraham8a82ba62020-01-17 12:43:17 -0800601 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800602 std::vector<RefreshRateScore> scores;
Ady Abraham68636062022-11-16 17:07:25 -0800603 scores.reserve(mAppRequestFrameRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800604
Ady Abraham68636062022-11-16 17:07:25 -0800605 for (const FrameRateMode& it : mAppRequestFrameRates) {
606 scores.emplace_back(RefreshRateScore{it, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800607 }
608
609 for (const auto& layer : layers) {
Rachel Leece6e0042023-06-27 11:22:54 -0700610 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f, category %s) ",
611 layer.name.c_str(), ftl::enum_string(layer.vote).c_str(), layer.weight,
612 layer.desiredRefreshRate.getValue(),
613 ftl::enum_string(layer.frameRateCategory).c_str());
Rachel Leed0694bc2023-09-12 14:57:58 -0700614 if (layer.isNoVote() || layer.frameRateCategory == FrameRateCategory::NoPreference ||
615 layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800616 continue;
617 }
618
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800619 const auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800620
Ady Abraham68636062022-11-16 17:07:25 -0800621 for (auto& [mode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
622 const auto& [fps, modePtr] = mode;
623 const bool isSeamlessSwitch = modePtr->getGroup() == activeMode.getGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200624
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100625 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100626 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800627 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700628 to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200629 continue;
630 }
631
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100632 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
633 !layer.focused) {
634 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100635 " Current mode = %s",
Ady Abraham68636062022-11-16 17:07:25 -0800636 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700637 to_string(activeMode).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100638 continue;
639 }
640
Rachel Lee67afbea2023-09-28 15:35:07 -0700641 if (smoothSwitchOnly && modePtr->getId() != activeModeId) {
642 ALOGV("%s ignores %s because it's non-VRR and smooth switch only."
643 " Current mode = %s",
644 formatLayerInfo(layer, weight).c_str(), to_string(*modePtr).c_str(),
645 to_string(activeMode).c_str());
646 continue;
647 }
648
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100649 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100650 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100651 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100652 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
653 // disappeared.
Ady Abraham68636062022-11-16 17:07:25 -0800654 const bool isInPolicyForDefault = modePtr->getGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100655 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100656 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham68636062022-11-16 17:07:25 -0800657 to_string(*modePtr).c_str(), to_string(activeMode).c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200658 continue;
659 }
660
Ady Abraham90f7fd22023-08-16 11:02:00 -0700661 const bool inPrimaryPhysicalRange =
ramindania04b8a52023-08-07 18:49:47 -0700662 policy->primaryRanges.physical.includes(modePtr->getPeakFps());
Ady Abraham90f7fd22023-08-16 11:02:00 -0700663 const bool inPrimaryRenderRange = policy->primaryRanges.render.includes(fps);
664 if (((policy->primaryRangeIsSingleRate() && !inPrimaryPhysicalRange) ||
665 !inPrimaryRenderRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800666 !(layer.focused &&
667 (layer.vote == LayerVoteType::ExplicitDefault ||
668 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700669 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700670 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700671 continue;
672 }
673
Ady Abraham68636062022-11-16 17:07:25 -0800674 const float layerScore = calculateLayerScoreLocked(layer, fps, isSeamlessSwitch);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000675 const float weightedLayerScore = weight * layerScore;
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800676
Ady Abraham13cfb362022-08-13 05:12:13 +0000677 // Layer with fixed source has a special consideration which depends on the
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000678 // mConfig.frameRateMultipleThreshold. We don't want these layers to score
679 // refresh rates above the threshold, but we also don't want to favor the lower
680 // ones by having a greater number of layers scoring them. Instead, we calculate
681 // the score independently for these layers and later decide which
682 // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
683 // score 120 Hz, but desired 60 fps should contribute to the score.
684 const bool fixedSourceLayer = [](LayerVoteType vote) {
685 switch (vote) {
686 case LayerVoteType::ExplicitExactOrMultiple:
687 case LayerVoteType::Heuristic:
688 return true;
689 case LayerVoteType::NoVote:
690 case LayerVoteType::Min:
691 case LayerVoteType::Max:
692 case LayerVoteType::ExplicitDefault:
693 case LayerVoteType::ExplicitExact:
Rachel Leece6e0042023-06-27 11:22:54 -0700694 case LayerVoteType::ExplicitCategory:
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000695 return false;
696 }
697 }(layer.vote);
Ady Abraham62f51d92022-08-24 22:20:22 +0000698 const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000699 layer.desiredRefreshRate <
700 Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
Ady Abraham62f51d92022-08-24 22:20:22 +0000701 if (fixedSourceLayer && layerBelowThreshold) {
Ady Abraham13cfb362022-08-13 05:12:13 +0000702 const bool modeAboveThreshold =
ramindania04b8a52023-08-07 18:49:47 -0700703 modePtr->getPeakFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
Ady Abraham62f51d92022-08-24 22:20:22 +0000704 if (modeAboveThreshold) {
ramindania04b8a52023-08-07 18:49:47 -0700705 ALOGV("%s gives %s (%s(%s)) fixed source (above threshold) score of %.4f",
Ady Abraham68636062022-11-16 17:07:25 -0800706 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700707 to_string(modePtr->getPeakFps()).c_str(),
708 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000709 fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000710 } else {
ramindania04b8a52023-08-07 18:49:47 -0700711 ALOGV("%s gives %s (%s(%s)) fixed source (below threshold) score of %.4f",
Ady Abraham68636062022-11-16 17:07:25 -0800712 formatLayerInfo(layer, weight).c_str(), to_string(fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700713 to_string(modePtr->getPeakFps()).c_str(),
714 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abraham62f51d92022-08-24 22:20:22 +0000715 fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000716 }
717 } else {
ramindania04b8a52023-08-07 18:49:47 -0700718 ALOGV("%s gives %s (%s(%s)) score of %.4f", formatLayerInfo(layer, weight).c_str(),
719 to_string(fps).c_str(), to_string(modePtr->getPeakFps()).c_str(),
720 to_string(modePtr->getVsyncRate()).c_str(), layerScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000721 overallScore += weightedLayerScore;
722 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800723 }
724 }
725
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000726 // We want to find the best refresh rate without the fixed source layers,
Ady Abraham62f51d92022-08-24 22:20:22 +0000727 // so we could know whether we should add the modeAboveThreshold scores or not.
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000728 // If the best refresh rate is already above the threshold, it means that
729 // some non-fixed source layers already scored it, so we can just add the score
730 // for all fixed source layers, even the ones that are above the threshold.
731 const bool maxScoreAboveThreshold = [&] {
732 if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
733 return false;
734 }
735
736 const auto maxScoreIt =
737 std::max_element(scores.begin(), scores.end(),
738 [](RefreshRateScore max, RefreshRateScore current) {
Ady Abraham68636062022-11-16 17:07:25 -0800739 return current.overallScore > max.overallScore;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000740 });
ramindania04b8a52023-08-07 18:49:47 -0700741 ALOGV("%s (%s(%s)) is the best refresh rate without fixed source layers. It is %s the "
Ady Abraham68636062022-11-16 17:07:25 -0800742 "threshold for "
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000743 "refresh rate multiples",
Ady Abraham68636062022-11-16 17:07:25 -0800744 to_string(maxScoreIt->frameRateMode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700745 to_string(maxScoreIt->frameRateMode.modePtr->getPeakFps()).c_str(),
746 to_string(maxScoreIt->frameRateMode.modePtr->getVsyncRate()).c_str(),
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000747 maxScoreAboveThreshold ? "above" : "below");
ramindania04b8a52023-08-07 18:49:47 -0700748 return maxScoreIt->frameRateMode.modePtr->getPeakFps() >=
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000749 Fps::fromValue(mConfig.frameRateMultipleThreshold);
750 }();
751
752 // Now we can add the fixed rate layers score
Ady Abraham68636062022-11-16 17:07:25 -0800753 for (auto& [frameRateMode, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000754 overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000755 if (maxScoreAboveThreshold) {
Ady Abraham62f51d92022-08-24 22:20:22 +0000756 overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000757 }
ramindania04b8a52023-08-07 18:49:47 -0700758 ALOGV("%s (%s(%s)) adjusted overallScore is %.4f", to_string(frameRateMode.fps).c_str(),
759 to_string(frameRateMode.modePtr->getPeakFps()).c_str(),
760 to_string(frameRateMode.modePtr->getVsyncRate()).c_str(), overallScore);
Ady Abrahamae2e3c72022-08-13 05:12:13 +0000761 }
762
763 // Now that we scored all the refresh rates we need to pick the one that got the highest
ramindanid72ba162022-09-09 21:33:40 +0000764 // overallScore. Sort the scores based on their overallScore in descending order of priority.
765 const RefreshRateOrder refreshRateOrder =
766 maxVoteLayers > 0 ? RefreshRateOrder::Descending : RefreshRateOrder::Ascending;
767 std::sort(scores.begin(), scores.end(),
768 RefreshRateScoreComparator{.refreshRateOrder = refreshRateOrder});
ramindanid72ba162022-09-09 21:33:40 +0000769
Ady Abraham68636062022-11-16 17:07:25 -0800770 FrameRateRanking ranking;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400771 ranking.reserve(scores.size());
772
773 std::transform(scores.begin(), scores.end(), back_inserter(ranking),
ramindanid72ba162022-09-09 21:33:40 +0000774 [](const RefreshRateScore& score) {
Ady Abraham68636062022-11-16 17:07:25 -0800775 return ScoredFrameRate{score.frameRateMode, score.overallScore};
ramindanid72ba162022-09-09 21:33:40 +0000776 });
Ady Abraham34702102020-02-10 14:12:05 -0800777
Ady Abraham37d46922022-10-05 13:08:51 -0700778 const bool noLayerScore = std::all_of(scores.begin(), scores.end(), [](RefreshRateScore score) {
779 return score.overallScore == 0;
780 });
781
Ady Abraham90f7fd22023-08-16 11:02:00 -0700782 if (policy->primaryRangeIsSingleRate()) {
Alec Mouri11232a22020-05-14 18:06:25 -0700783 // If we never scored any layers, then choose the rate from the primary
784 // range instead of picking a random score from the app range.
Ady Abraham37d46922022-10-05 13:08:51 -0700785 if (noLayerScore) {
ramindanid72ba162022-09-09 21:33:40 +0000786 ALOGV("Layers not scored");
Ady Abrahamccf63862023-01-19 11:44:01 -0800787 const auto descending = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
788 ATRACE_FORMAT_INSTANT("%s (Layers not scored)",
789 to_string(descending.front().frameRateMode.fps).c_str());
790 return {descending, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700791 } else {
Rachel Lee67afbea2023-09-28 15:35:07 -0700792 ALOGV("primaryRangeIsSingleRate");
Ady Abrahamccf63862023-01-19 11:44:01 -0800793 ATRACE_FORMAT_INSTANT("%s (primaryRangeIsSingleRate)",
794 to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400795 return {ranking, kNoSignals};
Alec Mouri11232a22020-05-14 18:06:25 -0700796 }
797 }
798
Steven Thomasf734df42020-04-13 21:09:28 -0700799 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
800 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
801 // vote we should not change it if we get a touch event. Only apply touch boost if it will
802 // actually increase the refresh rate over the normal selection.
Ady Abraham5e4e9832021-06-14 13:40:56 -0700803 const bool touchBoostForExplicitExact = [&] {
Ady Abraham68636062022-11-16 17:07:25 -0800804 if (supportsAppFrameRateOverrideByContent()) {
Ady Abraham5e4e9832021-06-14 13:40:56 -0700805 // Enable touch boost if there are other layers besides exact
806 return explicitExact + noVoteLayers != layers.size();
807 } else {
808 // Enable touch boost if there are no exact layers
809 return explicitExact == 0;
810 }
811 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700812
Ady Abraham68636062022-11-16 17:07:25 -0800813 const auto touchRefreshRates = rankFrameRates(anchorGroup, RefreshRateOrder::Descending);
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700814 using fps_approx_ops::operator<;
815
Rachel Leece6e0042023-06-27 11:22:54 -0700816 if (signals.touch && explicitDefaultVoteLayers == 0 && explicitCategoryVoteLayers == 0 &&
817 touchBoostForExplicitExact &&
Ady Abraham68636062022-11-16 17:07:25 -0800818 scores.front().frameRateMode.fps < touchRefreshRates.front().frameRateMode.fps) {
ramindanid72ba162022-09-09 21:33:40 +0000819 ALOGV("Touch Boost");
Ady Abrahamccf63862023-01-19 11:44:01 -0800820 ATRACE_FORMAT_INSTANT("%s (Touch Boost [late])",
821 to_string(touchRefreshRates.front().frameRateMode.fps).c_str());
ramindanid72ba162022-09-09 21:33:40 +0000822 return {touchRefreshRates, GlobalSignals{.touch = true}};
Steven Thomasf734df42020-04-13 21:09:28 -0700823 }
824
Ady Abraham37d46922022-10-05 13:08:51 -0700825 // If we never scored any layers, and we don't favor high refresh rates, prefer to stay with the
826 // current config
827 if (noLayerScore && refreshRateOrder == RefreshRateOrder::Ascending) {
Rachel Lee67afbea2023-09-28 15:35:07 -0700828 ALOGV("preferredDisplayMode");
Ady Abrahamccf63862023-01-19 11:44:01 -0800829 const auto ascendingWithPreferred =
830 rankFrameRates(anchorGroup, RefreshRateOrder::Ascending, activeMode.getId());
831 ATRACE_FORMAT_INSTANT("%s (preferredDisplayMode)",
832 to_string(ascendingWithPreferred.front().frameRateMode.fps).c_str());
833 return {ascendingWithPreferred, kNoSignals};
Ady Abraham37d46922022-10-05 13:08:51 -0700834 }
835
Rachel Lee67afbea2023-09-28 15:35:07 -0700836 ALOGV("%s (scored))", to_string(ranking.front().frameRateMode.fps).c_str());
Ady Abrahamccf63862023-01-19 11:44:01 -0800837 ATRACE_FORMAT_INSTANT("%s (scored))", to_string(ranking.front().frameRateMode.fps).c_str());
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400838 return {ranking, kNoSignals};
Ady Abraham34702102020-02-10 14:12:05 -0800839}
840
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400841using LayerRequirementPtrs = std::vector<const RefreshRateSelector::LayerRequirement*>;
842using PerUidLayerRequirements = std::unordered_map<uid_t, LayerRequirementPtrs>;
843
844PerUidLayerRequirements groupLayersByUid(
845 const std::vector<RefreshRateSelector::LayerRequirement>& layers) {
846 PerUidLayerRequirements layersByUid;
Ady Abraham62a0be22020-12-08 16:54:10 -0800847 for (const auto& layer : layers) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400848 const auto it = layersByUid.emplace(layer.ownerUid, LayerRequirementPtrs()).first;
849 auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800850 layersWithSameUid.push_back(&layer);
851 }
852
853 // Remove uids that can't have a frame rate override
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400854 for (auto it = layersByUid.begin(); it != layersByUid.end();) {
855 const auto& layersWithSameUid = it->second;
Ady Abraham62a0be22020-12-08 16:54:10 -0800856 bool skipUid = false;
857 for (const auto& layer : layersWithSameUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400858 using LayerVoteType = RefreshRateSelector::LayerVoteType;
859
860 if (layer->vote == LayerVoteType::Max || layer->vote == LayerVoteType::Heuristic) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800861 skipUid = true;
862 break;
863 }
864 }
865 if (skipUid) {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400866 it = layersByUid.erase(it);
Ady Abraham62a0be22020-12-08 16:54:10 -0800867 } else {
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400868 ++it;
Ady Abraham62a0be22020-12-08 16:54:10 -0800869 }
870 }
871
872 return layersByUid;
873}
874
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400875auto RefreshRateSelector::getFrameRateOverrides(const std::vector<LayerRequirement>& layers,
876 Fps displayRefreshRate,
877 GlobalSignals globalSignals) const
878 -> UidToFrameRateOverride {
Ady Abraham62a0be22020-12-08 16:54:10 -0800879 ATRACE_CALL();
Ady Abraham68636062022-11-16 17:07:25 -0800880 if (mConfig.enableFrameRateOverride == Config::FrameRateOverride::Disabled) {
881 return {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800882 }
883
Ady Abraham68636062022-11-16 17:07:25 -0800884 ALOGV("%s: %zu layers", __func__, layers.size());
885 std::lock_guard lock(mLock);
886
Ady Abraham8ca643a2022-10-18 18:26:47 -0700887 const auto* policyPtr = getCurrentPolicyLocked();
888 // We don't want to run lower than 30fps
ramindania04b8a52023-08-07 18:49:47 -0700889 // TODO(b/297600226): revise this for dVRR
Ady Abraham8ca643a2022-10-18 18:26:47 -0700890 const Fps minFrameRate = std::max(policyPtr->appRequestRanges.render.min, 30_Hz, isApproxLess);
891
892 using fps_approx_ops::operator/;
893 const unsigned numMultiples = displayRefreshRate / minFrameRate;
894
895 std::vector<std::pair<Fps, float>> scoredFrameRates;
896 scoredFrameRates.reserve(numMultiples);
897
898 for (unsigned n = numMultiples; n > 0; n--) {
899 const Fps divisor = displayRefreshRate / n;
900 if (mConfig.enableFrameRateOverride ==
Ady Abraham68636062022-11-16 17:07:25 -0800901 Config::FrameRateOverride::AppOverrideNativeRefreshRates &&
902 !isNativeRefreshRate(divisor)) {
Ady Abraham8ca643a2022-10-18 18:26:47 -0700903 continue;
904 }
905
906 if (policyPtr->appRequestRanges.render.includes(divisor)) {
907 ALOGV("%s: adding %s as a potential frame rate", __func__, to_string(divisor).c_str());
908 scoredFrameRates.emplace_back(divisor, 0);
909 }
910 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800911
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400912 const auto layersByUid = groupLayersByUid(layers);
Ady Abraham62a0be22020-12-08 16:54:10 -0800913 UidToFrameRateOverride frameRateOverrides;
914 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800915 // Layers with ExplicitExactOrMultiple expect touch boost
916 const bool hasExplicitExactOrMultiple =
917 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
918 [](const auto& layer) {
919 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
920 });
921
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700922 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800923 continue;
924 }
925
Ady Abraham8ca643a2022-10-18 18:26:47 -0700926 for (auto& [_, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800927 score = 0;
Ady Abraham62a0be22020-12-08 16:54:10 -0800928 }
929
930 for (const auto& layer : layersWithSameUid) {
Rachel Lee47adfcf2023-09-15 17:36:56 -0700931 if (layer->isNoVote() || layer->frameRateCategory == FrameRateCategory::NoPreference ||
932 layer->vote == LayerVoteType::Min) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800933 continue;
934 }
935
936 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Rachel Leece6e0042023-06-27 11:22:54 -0700937 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
938 layer->vote != LayerVoteType::ExplicitExact &&
939 layer->vote != LayerVoteType::ExplicitCategory,
940 "Invalid layer vote type for frame rate overrides");
Ady Abraham8ca643a2022-10-18 18:26:47 -0700941 for (auto& [fps, score] : scoredFrameRates) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800942 constexpr bool isSeamlessSwitch = true;
Ady Abraham8ca643a2022-10-18 18:26:47 -0700943 const auto layerScore = calculateLayerScoreLocked(*layer, fps, isSeamlessSwitch);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800944 score += layer->weight * layerScore;
Ady Abraham62a0be22020-12-08 16:54:10 -0800945 }
946 }
947
Ady Abraham62a0be22020-12-08 16:54:10 -0800948 // If we never scored any layers, we don't have a preferred frame rate
Ady Abraham8ca643a2022-10-18 18:26:47 -0700949 if (std::all_of(scoredFrameRates.begin(), scoredFrameRates.end(),
950 [](const auto& scoredFrameRate) {
951 const auto [_, score] = scoredFrameRate;
952 return score == 0;
953 })) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800954 continue;
955 }
956
ramindanid72ba162022-09-09 21:33:40 +0000957 // Now that we scored all the refresh rates we need to pick the lowest refresh rate
958 // that got the highest score.
Ady Abraham8ca643a2022-10-18 18:26:47 -0700959 const auto [overrideFps, _] =
960 *std::max_element(scoredFrameRates.begin(), scoredFrameRates.end(),
961 [](const auto& lhsPair, const auto& rhsPair) {
962 const float lhs = lhsPair.second;
963 const float rhs = rhsPair.second;
Ady Abraham68636062022-11-16 17:07:25 -0800964 return lhs < rhs && !ScoredFrameRate::scoresEqual(lhs, rhs);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700965 });
966 ALOGV("%s: overriding to %s for uid=%d", __func__, to_string(overrideFps).c_str(), uid);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700967 ATRACE_FORMAT_INSTANT("%s: overriding to %s for uid=%d", __func__,
968 to_string(overrideFps).c_str(), uid);
Ady Abraham8ca643a2022-10-18 18:26:47 -0700969 frameRateOverrides.emplace(uid, overrideFps);
Ady Abraham62a0be22020-12-08 16:54:10 -0800970 }
971
972 return frameRateOverrides;
973}
974
Ady Abraham0aa373a2022-11-22 13:56:50 -0800975ftl::Optional<FrameRateMode> RefreshRateSelector::onKernelTimerChanged(
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800976 std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800977 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100978
Ady Abraham0aa373a2022-11-22 13:56:50 -0800979 const auto current = [&]() REQUIRES(mLock) -> FrameRateMode {
980 if (desiredActiveModeId) {
981 const auto& modePtr = mDisplayModes.get(*desiredActiveModeId)->get();
ramindania04b8a52023-08-07 18:49:47 -0700982 return FrameRateMode{modePtr->getPeakFps(), ftl::as_non_null(modePtr)};
Ady Abraham0aa373a2022-11-22 13:56:50 -0800983 }
984
985 return getActiveModeLocked();
986 }();
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100987
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800988 const DisplayModePtr& min = mMinRefreshRateModeIt->second;
Ady Abraham0aa373a2022-11-22 13:56:50 -0800989 if (current.modePtr->getId() == min->getId()) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800990 return {};
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100991 }
992
ramindania04b8a52023-08-07 18:49:47 -0700993 return timerExpired ? FrameRateMode{min->getPeakFps(), ftl::as_non_null(min)} : current;
Steven Thomasf734df42020-04-13 21:09:28 -0700994}
995
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400996const DisplayModePtr& RefreshRateSelector::getMinRefreshRateByPolicyLocked() const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800997 const auto& activeMode = *getActiveModeLocked().modePtr;
Dominik Laskowskif8734e02022-08-26 09:06:59 -0700998
Ady Abraham68636062022-11-16 17:07:25 -0800999 for (const FrameRateMode& mode : mPrimaryFrameRates) {
1000 if (activeMode.getGroup() == mode.modePtr->getGroup()) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001001 return mode.modePtr.get();
Marin Shalamanov46084422020-10-13 12:33:42 +02001002 }
1003 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001004
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001005 ALOGE("Can't find min refresh rate by policy with the same mode group as the current mode %s",
1006 to_string(activeMode).c_str());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001007
1008 // Default to the lowest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -08001009 return mPrimaryFrameRates.front().modePtr.get();
Ady Abraham2139f732019-11-13 18:56:40 -08001010}
1011
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001012const DisplayModePtr& RefreshRateSelector::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Ady Abrahamace3d052022-11-17 16:25:05 -08001013 const ftl::NonNull<DisplayModePtr>* maxByAnchor = &mPrimaryFrameRates.back().modePtr;
1014 const ftl::NonNull<DisplayModePtr>* max = &mPrimaryFrameRates.back().modePtr;
Ady Abraham68636062022-11-16 17:07:25 -08001015
1016 bool maxByAnchorFound = false;
1017 for (auto it = mPrimaryFrameRates.rbegin(); it != mPrimaryFrameRates.rend(); ++it) {
1018 using namespace fps_approx_ops;
ramindania04b8a52023-08-07 18:49:47 -07001019 if (it->modePtr->getPeakFps() > (*max)->getPeakFps()) {
Ady Abraham68636062022-11-16 17:07:25 -08001020 max = &it->modePtr;
Marin Shalamanov46084422020-10-13 12:33:42 +02001021 }
Ady Abraham68636062022-11-16 17:07:25 -08001022
1023 if (anchorGroup == it->modePtr->getGroup() &&
ramindania04b8a52023-08-07 18:49:47 -07001024 it->modePtr->getPeakFps() >= (*maxByAnchor)->getPeakFps()) {
Ady Abraham68636062022-11-16 17:07:25 -08001025 maxByAnchorFound = true;
1026 maxByAnchor = &it->modePtr;
1027 }
1028 }
1029
1030 if (maxByAnchorFound) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001031 return maxByAnchor->get();
Marin Shalamanov46084422020-10-13 12:33:42 +02001032 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001033
ramindanid72ba162022-09-09 21:33:40 +00001034 ALOGE("Can't find max refresh rate by policy with the same group %d", anchorGroup);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001035
1036 // Default to the highest refresh rate.
Ady Abrahamace3d052022-11-17 16:25:05 -08001037 return max->get();
Ady Abraham2139f732019-11-13 18:56:40 -08001038}
1039
Ady Abraham68636062022-11-16 17:07:25 -08001040auto RefreshRateSelector::rankFrameRates(std::optional<int> anchorGroupOpt,
1041 RefreshRateOrder refreshRateOrder,
Rachel Lee67afbea2023-09-28 15:35:07 -07001042 std::optional<DisplayModeId> preferredDisplayModeOpt,
1043 const RankFrameRatesPredicate& predicate) const
Ady Abraham68636062022-11-16 17:07:25 -08001044 -> FrameRateRanking {
Ady Abrahama5992df2023-01-27 21:10:57 -08001045 using fps_approx_ops::operator<;
Ady Abraham68636062022-11-16 17:07:25 -08001046 const char* const whence = __func__;
Ady Abrahama5992df2023-01-27 21:10:57 -08001047
1048 // find the highest frame rate for each display mode
1049 ftl::SmallMap<DisplayModeId, Fps, 8> maxRenderRateForMode;
1050 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
1051 if (ascending) {
1052 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1053 // use a lower frame rate when we want Ascending frame rates.
1054 for (const auto& frameRateMode : mPrimaryFrameRates) {
1055 if (anchorGroupOpt && frameRateMode.modePtr->getGroup() != anchorGroupOpt) {
1056 continue;
1057 }
1058
1059 const auto [iter, _] = maxRenderRateForMode.try_emplace(frameRateMode.modePtr->getId(),
1060 frameRateMode.fps);
1061 if (iter->second < frameRateMode.fps) {
1062 iter->second = frameRateMode.fps;
1063 }
1064 }
1065 }
1066
Ady Abraham68636062022-11-16 17:07:25 -08001067 std::deque<ScoredFrameRate> ranking;
1068 const auto rankFrameRate = [&](const FrameRateMode& frameRateMode) REQUIRES(mLock) {
1069 const auto& modePtr = frameRateMode.modePtr;
Rachel Lee67afbea2023-09-28 15:35:07 -07001070 if ((anchorGroupOpt && modePtr->getGroup() != anchorGroupOpt) ||
1071 !predicate(frameRateMode)) {
Ady Abraham37d46922022-10-05 13:08:51 -07001072 return;
ramindanid72ba162022-09-09 21:33:40 +00001073 }
Ady Abraham37d46922022-10-05 13:08:51 -07001074
Ady Abraham3f965922023-01-23 17:18:29 -08001075 const bool ascending = (refreshRateOrder == RefreshRateOrder::Ascending);
ramindanif7075202023-03-10 00:24:34 +00001076 const auto id = modePtr->getId();
Ady Abrahama5992df2023-01-27 21:10:57 -08001077 if (ascending && frameRateMode.fps < *maxRenderRateForMode.get(id)) {
Ady Abraham3f965922023-01-23 17:18:29 -08001078 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround and actually
1079 // use a lower frame rate when we want Ascending frame rates.
1080 return;
1081 }
1082
Ady Abraham68636062022-11-16 17:07:25 -08001083 float score = calculateDistanceScoreFromMax(frameRateMode.fps);
Ady Abraham3f965922023-01-23 17:18:29 -08001084
1085 if (ascending) {
Ady Abraham37d46922022-10-05 13:08:51 -07001086 score = 1.0f / score;
1087 }
ramindanif7075202023-03-10 00:24:34 +00001088
1089 constexpr float kScore = std::numeric_limits<float>::max();
Ady Abraham37d46922022-10-05 13:08:51 -07001090 if (preferredDisplayModeOpt) {
Ady Abraham68636062022-11-16 17:07:25 -08001091 if (*preferredDisplayModeOpt == modePtr->getId()) {
Ady Abraham68636062022-11-16 17:07:25 -08001092 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
Ady Abraham37d46922022-10-05 13:08:51 -07001093 return;
1094 }
1095 constexpr float kNonPreferredModePenalty = 0.95f;
1096 score *= kNonPreferredModePenalty;
ramindanif7075202023-03-10 00:24:34 +00001097 } else if (ascending && id == getMinRefreshRateByPolicyLocked()->getId()) {
1098 // TODO(b/266481656): Once this bug is fixed, we can remove this workaround
1099 // and actually use a lower frame rate when we want Ascending frame rates.
1100 ranking.emplace_front(ScoredFrameRate{frameRateMode, kScore});
1101 return;
Ady Abraham37d46922022-10-05 13:08:51 -07001102 }
Ady Abraham3f965922023-01-23 17:18:29 -08001103
ramindania04b8a52023-08-07 18:49:47 -07001104 ALOGV("%s(%s) %s (%s(%s)) scored %.2f", whence, ftl::enum_string(refreshRateOrder).c_str(),
1105 to_string(frameRateMode.fps).c_str(), to_string(modePtr->getPeakFps()).c_str(),
1106 to_string(modePtr->getVsyncRate()).c_str(), score);
Ady Abraham68636062022-11-16 17:07:25 -08001107 ranking.emplace_back(ScoredFrameRate{frameRateMode, score});
ramindanid72ba162022-09-09 21:33:40 +00001108 };
1109
1110 if (refreshRateOrder == RefreshRateOrder::Ascending) {
Ady Abraham68636062022-11-16 17:07:25 -08001111 std::for_each(mPrimaryFrameRates.begin(), mPrimaryFrameRates.end(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001112 } else {
Ady Abraham68636062022-11-16 17:07:25 -08001113 std::for_each(mPrimaryFrameRates.rbegin(), mPrimaryFrameRates.rend(), rankFrameRate);
ramindanid72ba162022-09-09 21:33:40 +00001114 }
1115
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001116 if (!ranking.empty() || !anchorGroupOpt) {
1117 return {ranking.begin(), ranking.end()};
ramindanid72ba162022-09-09 21:33:40 +00001118 }
1119
1120 ALOGW("Can't find %s refresh rate by policy with the same mode group"
1121 " as the mode group %d",
1122 refreshRateOrder == RefreshRateOrder::Ascending ? "min" : "max", anchorGroupOpt.value());
1123
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001124 constexpr std::optional<int> kNoAnchorGroup = std::nullopt;
Ady Abraham68636062022-11-16 17:07:25 -08001125 return rankFrameRates(kNoAnchorGroup, refreshRateOrder, preferredDisplayModeOpt);
ramindanid72ba162022-09-09 21:33:40 +00001126}
1127
Ady Abrahamace3d052022-11-17 16:25:05 -08001128FrameRateMode RefreshRateSelector::getActiveMode() const {
Ady Abraham2139f732019-11-13 18:56:40 -08001129 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001130 return getActiveModeLocked();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001131}
1132
Ady Abrahamace3d052022-11-17 16:25:05 -08001133const FrameRateMode& RefreshRateSelector::getActiveModeLocked() const {
1134 return *mActiveModeOpt;
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001135}
1136
Ady Abrahamace3d052022-11-17 16:25:05 -08001137void RefreshRateSelector::setActiveMode(DisplayModeId modeId, Fps renderFrameRate) {
Ady Abraham2139f732019-11-13 18:56:40 -08001138 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001139
Ady Abraham68636062022-11-16 17:07:25 -08001140 // Invalidate the cached invocation to getRankedFrameRates. This forces
1141 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1142 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001143
Ady Abrahamace3d052022-11-17 16:25:05 -08001144 const auto activeModeOpt = mDisplayModes.get(modeId);
1145 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
1146
1147 mActiveModeOpt.emplace(FrameRateMode{renderFrameRate, ftl::as_non_null(activeModeOpt->get())});
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001148}
1149
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001150RefreshRateSelector::RefreshRateSelector(DisplayModes modes, DisplayModeId activeModeId,
1151 Config config)
rnlee3bd610662021-06-23 16:27:57 -07001152 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001153 initializeIdleTimer();
Dominik Laskowskif8734e02022-08-26 09:06:59 -07001154 FTL_FAKE_GUARD(kMainThreadContext, updateDisplayModes(std::move(modes), activeModeId));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001155}
1156
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001157void RefreshRateSelector::initializeIdleTimer() {
ramindani32cf0602022-03-02 02:30:29 +00001158 if (mConfig.idleTimerTimeout > 0ms) {
Ady Abraham9a2ea342021-09-03 17:32:34 -07001159 mIdleTimer.emplace(
ramindani32cf0602022-03-02 02:30:29 +00001160 "IdleTimer", mConfig.idleTimerTimeout,
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001161 [this] {
1162 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1163 if (const auto callbacks = getIdleTimerCallbacks()) {
1164 callbacks->onReset();
1165 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001166 },
Dominik Laskowski83bd7712022-01-07 14:30:53 -08001167 [this] {
1168 std::scoped_lock lock(mIdleTimerCallbacksMutex);
1169 if (const auto callbacks = getIdleTimerCallbacks()) {
1170 callbacks->onExpired();
1171 }
Ady Abraham9a2ea342021-09-03 17:32:34 -07001172 });
Ady Abraham9a2ea342021-09-03 17:32:34 -07001173 }
1174}
1175
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001176void RefreshRateSelector::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +01001177 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001178
Ady Abraham68636062022-11-16 17:07:25 -08001179 // Invalidate the cached invocation to getRankedFrameRates. This forces
1180 // the refresh rate to be recomputed on the next call to getRankedFrameRates.
1181 mGetRankedFrameRatesCache.reset();
Marin Shalamanov4c7831e2021-06-08 20:44:06 +02001182
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001183 mDisplayModes = std::move(modes);
Ady Abrahamace3d052022-11-17 16:25:05 -08001184 const auto activeModeOpt = mDisplayModes.get(activeModeId);
1185 LOG_ALWAYS_FATAL_IF(!activeModeOpt);
ramindania04b8a52023-08-07 18:49:47 -07001186 mActiveModeOpt = FrameRateMode{activeModeOpt->get()->getPeakFps(),
1187 ftl::as_non_null(activeModeOpt->get())};
Ady Abrahamabc27602020-04-08 17:20:29 -07001188
Ady Abraham68636062022-11-16 17:07:25 -08001189 const auto sortedModes = sortByRefreshRate(mDisplayModes);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001190 mMinRefreshRateModeIt = sortedModes.front();
1191 mMaxRefreshRateModeIt = sortedModes.back();
1192
Marin Shalamanov75f37252021-02-10 21:43:57 +01001193 // Reset the policy because the old one may no longer be valid.
1194 mDisplayManagerPolicy = {};
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001195 mDisplayManagerPolicy.defaultMode = activeModeId;
Ady Abraham64c2fc02020-12-29 12:07:50 -08001196
Ady Abraham8ca643a2022-10-18 18:26:47 -07001197 mFrameRateOverrideConfig = [&] {
1198 switch (mConfig.enableFrameRateOverride) {
1199 case Config::FrameRateOverride::Disabled:
Ady Abraham68636062022-11-16 17:07:25 -08001200 case Config::FrameRateOverride::AppOverride:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001201 case Config::FrameRateOverride::Enabled:
1202 return mConfig.enableFrameRateOverride;
Ady Abraham68636062022-11-16 17:07:25 -08001203 case Config::FrameRateOverride::AppOverrideNativeRefreshRates:
Ady Abraham8ca643a2022-10-18 18:26:47 -07001204 return shouldEnableFrameRateOverride(sortedModes)
Ady Abraham68636062022-11-16 17:07:25 -08001205 ? Config::FrameRateOverride::AppOverrideNativeRefreshRates
Ady Abraham8ca643a2022-10-18 18:26:47 -07001206 : Config::FrameRateOverride::Disabled;
1207 }
1208 }();
Ady Abraham4899ff82021-01-06 13:53:29 -08001209
Ady Abraham68636062022-11-16 17:07:25 -08001210 if (mConfig.enableFrameRateOverride ==
1211 Config::FrameRateOverride::AppOverrideNativeRefreshRates) {
1212 for (const auto& [_, mode] : mDisplayModes) {
ramindania04b8a52023-08-07 18:49:47 -07001213 mAppOverrideNativeRefreshRates.try_emplace(mode->getPeakFps(), ftl::unit);
Ady Abraham68636062022-11-16 17:07:25 -08001214 }
1215 }
1216
Ady Abrahamabc27602020-04-08 17:20:29 -07001217 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -08001218}
1219
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001220bool RefreshRateSelector::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001221 // defaultMode must be a valid mode, and within the given refresh rate range.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001222 if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
ramindania04b8a52023-08-07 18:49:47 -07001223 if (!policy.primaryRanges.physical.includes(mode->get()->getPeakFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001224 ALOGE("Default mode is not in the primary range.");
1225 return false;
1226 }
1227 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001228 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -07001229 return false;
1230 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001231
Ady Abraham68636062022-11-16 17:07:25 -08001232 const auto& primaryRanges = policy.primaryRanges;
1233 const auto& appRequestRanges = policy.appRequestRanges;
1234 ALOGE_IF(!appRequestRanges.physical.includes(primaryRanges.physical),
Ady Abraham08048ce2022-11-30 18:08:00 -08001235 "Physical range is invalid: primary: %s appRequest: %s",
1236 to_string(primaryRanges.physical).c_str(),
1237 to_string(appRequestRanges.physical).c_str());
1238 ALOGE_IF(!appRequestRanges.render.includes(primaryRanges.render),
1239 "Render range is invalid: primary: %s appRequest: %s",
1240 to_string(primaryRanges.render).c_str(), to_string(appRequestRanges.render).c_str());
Ady Abraham68636062022-11-16 17:07:25 -08001241
1242 return primaryRanges.valid() && appRequestRanges.valid();
Steven Thomasd4071902020-03-24 16:02:53 -07001243}
1244
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001245auto RefreshRateSelector::setPolicy(const PolicyVariant& policy) -> SetPolicyResult {
Dominik Laskowski36dced82022-09-02 09:24:00 -07001246 Policy oldPolicy;
Ady Abrahamace3d052022-11-17 16:25:05 -08001247 PhysicalDisplayId displayId;
Dominik Laskowski36dced82022-09-02 09:24:00 -07001248 {
1249 std::lock_guard lock(mLock);
1250 oldPolicy = *getCurrentPolicyLocked();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001251
Dominik Laskowski36dced82022-09-02 09:24:00 -07001252 const bool valid = ftl::match(
1253 policy,
1254 [this](const auto& policy) {
1255 ftl::FakeGuard guard(mLock);
1256 if (!isPolicyValidLocked(policy)) {
1257 ALOGE("Invalid policy: %s", policy.toString().c_str());
1258 return false;
1259 }
1260
1261 using T = std::decay_t<decltype(policy)>;
1262
1263 if constexpr (std::is_same_v<T, DisplayManagerPolicy>) {
1264 mDisplayManagerPolicy = policy;
1265 } else {
1266 static_assert(std::is_same_v<T, OverridePolicy>);
1267 mOverridePolicy = policy;
1268 }
1269 return true;
1270 },
1271 [this](NoOverridePolicy) {
1272 ftl::FakeGuard guard(mLock);
1273 mOverridePolicy.reset();
1274 return true;
1275 });
1276
1277 if (!valid) {
1278 return SetPolicyResult::Invalid;
1279 }
1280
Ady Abraham68636062022-11-16 17:07:25 -08001281 mGetRankedFrameRatesCache.reset();
Dominik Laskowski36dced82022-09-02 09:24:00 -07001282
1283 if (*getCurrentPolicyLocked() == oldPolicy) {
1284 return SetPolicyResult::Unchanged;
1285 }
1286 constructAvailableRefreshRates();
Ady Abrahamace3d052022-11-17 16:25:05 -08001287
1288 displayId = getActiveModeLocked().modePtr->getPhysicalDisplayId();
Steven Thomasd4071902020-03-24 16:02:53 -07001289 }
Dominik Laskowski36dced82022-09-02 09:24:00 -07001290
Dominik Laskowski36dced82022-09-02 09:24:00 -07001291 const unsigned numModeChanges = std::exchange(mNumModeSwitchesInPolicy, 0u);
1292
1293 ALOGI("Display %s policy changed\n"
1294 "Previous: %s\n"
1295 "Current: %s\n"
1296 "%u mode changes were performed under the previous policy",
1297 to_string(displayId).c_str(), oldPolicy.toString().c_str(), toString(policy).c_str(),
1298 numModeChanges);
1299
1300 return SetPolicyResult::Changed;
Steven Thomasd4071902020-03-24 16:02:53 -07001301}
1302
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001303auto RefreshRateSelector::getCurrentPolicyLocked() const -> const Policy* {
Steven Thomasd4071902020-03-24 16:02:53 -07001304 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
1305}
1306
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001307auto RefreshRateSelector::getCurrentPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001308 std::lock_guard lock(mLock);
1309 return *getCurrentPolicyLocked();
1310}
1311
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001312auto RefreshRateSelector::getDisplayManagerPolicy() const -> Policy {
Steven Thomasd4071902020-03-24 16:02:53 -07001313 std::lock_guard lock(mLock);
1314 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001315}
1316
Ady Abrahamace3d052022-11-17 16:25:05 -08001317bool RefreshRateSelector::isModeAllowed(const FrameRateMode& mode) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001318 std::lock_guard lock(mLock);
Ady Abrahamace3d052022-11-17 16:25:05 -08001319 return std::find(mAppRequestFrameRates.begin(), mAppRequestFrameRates.end(), mode) !=
1320 mAppRequestFrameRates.end();
Ady Abraham2139f732019-11-13 18:56:40 -08001321}
1322
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001323void RefreshRateSelector::constructAvailableRefreshRates() {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001324 // Filter modes based on current policy and sort on refresh rate.
Steven Thomasd4071902020-03-24 16:02:53 -07001325 const Policy* policy = getCurrentPolicyLocked();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001326 ALOGV("%s: %s ", __func__, policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -07001327
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001328 const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
Ady Abraham8a82ba62020-01-17 12:43:17 -08001329
Ady Abraham68636062022-11-16 17:07:25 -08001330 const auto filterRefreshRates = [&](const FpsRanges& ranges,
1331 const char* rangeName) REQUIRES(mLock) {
1332 const auto filterModes = [&](const DisplayMode& mode) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001333 return mode.getResolution() == defaultMode->getResolution() &&
1334 mode.getDpi() == defaultMode->getDpi() &&
1335 (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
ramindania04b8a52023-08-07 18:49:47 -07001336 ranges.physical.includes(mode.getPeakFps()) &&
1337 (supportsFrameRateOverride() || ranges.render.includes(mode.getPeakFps()));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001338 };
Ady Abraham8a82ba62020-01-17 12:43:17 -08001339
Ady Abraham90f7fd22023-08-16 11:02:00 -07001340 auto frameRateModes = createFrameRateModes(*policy, filterModes, ranges.render);
Ady Abraham41bf7c62023-07-20 10:33:06 -07001341 if (frameRateModes.empty()) {
1342 ALOGW("No matching frame rate modes for %s range. policy: %s", rangeName,
1343 policy->toString().c_str());
1344 // TODO(b/292105422): Ideally DisplayManager should not send render ranges smaller than
1345 // the min supported. See b/292047939.
1346 // For not we just ignore the render ranges.
Ady Abraham90f7fd22023-08-16 11:02:00 -07001347 frameRateModes = createFrameRateModes(*policy, filterModes, {});
Ady Abraham41bf7c62023-07-20 10:33:06 -07001348 }
Ady Abraham68636062022-11-16 17:07:25 -08001349 LOG_ALWAYS_FATAL_IF(frameRateModes.empty(),
Ady Abraham41bf7c62023-07-20 10:33:06 -07001350 "No matching frame rate modes for %s range even after ignoring the "
1351 "render range. policy: %s",
1352 rangeName, policy->toString().c_str());
Dominik Laskowski953b7fd2022-01-08 19:34:59 -08001353
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001354 const auto stringifyModes = [&] {
1355 std::string str;
Ady Abraham68636062022-11-16 17:07:25 -08001356 for (const auto& frameRateMode : frameRateModes) {
1357 str += to_string(frameRateMode) + " ";
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001358 }
1359 return str;
1360 };
Ady Abraham68636062022-11-16 17:07:25 -08001361 ALOGV("%s render rates: %s", rangeName, stringifyModes().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -07001362
Ady Abraham68636062022-11-16 17:07:25 -08001363 return frameRateModes;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001364 };
1365
Ady Abraham68636062022-11-16 17:07:25 -08001366 mPrimaryFrameRates = filterRefreshRates(policy->primaryRanges, "primary");
1367 mAppRequestFrameRates = filterRefreshRates(policy->appRequestRanges, "app request");
Ady Abraham2139f732019-11-13 18:56:40 -08001368}
1369
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001370Fps RefreshRateSelector::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001371 using namespace fps_approx_ops;
1372
1373 if (frameRate <= mKnownFrameRates.front()) {
1374 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001375 }
1376
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001377 if (frameRate >= mKnownFrameRates.back()) {
1378 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001379 }
1380
Marin Shalamanove8a663d2020-11-24 17:48:00 +01001381 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001382 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001383
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001384 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
1385 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -07001386 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
1387}
1388
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001389auto RefreshRateSelector::getIdleTimerAction() const -> KernelIdleTimerAction {
Ana Krulecb9afd792020-06-11 13:16:15 -07001390 std::lock_guard lock(mLock);
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001391
ramindania04b8a52023-08-07 18:49:47 -07001392 const Fps deviceMinFps = mMinRefreshRateModeIt->second->getPeakFps();
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001393 const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -07001394
1395 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
1396 // the min allowed refresh rate is higher than the device min, we do not want to enable the
1397 // timer.
ramindania04b8a52023-08-07 18:49:47 -07001398 if (isStrictlyLess(deviceMinFps, minByPolicy->getPeakFps())) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001399 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001400 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001401
ramindanid72ba162022-09-09 21:33:40 +00001402 const DisplayModePtr& maxByPolicy =
Ady Abrahamace3d052022-11-17 16:25:05 -08001403 getMaxRefreshRateByPolicyLocked(getActiveModeLocked().modePtr->getGroup());
Ana Krulecb9afd792020-06-11 13:16:15 -07001404 if (minByPolicy == maxByPolicy) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001405 // Turn on the timer when the min of the primary range is below the device min.
1406 if (const Policy* currentPolicy = getCurrentPolicyLocked();
Ady Abraham285f8c12022-10-11 17:12:14 -07001407 isApproxLess(currentPolicy->primaryRanges.physical.min, deviceMinFps)) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001408 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001409 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001410 return KernelIdleTimerAction::TurnOff;
Ana Krulecb9afd792020-06-11 13:16:15 -07001411 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001412
Ana Krulecb9afd792020-06-11 13:16:15 -07001413 // Turn on the timer in all other cases.
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001414 return KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -07001415}
1416
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001417int RefreshRateSelector::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -07001418 // This calculation needs to be in sync with the java code
1419 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001420
1421 // The threshold must be smaller than 0.001 in order to differentiate
1422 // between the fractional pairs (e.g. 59.94 and 60).
1423 constexpr float kThreshold = 0.0009f;
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001424 const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -07001425 const auto numPeriodsRounded = std::round(numPeriods);
1426 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -08001427 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -07001428 }
1429
Ady Abraham62f216c2020-10-13 19:07:23 -07001430 return static_cast<int>(numPeriodsRounded);
1431}
1432
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001433bool RefreshRateSelector::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001434 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001435 return isFractionalPairOrMultiple(bigger, smaller);
1436 }
1437
1438 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
1439 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001440 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
1441 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001442}
1443
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001444void RefreshRateSelector::dump(utils::Dumper& dumper) const {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001445 using namespace std::string_view_literals;
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001446
Marin Shalamanovba421a82020-11-10 21:49:26 +01001447 std::lock_guard lock(mLock);
Marin Shalamanovba421a82020-11-10 21:49:26 +01001448
Ady Abrahamace3d052022-11-17 16:25:05 -08001449 const auto activeMode = getActiveModeLocked();
1450 dumper.dump("activeMode"sv, to_string(activeMode));
Marin Shalamanovba421a82020-11-10 21:49:26 +01001451
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001452 dumper.dump("displayModes"sv);
1453 {
1454 utils::Dumper::Indent indent(dumper);
1455 for (const auto& [id, mode] : mDisplayModes) {
1456 dumper.dump({}, to_string(*mode));
1457 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001458 }
1459
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001460 dumper.dump("displayManagerPolicy"sv, mDisplayManagerPolicy.toString());
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001461
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001462 if (const Policy& currentPolicy = *getCurrentPolicyLocked();
1463 mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Dominik Laskowskie70461a2022-08-30 14:42:01 -07001464 dumper.dump("overridePolicy"sv, currentPolicy.toString());
ramindani32cf0602022-03-02 02:30:29 +00001465 }
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001466
Ady Abraham8ca643a2022-10-18 18:26:47 -07001467 dumper.dump("frameRateOverrideConfig"sv, *ftl::enum_name(mFrameRateOverrideConfig));
Dominik Laskowski0acc3842022-04-07 11:23:42 -07001468
Dominik Laskowski03cfce82022-11-02 12:13:29 -04001469 dumper.dump("idleTimer"sv);
1470 {
1471 utils::Dumper::Indent indent(dumper);
1472 dumper.dump("interval"sv, mIdleTimer.transform(&OneShotTimer::interval));
1473 dumper.dump("controller"sv,
1474 mConfig.kernelIdleTimerController
1475 .and_then(&ftl::enum_name<KernelIdleTimerController>)
1476 .value_or("Platform"sv));
Dominik Laskowskib0054a22022-03-03 09:03:06 -08001477 }
Marin Shalamanovba421a82020-11-10 21:49:26 +01001478}
1479
Dominik Laskowskid82e0f02022-10-26 15:23:04 -04001480std::chrono::milliseconds RefreshRateSelector::getIdleTimerTimeout() {
ramindani32cf0602022-03-02 02:30:29 +00001481 return mConfig.idleTimerTimeout;
1482}
1483
Rachel Leece6e0042023-06-27 11:22:54 -07001484// TODO(b/293651105): Extract category FpsRange mapping to OEM-configurable config.
1485FpsRange RefreshRateSelector::getFrameRateCategoryRange(FrameRateCategory category) {
1486 switch (category) {
1487 case FrameRateCategory::High:
1488 return FpsRange{90_Hz, 120_Hz};
1489 case FrameRateCategory::Normal:
1490 return FpsRange{60_Hz, 90_Hz};
1491 case FrameRateCategory::Low:
1492 return FpsRange{30_Hz, 60_Hz};
1493 case FrameRateCategory::NoPreference:
1494 case FrameRateCategory::Default:
1495 LOG_ALWAYS_FATAL("Should not get fps range for frame rate category: %s",
1496 ftl::enum_string(category).c_str());
1497 return FpsRange{0_Hz, 0_Hz};
1498 default:
1499 LOG_ALWAYS_FATAL("Invalid frame rate category for range: %s",
1500 ftl::enum_string(category).c_str());
1501 return FpsRange{0_Hz, 0_Hz};
1502 }
1503}
1504
Ady Abraham2139f732019-11-13 18:56:40 -08001505} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001506
1507// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001508#pragma clang diagnostic pop // ignored "-Wextra"