blob: 3331185caa877c1ffcc9cf83e38a2f3968d1a19a [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 Laskowskif5d0ea52021-09-26 17:27:01 -070026
27#include <android-base/properties.h>
28#include <android-base/stringprintf.h>
29#include <ftl/enum.h>
30#include <utils/Trace.h>
31
Ady Abraham4899ff82021-01-06 13:53:29 -080032#include "../SurfaceFlingerProperties.h"
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070033#include "RefreshRateConfigs.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080034
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080035#undef LOG_TAG
36#define LOG_TAG "RefreshRateConfigs"
37
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080038namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010039namespace {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070040
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010041std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010042 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070043 ftl::enum_string(layer.vote).c_str(), weight,
44 ftl::enum_string(layer.seamlessness).c_str(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +010045 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010046}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010047
Marin Shalamanova7fe3042021-01-29 21:02:08 +010048std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070049 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010050 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010051
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070052 // Add all supported refresh rates.
Marin Shalamanova7fe3042021-01-29 21:02:08 +010053 for (const auto& mode : modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070054 knownFrameRates.push_back(Fps::fromPeriodNsecs(mode->getVsyncPeriod()));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010055 }
56
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070057 // Sort and remove duplicates.
58 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010059 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070060 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010061 knownFrameRates.end());
62 return knownFrameRates;
63}
64
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010065} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080066
67using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080068using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080069
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070070bool RefreshRate::inPolicy(Fps minRefreshRate, Fps maxRefreshRate) const {
71 using fps_approx_ops::operator<=;
72 return minRefreshRate <= getFps() && getFps() <= maxRefreshRate;
73}
74
Marin Shalamanov46084422020-10-13 12:33:42 +020075std::string RefreshRate::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010076 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010077 getModeId().value(), mode->getHwcId(), getFps().getValue(),
78 mode->getWidth(), mode->getHeight(), getModeGroup());
Marin Shalamanov46084422020-10-13 12:33:42 +020079}
80
Marin Shalamanovb6674e72020-11-06 13:05:57 +010081std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010082 return base::StringPrintf("default mode ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010083 ", primary range: %s, app request range: %s",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010084 defaultMode.value(), allowGroupSwitching,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010085 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020086}
87
Ady Abraham4ccdcb42020-02-11 17:34:34 -080088std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
89 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -080090 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
91 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
92 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
93 quotient++;
94 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -080095 }
96
Ady Abraham62a0be22020-12-08 16:54:10 -080097 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -080098}
99
rnlee3bd610662021-06-23 16:27:57 -0700100bool RefreshRateConfigs::isVoteAllowed(const LayerRequirement& layer,
101 const RefreshRate& refreshRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700102 using namespace fps_approx_ops;
103
rnlee3bd610662021-06-23 16:27:57 -0700104 switch (layer.vote) {
105 case LayerVoteType::ExplicitExactOrMultiple:
106 case LayerVoteType::Heuristic:
107 if (mConfig.frameRateMultipleThreshold != 0 &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700108 refreshRate.getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold) &&
109 layer.desiredRefreshRate < Fps::fromValue(mConfig.frameRateMultipleThreshold / 2)) {
rnlee3bd610662021-06-23 16:27:57 -0700110 // Don't vote high refresh rates past the threshold for layers with a low desired
111 // refresh rate. For example, desired 24 fps with 120 Hz threshold means no vote for
112 // 120 Hz, but desired 60 fps should have a vote.
113 return false;
114 }
115 break;
116 case LayerVoteType::ExplicitDefault:
117 case LayerVoteType::ExplicitExact:
118 case LayerVoteType::Max:
119 case LayerVoteType::Min:
120 case LayerVoteType::NoVote:
121 break;
122 }
123 return true;
124}
125
Ady Abraham05243be2021-09-16 15:58:52 -0700126float RefreshRateConfigs::calculateNonExactMatchingLayerScoreLocked(
127 const LayerRequirement& layer, const RefreshRate& refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200128 constexpr float kScoreForFractionalPairs = .8f;
129
Ady Abraham62a0be22020-12-08 16:54:10 -0800130 const auto displayPeriod = refreshRate.getVsyncPeriod();
131 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
132 if (layer.vote == LayerVoteType::ExplicitDefault) {
133 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200134 // that layerPeriod is the minimal period to render a frame.
135 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
136 // then the actualLayerPeriod will be 32ms, because it is the
137 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800138 auto actualLayerPeriod = displayPeriod;
139 int multiplier = 1;
140 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
141 multiplier++;
142 actualLayerPeriod = displayPeriod * multiplier;
143 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200144
145 // Because of the threshold we used above it's possible that score is slightly
146 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800147 return std::min(1.0f,
148 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
149 }
150
151 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
152 layer.vote == LayerVoteType::Heuristic) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200153 if (isFractionalPairOrMultiple(refreshRate.getFps(), layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700154 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200155 }
156
Ady Abraham62a0be22020-12-08 16:54:10 -0800157 // Calculate how many display vsyncs we need to present a single frame for this
158 // layer
159 const auto [displayFramesQuotient, displayFramesRemainder] =
160 getDisplayFrames(layerPeriod, displayPeriod);
161 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
162 if (displayFramesRemainder == 0) {
163 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700164 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800165 }
166
167 if (displayFramesQuotient == 0) {
168 // Layer desired refresh rate is higher than the display rate.
169 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
170 (1.0f / (MAX_FRAMES_TO_FIT + 1));
171 }
172
173 // Layer desired refresh rate is lower than the display rate. Check how well it fits
174 // the cadence.
175 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
176 int iter = 2;
177 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
178 diff = diff - (displayPeriod - diff);
179 iter++;
180 }
181
Ady Abraham05243be2021-09-16 15:58:52 -0700182 return (1.0f / iter);
183 }
184
185 return 0;
186}
187
188float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
189 const RefreshRate& refreshRate,
190 bool isSeamlessSwitch) const {
191 if (!isVoteAllowed(layer, refreshRate)) {
192 return 0;
193 }
194
195 // Slightly prefer seamless switches.
196 constexpr float kSeamedSwitchPenalty = 0.95f;
197 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
198
199 // If the layer wants Max, give higher score to the higher refresh rate
200 if (layer.vote == LayerVoteType::Max) {
201 const auto ratio = refreshRate.getFps().getValue() /
202 mAppRequestRefreshRates.back()->getFps().getValue();
203 // use ratio^2 to get a lower score the more we get further from peak
204 return ratio * ratio;
Ady Abraham62a0be22020-12-08 16:54:10 -0800205 }
206
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800207 if (layer.vote == LayerVoteType::ExplicitExact) {
208 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
209 if (mSupportsFrameRateOverride) {
210 // Since we support frame rate override, allow refresh rates which are
211 // multiples of the layer's request, as those apps would be throttled
212 // down to run at the desired refresh rate.
213 return divider > 0;
214 }
215
216 return divider == 1;
217 }
218
Ady Abraham05243be2021-09-16 15:58:52 -0700219 // If the layer frame rate is a divider of the refresh rate it should score
220 // the highest score.
221 if (getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate) > 0) {
222 return 1.0f * seamlessness;
223 }
224
225 // The layer frame rate is not a divider of the refresh rate,
226 // there is a small penalty attached to the score to favor the frame rates
227 // the exactly matches the display refresh rate or a multiple.
Ady Abraham1c595502022-01-13 21:58:32 -0800228 constexpr float kNonExactMatchingPenalty = 0.95f;
Ady Abraham05243be2021-09-16 15:58:52 -0700229 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
230 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800231}
232
233struct RefreshRateScore {
234 const RefreshRate* refreshRate;
235 float score;
236};
237
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100238RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700239 GlobalSignals globalSignals,
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100240 GlobalSignals* outSignalsConsidered) const {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200241 std::lock_guard lock(mLock);
242
243 if (auto cached = getCachedBestRefreshRate(layers, globalSignals, outSignalsConsidered)) {
244 return *cached;
245 }
246
247 GlobalSignals signalsConsidered;
248 RefreshRate result = getBestRefreshRateLocked(layers, globalSignals, &signalsConsidered);
249 lastBestRefreshRateInvocation.emplace(
250 GetBestRefreshRateInvocation{.layerRequirements = layers,
251 .globalSignals = globalSignals,
252 .outSignalsConsidered = signalsConsidered,
253 .resultingBestRefreshRate = result});
254 if (outSignalsConsidered) {
255 *outSignalsConsidered = signalsConsidered;
256 }
257 return result;
258}
259
260std::optional<RefreshRate> RefreshRateConfigs::getCachedBestRefreshRate(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700261 const std::vector<LayerRequirement>& layers, GlobalSignals globalSignals,
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200262 GlobalSignals* outSignalsConsidered) const {
263 const bool sameAsLastCall = lastBestRefreshRateInvocation &&
264 lastBestRefreshRateInvocation->layerRequirements == layers &&
265 lastBestRefreshRateInvocation->globalSignals == globalSignals;
266
267 if (sameAsLastCall) {
268 if (outSignalsConsidered) {
269 *outSignalsConsidered = lastBestRefreshRateInvocation->outSignalsConsidered;
270 }
271 return lastBestRefreshRateInvocation->resultingBestRefreshRate;
272 }
273
274 return {};
275}
276
277RefreshRate RefreshRateConfigs::getBestRefreshRateLocked(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700278 const std::vector<LayerRequirement>& layers, GlobalSignals globalSignals,
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200279 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800280 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200281 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800282
Ady Abrahamdfd62162020-06-10 16:11:56 -0700283 if (outSignalsConsidered) *outSignalsConsidered = {};
284 const auto setTouchConsidered = [&] {
285 if (outSignalsConsidered) {
286 outSignalsConsidered->touch = true;
287 }
288 };
289
290 const auto setIdleConsidered = [&] {
291 if (outSignalsConsidered) {
292 outSignalsConsidered->idle = true;
293 }
294 };
295
Ady Abraham8a82ba62020-01-17 12:43:17 -0800296 int noVoteLayers = 0;
297 int minVoteLayers = 0;
298 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800299 int explicitDefaultVoteLayers = 0;
300 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800301 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800302 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100303 int seamedFocusedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800304 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800305 switch (layer.vote) {
306 case LayerVoteType::NoVote:
307 noVoteLayers++;
308 break;
309 case LayerVoteType::Min:
310 minVoteLayers++;
311 break;
312 case LayerVoteType::Max:
313 maxVoteLayers++;
314 break;
315 case LayerVoteType::ExplicitDefault:
316 explicitDefaultVoteLayers++;
317 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
318 break;
319 case LayerVoteType::ExplicitExactOrMultiple:
320 explicitExactOrMultipleVoteLayers++;
321 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
322 break;
323 case LayerVoteType::ExplicitExact:
324 explicitExact++;
325 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
326 break;
327 case LayerVoteType::Heuristic:
328 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800329 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200330
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100331 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
332 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200333 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800334 }
335
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800336 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
337 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700338
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200339 const Policy* policy = getCurrentPolicyLocked();
340 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
341 // If the default mode group is different from the group of current mode,
342 // this means a layer requesting a seamed mode switch just disappeared and
343 // we should switch back to the default group.
344 // However if a seamed layer is still present we anchor around the group
345 // of the current mode, in order to prevent unnecessary seamed mode switches
346 // (e.g. when pausing a video playback).
347 const auto anchorGroup = seamedFocusedLayers > 0 ? mCurrentRefreshRate->getModeGroup()
348 : defaultMode->getModeGroup();
349
Steven Thomasf734df42020-04-13 21:09:28 -0700350 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
351 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700352 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700353 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700354 setTouchConsidered();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200355 return getMaxRefreshRateByPolicyLocked(anchorGroup);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800356 }
357
Alec Mouri11232a22020-05-14 18:06:25 -0700358 // If the primary range consists of a single refresh rate then we can only
359 // move out the of range if layers explicitly request a different refresh
360 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100361 const bool primaryRangeIsSingleRate =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700362 isApproxEqual(policy->primaryRange.min, policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700363
Ady Abrahamdfd62162020-06-10 16:11:56 -0700364 if (!globalSignals.touch && globalSignals.idle &&
365 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700366 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700367 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700368 return getMinRefreshRateByPolicyLocked();
369 }
370
Steven Thomasdebafed2020-05-18 17:30:35 -0700371 if (layers.empty() || noVoteLayers == layers.size()) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200372 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
373 ALOGV("no layers with votes - choose %s", refreshRate.getName().c_str());
374 return refreshRate;
Steven Thomasbb374322020-04-28 22:47:16 -0700375 }
376
Ady Abraham8a82ba62020-01-17 12:43:17 -0800377 // Only if all layers want Min we should return Min
378 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700379 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700380 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800381 }
382
Ady Abraham8a82ba62020-01-17 12:43:17 -0800383 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800384 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700385 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800386
Steven Thomasf734df42020-04-13 21:09:28 -0700387 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800388 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800389 }
390
391 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700392 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700393 ftl::enum_string(layer.vote).c_str(), layer.weight,
rnlee3bd610662021-06-23 16:27:57 -0700394 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800395 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800396 continue;
397 }
398
Ady Abraham71c437d2020-01-31 15:56:57 -0800399 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800400
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800401 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100402 const bool isSeamlessSwitch =
403 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200404
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100405 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100406 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800407 formatLayerInfo(layer, weight).c_str(),
408 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100409 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200410 continue;
411 }
412
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100413 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
414 !layer.focused) {
415 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100416 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800417 formatLayerInfo(layer, weight).c_str(),
418 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100419 mCurrentRefreshRate->toString().c_str());
420 continue;
421 }
422
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100423 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100424 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100425 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100426 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
427 // disappeared.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200428 const bool isInPolicyForDefault = scores[i].refreshRate->getModeGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100429 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100430 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800431 scores[i].refreshRate->toString().c_str(),
432 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200433 continue;
434 }
435
Ady Abraham62a0be22020-12-08 16:54:10 -0800436 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
437 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700438 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800439 !(layer.focused &&
440 (layer.vote == LayerVoteType::ExplicitDefault ||
441 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700442 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700443 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700444 continue;
445 }
446
Ady Abraham62a0be22020-12-08 16:54:10 -0800447 const auto layerScore =
448 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200449 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800450 scores[i].refreshRate->getName().c_str(), layerScore);
451 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800452 }
453 }
454
Ady Abraham34702102020-02-10 14:12:05 -0800455 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
456 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
457 // or the lower otherwise.
458 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
459 ? getBestRefreshRate(scores.rbegin(), scores.rend())
460 : getBestRefreshRate(scores.begin(), scores.end());
461
Alec Mouri11232a22020-05-14 18:06:25 -0700462 if (primaryRangeIsSingleRate) {
463 // If we never scored any layers, then choose the rate from the primary
464 // range instead of picking a random score from the app range.
465 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800466 [](RefreshRateScore score) { return score.score == 0; })) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200467 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
468 ALOGV("layers not scored - choose %s", refreshRate.getName().c_str());
469 return refreshRate;
Alec Mouri11232a22020-05-14 18:06:25 -0700470 } else {
471 return *bestRefreshRate;
472 }
473 }
474
Steven Thomasf734df42020-04-13 21:09:28 -0700475 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
476 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
477 // vote we should not change it if we get a touch event. Only apply touch boost if it will
478 // actually increase the refresh rate over the normal selection.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200479 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
Alec Mouri11232a22020-05-14 18:06:25 -0700480
Ady Abraham5e4e9832021-06-14 13:40:56 -0700481 const bool touchBoostForExplicitExact = [&] {
482 if (mSupportsFrameRateOverride) {
483 // Enable touch boost if there are other layers besides exact
484 return explicitExact + noVoteLayers != layers.size();
485 } else {
486 // Enable touch boost if there are no exact layers
487 return explicitExact == 0;
488 }
489 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700490
491 using fps_approx_ops::operator<;
492
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800493 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700494 bestRefreshRate->getFps() < touchRefreshRate.getFps()) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700495 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700496 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700497 return touchRefreshRate;
498 }
499
Ady Abrahamde7156e2020-02-28 17:29:39 -0800500 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800501}
502
Ady Abraham62a0be22020-12-08 16:54:10 -0800503std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
504groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
505 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
506 for (const auto& layer : layers) {
507 auto iter = layersByUid.emplace(layer.ownerUid,
508 std::vector<const RefreshRateConfigs::LayerRequirement*>());
509 auto& layersWithSameUid = iter.first->second;
510 layersWithSameUid.push_back(&layer);
511 }
512
513 // Remove uids that can't have a frame rate override
514 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
515 const auto& layersWithSameUid = iter->second;
516 bool skipUid = false;
517 for (const auto& layer : layersWithSameUid) {
518 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
519 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
520 skipUid = true;
521 break;
522 }
523 }
524 if (skipUid) {
525 iter = layersByUid.erase(iter);
526 } else {
527 ++iter;
528 }
529 }
530
531 return layersByUid;
532}
533
534std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
535 const AllRefreshRatesMapType& refreshRates) {
536 std::vector<RefreshRateScore> scores;
537 scores.reserve(refreshRates.size());
538 for (const auto& [ignored, refreshRate] : refreshRates) {
539 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
540 }
541 std::sort(scores.begin(), scores.end(),
542 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
543 return scores;
544}
545
546RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700547 const std::vector<LayerRequirement>& layers, Fps displayFrameRate,
548 GlobalSignals globalSignals) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800549 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800550 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800551
Ady Abraham64c2fc02020-12-29 12:07:50 -0800552 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800553 std::lock_guard lock(mLock);
554 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
555 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
556 groupLayersByUid(layers);
557 UidToFrameRateOverride frameRateOverrides;
558 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800559 // Layers with ExplicitExactOrMultiple expect touch boost
560 const bool hasExplicitExactOrMultiple =
561 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
562 [](const auto& layer) {
563 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
564 });
565
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700566 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800567 continue;
568 }
569
Ady Abraham62a0be22020-12-08 16:54:10 -0800570 for (auto& score : scores) {
571 score.score = 0;
572 }
573
574 for (const auto& layer : layersWithSameUid) {
575 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
576 continue;
577 }
578
579 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800580 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
581 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800582 for (RefreshRateScore& score : scores) {
583 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
584 /*isSeamlessSwitch*/ true);
585 score.score += layer->weight * layerScore;
586 }
587 }
588
589 // We just care about the refresh rates which are a divider of the
590 // display refresh rate
591 auto iter =
592 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
593 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
594 });
595 scores.erase(iter, scores.end());
596
597 // If we never scored any layers, we don't have a preferred frame rate
598 if (std::all_of(scores.begin(), scores.end(),
599 [](const RefreshRateScore& score) { return score.score == 0; })) {
600 continue;
601 }
602
603 // Now that we scored all the refresh rates we need to pick the one that got the highest
604 // score.
605 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700606 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800607 }
608
609 return frameRateOverrides;
610}
611
Ady Abraham34702102020-02-10 14:12:05 -0800612template <typename Iter>
613const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200614 constexpr auto kEpsilon = 0.0001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800615 const RefreshRate* bestRefreshRate = begin->refreshRate;
616 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800617 for (auto i = begin; i != end; ++i) {
618 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100619 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800620
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100621 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800622
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200623 if (score > max * (1 + kEpsilon)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800624 max = score;
625 bestRefreshRate = refreshRate;
626 }
627 }
628
Ady Abraham34702102020-02-10 14:12:05 -0800629 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800630}
631
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100632std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100633 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800634 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100635
636 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
637 : *mCurrentRefreshRate;
638 const auto& min = *mMinSupportedRefreshRate;
639
640 if (current != min) {
641 const auto& refreshRate = timerExpired ? min : current;
642 return refreshRate.getFps();
643 }
644
645 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700646}
647
648const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200649 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100650 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200651 return *refreshRate;
652 }
653 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100654 ALOGE("Can't find min refresh rate by policy with the same mode group"
655 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200656 mCurrentRefreshRate->toString().c_str());
657 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700658 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800659}
660
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100661RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800662 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700663 return getMaxRefreshRateByPolicyLocked();
664}
665
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200666const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200667 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
668 const auto& refreshRate = (**it);
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200669 if (anchorGroup == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200670 return refreshRate;
671 }
672 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100673 ALOGE("Can't find max refresh rate by policy with the same mode group"
674 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200675 mCurrentRefreshRate->toString().c_str());
676 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700677 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800678}
679
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100680RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800681 std::lock_guard lock(mLock);
682 return *mCurrentRefreshRate;
683}
684
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100685RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800686 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800687 return getCurrentRefreshRateByPolicyLocked();
688}
689
690const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700691 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
692 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800693 return *mCurrentRefreshRate;
694 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100695 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800696}
697
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100698void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800699 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200700
701 // Invalidate the cached invocation to getBestRefreshRate. This forces
702 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
703 lastBestRefreshRateInvocation.reset();
704
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100705 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800706}
707
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100708RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
rnlee3bd610662021-06-23 16:27:57 -0700709 Config config)
710 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700711 initializeIdleTimer();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100712 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100713}
714
Ady Abraham9a2ea342021-09-03 17:32:34 -0700715void RefreshRateConfigs::initializeIdleTimer() {
Ady Abraham6d885932021-09-03 18:05:48 -0700716 if (mConfig.idleTimerTimeoutMs > 0) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700717 const auto getCallback = [this]() -> std::optional<IdleTimerCallbacks::Callbacks> {
718 std::scoped_lock lock(mIdleTimerCallbacksMutex);
719 if (!mIdleTimerCallbacks.has_value()) return {};
Ady Abraham6d885932021-09-03 18:05:48 -0700720 return mConfig.supportKernelIdleTimer ? mIdleTimerCallbacks->kernel
721 : mIdleTimerCallbacks->platform;
Ady Abraham9a2ea342021-09-03 17:32:34 -0700722 };
723
724 mIdleTimer.emplace(
Ady Abraham6d885932021-09-03 18:05:48 -0700725 "IdleTimer", std::chrono::milliseconds(mConfig.idleTimerTimeoutMs),
Ady Abraham9a2ea342021-09-03 17:32:34 -0700726 [getCallback] {
727 if (const auto callback = getCallback()) callback->onReset();
728 },
729 [getCallback] {
730 if (const auto callback = getCallback()) callback->onExpired();
731 });
Ady Abraham9a2ea342021-09-03 17:32:34 -0700732 }
733}
734
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100735void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
736 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100737 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200738
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100739 // The current mode should be supported
740 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
741 return mode->getId() == currentModeId;
742 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700743
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200744 // Invalidate the cached invocation to getBestRefreshRate. This forces
745 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
746 lastBestRefreshRateInvocation.reset();
747
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100748 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100749 for (const auto& mode : modes) {
750 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100751 mRefreshRates.emplace(modeId,
Ady Abraham6b7ad652021-06-23 17:34:57 -0700752 std::make_unique<RefreshRate>(mode, RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100753 if (modeId == currentModeId) {
754 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700755 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800756 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700757
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100758 std::vector<const RefreshRate*> sortedModes;
759 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100760 // Reset the policy because the old one may no longer be valid.
761 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100762 mDisplayManagerPolicy.defaultMode = currentModeId;
763 mMinSupportedRefreshRate = sortedModes.front();
764 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800765
766 mSupportsFrameRateOverride = false;
rnlee3bd610662021-06-23 16:27:57 -0700767 if (mConfig.enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100768 for (const auto& mode1 : sortedModes) {
769 for (const auto& mode2 : sortedModes) {
770 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800771 mSupportsFrameRateOverride = true;
772 break;
773 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800774 }
775 }
776 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800777
Ady Abrahamabc27602020-04-08 17:20:29 -0700778 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800779}
780
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100781bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100782 // defaultMode must be a valid mode, and within the given refresh rate range.
783 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700784 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100785 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700786 return false;
787 }
788 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700789 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100790 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700791 return false;
792 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700793
794 using namespace fps_approx_ops;
795 return policy.appRequestRange.min <= policy.primaryRange.min &&
796 policy.appRequestRange.max >= policy.primaryRange.max;
Steven Thomasd4071902020-03-24 16:02:53 -0700797}
798
799status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800800 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100801 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100802 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100803 return BAD_VALUE;
804 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200805 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700806 Policy previousPolicy = *getCurrentPolicyLocked();
807 mDisplayManagerPolicy = policy;
808 if (*getCurrentPolicyLocked() == previousPolicy) {
809 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100810 }
Ady Abraham2139f732019-11-13 18:56:40 -0800811 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100812 return NO_ERROR;
813}
814
Steven Thomasd4071902020-03-24 16:02:53 -0700815status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100816 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100817 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700818 return BAD_VALUE;
819 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200820 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700821 Policy previousPolicy = *getCurrentPolicyLocked();
822 mOverridePolicy = policy;
823 if (*getCurrentPolicyLocked() == previousPolicy) {
824 return CURRENT_POLICY_UNCHANGED;
825 }
826 constructAvailableRefreshRates();
827 return NO_ERROR;
828}
829
830const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
831 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
832}
833
834RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
835 std::lock_guard lock(mLock);
836 return *getCurrentPolicyLocked();
837}
838
839RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
840 std::lock_guard lock(mLock);
841 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100842}
843
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100844bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100845 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700846 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700847 if (refreshRate->getModeId() == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100848 return true;
849 }
850 }
851 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800852}
853
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100854void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800855 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
856 std::vector<const RefreshRate*>* outRefreshRates) {
857 outRefreshRates->clear();
858 outRefreshRates->reserve(mRefreshRates.size());
859 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800860 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100861 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Ady Abraham6b7ad652021-06-23 17:34:57 -0700862 refreshRate->getModeId().value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800863 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800864 }
865 }
866
867 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
868 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100869 if (refreshRate1->mode->getVsyncPeriod() !=
870 refreshRate2->mode->getVsyncPeriod()) {
871 return refreshRate1->mode->getVsyncPeriod() >
872 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700873 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100874 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700875 }
Ady Abraham2139f732019-11-13 18:56:40 -0800876 });
877}
878
879void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100880 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700881 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100882 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100883 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700884
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100885 auto filterRefreshRates =
886 [&](Fps min, Fps max, const char* listName,
887 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
888 getSortedRefreshRateListLocked(
889 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
890 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800891
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100892 return mode->getHeight() == defaultMode->getHeight() &&
893 mode->getWidth() == defaultMode->getWidth() &&
894 mode->getDpiX() == defaultMode->getDpiX() &&
895 mode->getDpiY() == defaultMode->getDpiY() &&
896 (policy->allowGroupSwitching ||
897 mode->getGroup() == defaultMode->getGroup()) &&
898 refreshRate.inPolicy(min, max);
899 },
900 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800901
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100902 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
903 "No matching modes for %s range: min=%s max=%s", listName,
904 to_string(min).c_str(), to_string(max).c_str());
905 auto stringifyRefreshRates = [&]() -> std::string {
906 std::string str;
907 for (auto refreshRate : *outRefreshRates) {
908 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
909 }
910 return str;
911 };
912 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
913 };
Steven Thomasf734df42020-04-13 21:09:28 -0700914
915 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
916 &mPrimaryRefreshRates);
917 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
918 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800919}
920
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100921Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700922 using namespace fps_approx_ops;
923
924 if (frameRate <= mKnownFrameRates.front()) {
925 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700926 }
927
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700928 if (frameRate >= mKnownFrameRates.back()) {
929 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700930 }
931
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100932 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700933 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700934
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700935 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
936 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700937 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
938}
939
Ana Krulecb9afd792020-06-11 13:16:15 -0700940RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
941 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100942 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700943 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
944 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
TreeHugger Robot758ab612021-06-22 19:17:29 +0000945 const auto& currentPolicy = getCurrentPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700946
947 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
948 // the min allowed refresh rate is higher than the device min, we do not want to enable the
949 // timer.
950 if (deviceMin < minByPolicy) {
951 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
952 }
953 if (minByPolicy == maxByPolicy) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000954 // when min primary range in display manager policy is below device min turn on the timer.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700955 if (isApproxLess(currentPolicy->primaryRange.min, deviceMin.getFps())) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000956 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700957 }
958 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
959 }
960 // Turn on the timer in all other cases.
961 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
962}
963
Ady Abraham62a0be22020-12-08 16:54:10 -0800964int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700965 // This calculation needs to be in sync with the java code
966 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200967
968 // The threshold must be smaller than 0.001 in order to differentiate
969 // between the fractional pairs (e.g. 59.94 and 60).
970 constexpr float kThreshold = 0.0009f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800971 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700972 const auto numPeriodsRounded = std::round(numPeriods);
973 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800974 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700975 }
976
Ady Abraham62f216c2020-10-13 19:07:23 -0700977 return static_cast<int>(numPeriodsRounded);
978}
979
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200980bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700981 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200982 return isFractionalPairOrMultiple(bigger, smaller);
983 }
984
985 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
986 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700987 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
988 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200989}
990
Marin Shalamanovba421a82020-11-10 21:49:26 +0100991void RefreshRateConfigs::dump(std::string& result) const {
992 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100993 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100994 mDisplayManagerPolicy.toString().c_str());
995 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
996 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100997 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100998 currentPolicy.toString().c_str());
999 }
1000
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001001 auto mode = mCurrentRefreshRate->mode;
1002 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +01001003
1004 result.append("Refresh rates:\n");
1005 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001006 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +01001007 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
1008 }
1009
Ady Abraham64c2fc02020-12-29 12:07:50 -08001010 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
1011 mSupportsFrameRateOverride ? "yes" : "no");
Ady Abraham6d885932021-09-03 18:05:48 -07001012 base::StringAppendF(&result, "Idle timer: (%s) %s\n",
1013 mConfig.supportKernelIdleTimer ? "kernel" : "platform",
Ady Abraham9a2ea342021-09-03 17:32:34 -07001014 mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Marin Shalamanovba421a82020-11-10 21:49:26 +01001015 result.append("\n");
1016}
1017
Ady Abraham2139f732019-11-13 18:56:40 -08001018} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001019
1020// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001021#pragma clang diagnostic pop // ignored "-Wextra"