blob: 0d17b0ca94274f0f1ce9239c359df688e690584d [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 Abrahamb4b1e0a2019-11-20 18:25:35 -080024#include "RefreshRateConfigs.h"
Ady Abraham9a2ea342021-09-03 17:32:34 -070025#include <android-base/properties.h>
Ady Abraham8a82ba62020-01-17 12:43:17 -080026#include <android-base/stringprintf.h>
27#include <utils/Trace.h>
28#include <chrono>
29#include <cmath>
Ady Abraham4899ff82021-01-06 13:53:29 -080030#include "../SurfaceFlingerProperties.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080031
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080032#undef LOG_TAG
33#define LOG_TAG "RefreshRateConfigs"
34
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080035namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010036namespace {
37std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010038 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010039 RefreshRateConfigs::layerVoteTypeString(layer.vote).c_str(), weight,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010040 toString(layer.seamlessness).c_str(),
41 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010042}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010043
Marin Shalamanova7fe3042021-01-29 21:02:08 +010044std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070045 std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010046 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010047
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070048 // Add all supported refresh rates.
Marin Shalamanova7fe3042021-01-29 21:02:08 +010049 for (const auto& mode : modes) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070050 knownFrameRates.push_back(Fps::fromPeriodNsecs(mode->getVsyncPeriod()));
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010051 }
52
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070053 // Sort and remove duplicates.
54 std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010055 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070056 isApproxEqual),
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010057 knownFrameRates.end());
58 return knownFrameRates;
59}
60
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010061} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080062
63using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080064using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080065
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070066bool RefreshRate::inPolicy(Fps minRefreshRate, Fps maxRefreshRate) const {
67 using fps_approx_ops::operator<=;
68 return minRefreshRate <= getFps() && getFps() <= maxRefreshRate;
69}
70
Marin Shalamanov46084422020-10-13 12:33:42 +020071std::string RefreshRate::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010072 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010073 getModeId().value(), mode->getHwcId(), getFps().getValue(),
74 mode->getWidth(), mode->getHeight(), getModeGroup());
Marin Shalamanov46084422020-10-13 12:33:42 +020075}
76
Ady Abrahama6b676e2020-05-27 14:29:09 -070077std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
78 switch (vote) {
79 case LayerVoteType::NoVote:
80 return "NoVote";
81 case LayerVoteType::Min:
82 return "Min";
83 case LayerVoteType::Max:
84 return "Max";
85 case LayerVoteType::Heuristic:
86 return "Heuristic";
87 case LayerVoteType::ExplicitDefault:
88 return "ExplicitDefault";
89 case LayerVoteType::ExplicitExactOrMultiple:
90 return "ExplicitExactOrMultiple";
Ady Abrahamdd5bfa92021-01-07 17:56:08 -080091 case LayerVoteType::ExplicitExact:
92 return "ExplicitExact";
Ady Abrahama6b676e2020-05-27 14:29:09 -070093 }
94}
95
Marin Shalamanovb6674e72020-11-06 13:05:57 +010096std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010097 return base::StringPrintf("default mode ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010098 ", primary range: %s, app request range: %s",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010099 defaultMode.value(), allowGroupSwitching,
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100100 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +0200101}
102
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800103std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
104 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800105 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
106 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
107 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
108 quotient++;
109 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800110 }
111
Ady Abraham62a0be22020-12-08 16:54:10 -0800112 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800113}
114
rnlee3bd610662021-06-23 16:27:57 -0700115bool RefreshRateConfigs::isVoteAllowed(const LayerRequirement& layer,
116 const RefreshRate& refreshRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700117 using namespace fps_approx_ops;
118
rnlee3bd610662021-06-23 16:27:57 -0700119 switch (layer.vote) {
120 case LayerVoteType::ExplicitExactOrMultiple:
121 case LayerVoteType::Heuristic:
122 if (mConfig.frameRateMultipleThreshold != 0 &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700123 refreshRate.getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold) &&
124 layer.desiredRefreshRate < Fps::fromValue(mConfig.frameRateMultipleThreshold / 2)) {
rnlee3bd610662021-06-23 16:27:57 -0700125 // Don't vote high refresh rates past the threshold for layers with a low desired
126 // refresh rate. For example, desired 24 fps with 120 Hz threshold means no vote for
127 // 120 Hz, but desired 60 fps should have a vote.
128 return false;
129 }
130 break;
131 case LayerVoteType::ExplicitDefault:
132 case LayerVoteType::ExplicitExact:
133 case LayerVoteType::Max:
134 case LayerVoteType::Min:
135 case LayerVoteType::NoVote:
136 break;
137 }
138 return true;
139}
140
Ady Abraham05243be2021-09-16 15:58:52 -0700141float RefreshRateConfigs::calculateNonExactMatchingLayerScoreLocked(
142 const LayerRequirement& layer, const RefreshRate& refreshRate) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200143 constexpr float kScoreForFractionalPairs = .8f;
144
Ady Abraham62a0be22020-12-08 16:54:10 -0800145 const auto displayPeriod = refreshRate.getVsyncPeriod();
146 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
147 if (layer.vote == LayerVoteType::ExplicitDefault) {
148 // Find the actual rate the layer will render, assuming
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200149 // that layerPeriod is the minimal period to render a frame.
150 // For example if layerPeriod is 20ms and displayPeriod is 16ms,
151 // then the actualLayerPeriod will be 32ms, because it is the
152 // smallest multiple of the display period which is >= layerPeriod.
Ady Abraham62a0be22020-12-08 16:54:10 -0800153 auto actualLayerPeriod = displayPeriod;
154 int multiplier = 1;
155 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
156 multiplier++;
157 actualLayerPeriod = displayPeriod * multiplier;
158 }
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200159
160 // Because of the threshold we used above it's possible that score is slightly
161 // above 1.
Ady Abraham62a0be22020-12-08 16:54:10 -0800162 return std::min(1.0f,
163 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
164 }
165
166 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
167 layer.vote == LayerVoteType::Heuristic) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200168 if (isFractionalPairOrMultiple(refreshRate.getFps(), layer.desiredRefreshRate)) {
Ady Abraham05243be2021-09-16 15:58:52 -0700169 return kScoreForFractionalPairs;
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200170 }
171
Ady Abraham62a0be22020-12-08 16:54:10 -0800172 // Calculate how many display vsyncs we need to present a single frame for this
173 // layer
174 const auto [displayFramesQuotient, displayFramesRemainder] =
175 getDisplayFrames(layerPeriod, displayPeriod);
176 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
177 if (displayFramesRemainder == 0) {
178 // Layer desired refresh rate matches the display rate.
Ady Abraham05243be2021-09-16 15:58:52 -0700179 return 1.0f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800180 }
181
182 if (displayFramesQuotient == 0) {
183 // Layer desired refresh rate is higher than the display rate.
184 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
185 (1.0f / (MAX_FRAMES_TO_FIT + 1));
186 }
187
188 // Layer desired refresh rate is lower than the display rate. Check how well it fits
189 // the cadence.
190 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
191 int iter = 2;
192 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
193 diff = diff - (displayPeriod - diff);
194 iter++;
195 }
196
Ady Abraham05243be2021-09-16 15:58:52 -0700197 return (1.0f / iter);
198 }
199
200 return 0;
201}
202
203float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
204 const RefreshRate& refreshRate,
205 bool isSeamlessSwitch) const {
206 if (!isVoteAllowed(layer, refreshRate)) {
207 return 0;
208 }
209
210 // Slightly prefer seamless switches.
211 constexpr float kSeamedSwitchPenalty = 0.95f;
212 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
213
214 // If the layer wants Max, give higher score to the higher refresh rate
215 if (layer.vote == LayerVoteType::Max) {
216 const auto ratio = refreshRate.getFps().getValue() /
217 mAppRequestRefreshRates.back()->getFps().getValue();
218 // use ratio^2 to get a lower score the more we get further from peak
219 return ratio * ratio;
Ady Abraham62a0be22020-12-08 16:54:10 -0800220 }
221
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800222 if (layer.vote == LayerVoteType::ExplicitExact) {
223 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
224 if (mSupportsFrameRateOverride) {
225 // Since we support frame rate override, allow refresh rates which are
226 // multiples of the layer's request, as those apps would be throttled
227 // down to run at the desired refresh rate.
228 return divider > 0;
229 }
230
231 return divider == 1;
232 }
233
Ady Abraham05243be2021-09-16 15:58:52 -0700234 // If the layer frame rate is a divider of the refresh rate it should score
235 // the highest score.
236 if (getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate) > 0) {
237 return 1.0f * seamlessness;
238 }
239
240 // The layer frame rate is not a divider of the refresh rate,
241 // there is a small penalty attached to the score to favor the frame rates
242 // the exactly matches the display refresh rate or a multiple.
243 constexpr float kNonExactMatchingPenalty = 0.99f;
244 return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
245 kNonExactMatchingPenalty;
Ady Abraham62a0be22020-12-08 16:54:10 -0800246}
247
248struct RefreshRateScore {
249 const RefreshRate* refreshRate;
250 float score;
251};
252
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100253RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700254 GlobalSignals globalSignals,
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100255 GlobalSignals* outSignalsConsidered) const {
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200256 std::lock_guard lock(mLock);
257
258 if (auto cached = getCachedBestRefreshRate(layers, globalSignals, outSignalsConsidered)) {
259 return *cached;
260 }
261
262 GlobalSignals signalsConsidered;
263 RefreshRate result = getBestRefreshRateLocked(layers, globalSignals, &signalsConsidered);
264 lastBestRefreshRateInvocation.emplace(
265 GetBestRefreshRateInvocation{.layerRequirements = layers,
266 .globalSignals = globalSignals,
267 .outSignalsConsidered = signalsConsidered,
268 .resultingBestRefreshRate = result});
269 if (outSignalsConsidered) {
270 *outSignalsConsidered = signalsConsidered;
271 }
272 return result;
273}
274
275std::optional<RefreshRate> RefreshRateConfigs::getCachedBestRefreshRate(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700276 const std::vector<LayerRequirement>& layers, GlobalSignals globalSignals,
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200277 GlobalSignals* outSignalsConsidered) const {
278 const bool sameAsLastCall = lastBestRefreshRateInvocation &&
279 lastBestRefreshRateInvocation->layerRequirements == layers &&
280 lastBestRefreshRateInvocation->globalSignals == globalSignals;
281
282 if (sameAsLastCall) {
283 if (outSignalsConsidered) {
284 *outSignalsConsidered = lastBestRefreshRateInvocation->outSignalsConsidered;
285 }
286 return lastBestRefreshRateInvocation->resultingBestRefreshRate;
287 }
288
289 return {};
290}
291
292RefreshRate RefreshRateConfigs::getBestRefreshRateLocked(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700293 const std::vector<LayerRequirement>& layers, GlobalSignals globalSignals,
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200294 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800295 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200296 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800297
Ady Abrahamdfd62162020-06-10 16:11:56 -0700298 if (outSignalsConsidered) *outSignalsConsidered = {};
299 const auto setTouchConsidered = [&] {
300 if (outSignalsConsidered) {
301 outSignalsConsidered->touch = true;
302 }
303 };
304
305 const auto setIdleConsidered = [&] {
306 if (outSignalsConsidered) {
307 outSignalsConsidered->idle = true;
308 }
309 };
310
Ady Abraham8a82ba62020-01-17 12:43:17 -0800311 int noVoteLayers = 0;
312 int minVoteLayers = 0;
313 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800314 int explicitDefaultVoteLayers = 0;
315 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800316 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800317 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100318 int seamedFocusedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800319 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800320 switch (layer.vote) {
321 case LayerVoteType::NoVote:
322 noVoteLayers++;
323 break;
324 case LayerVoteType::Min:
325 minVoteLayers++;
326 break;
327 case LayerVoteType::Max:
328 maxVoteLayers++;
329 break;
330 case LayerVoteType::ExplicitDefault:
331 explicitDefaultVoteLayers++;
332 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
333 break;
334 case LayerVoteType::ExplicitExactOrMultiple:
335 explicitExactOrMultipleVoteLayers++;
336 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
337 break;
338 case LayerVoteType::ExplicitExact:
339 explicitExact++;
340 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
341 break;
342 case LayerVoteType::Heuristic:
343 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800344 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200345
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100346 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
347 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200348 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800349 }
350
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800351 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
352 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700353
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200354 const Policy* policy = getCurrentPolicyLocked();
355 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
356 // If the default mode group is different from the group of current mode,
357 // this means a layer requesting a seamed mode switch just disappeared and
358 // we should switch back to the default group.
359 // However if a seamed layer is still present we anchor around the group
360 // of the current mode, in order to prevent unnecessary seamed mode switches
361 // (e.g. when pausing a video playback).
362 const auto anchorGroup = seamedFocusedLayers > 0 ? mCurrentRefreshRate->getModeGroup()
363 : defaultMode->getModeGroup();
364
Steven Thomasf734df42020-04-13 21:09:28 -0700365 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
366 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700367 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700368 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700369 setTouchConsidered();
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200370 return getMaxRefreshRateByPolicyLocked(anchorGroup);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800371 }
372
Alec Mouri11232a22020-05-14 18:06:25 -0700373 // If the primary range consists of a single refresh rate then we can only
374 // move out the of range if layers explicitly request a different refresh
375 // rate.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100376 const bool primaryRangeIsSingleRate =
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700377 isApproxEqual(policy->primaryRange.min, policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700378
Ady Abrahamdfd62162020-06-10 16:11:56 -0700379 if (!globalSignals.touch && globalSignals.idle &&
380 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700381 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700382 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700383 return getMinRefreshRateByPolicyLocked();
384 }
385
Steven Thomasdebafed2020-05-18 17:30:35 -0700386 if (layers.empty() || noVoteLayers == layers.size()) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200387 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
388 ALOGV("no layers with votes - choose %s", refreshRate.getName().c_str());
389 return refreshRate;
Steven Thomasbb374322020-04-28 22:47:16 -0700390 }
391
Ady Abraham8a82ba62020-01-17 12:43:17 -0800392 // Only if all layers want Min we should return Min
393 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700394 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700395 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800396 }
397
Ady Abraham8a82ba62020-01-17 12:43:17 -0800398 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800399 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700400 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800401
Steven Thomasf734df42020-04-13 21:09:28 -0700402 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800403 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800404 }
405
406 for (const auto& layer : layers) {
rnlee3bd610662021-06-23 16:27:57 -0700407 ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
408 layerVoteTypeString(layer.vote).c_str(), layer.weight,
409 layer.desiredRefreshRate.getValue());
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800410 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800411 continue;
412 }
413
Ady Abraham71c437d2020-01-31 15:56:57 -0800414 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800415
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800416 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100417 const bool isSeamlessSwitch =
418 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200419
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100420 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100421 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800422 formatLayerInfo(layer, weight).c_str(),
423 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100424 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200425 continue;
426 }
427
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100428 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
429 !layer.focused) {
430 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100431 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800432 formatLayerInfo(layer, weight).c_str(),
433 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100434 mCurrentRefreshRate->toString().c_str());
435 continue;
436 }
437
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100438 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100439 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100440 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100441 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
442 // disappeared.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200443 const bool isInPolicyForDefault = scores[i].refreshRate->getModeGroup() == anchorGroup;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100444 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100445 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800446 scores[i].refreshRate->toString().c_str(),
447 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200448 continue;
449 }
450
Ady Abraham62a0be22020-12-08 16:54:10 -0800451 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
452 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700453 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800454 !(layer.focused &&
455 (layer.vote == LayerVoteType::ExplicitDefault ||
456 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700457 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700458 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700459 continue;
460 }
461
Ady Abraham62a0be22020-12-08 16:54:10 -0800462 const auto layerScore =
463 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200464 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800465 scores[i].refreshRate->getName().c_str(), layerScore);
466 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800467 }
468 }
469
Ady Abraham34702102020-02-10 14:12:05 -0800470 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
471 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
472 // or the lower otherwise.
473 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
474 ? getBestRefreshRate(scores.rbegin(), scores.rend())
475 : getBestRefreshRate(scores.begin(), scores.end());
476
Alec Mouri11232a22020-05-14 18:06:25 -0700477 if (primaryRangeIsSingleRate) {
478 // If we never scored any layers, then choose the rate from the primary
479 // range instead of picking a random score from the app range.
480 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800481 [](RefreshRateScore score) { return score.score == 0; })) {
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200482 const auto& refreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
483 ALOGV("layers not scored - choose %s", refreshRate.getName().c_str());
484 return refreshRate;
Alec Mouri11232a22020-05-14 18:06:25 -0700485 } else {
486 return *bestRefreshRate;
487 }
488 }
489
Steven Thomasf734df42020-04-13 21:09:28 -0700490 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
491 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
492 // vote we should not change it if we get a touch event. Only apply touch boost if it will
493 // actually increase the refresh rate over the normal selection.
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200494 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
Alec Mouri11232a22020-05-14 18:06:25 -0700495
Ady Abraham5e4e9832021-06-14 13:40:56 -0700496 const bool touchBoostForExplicitExact = [&] {
497 if (mSupportsFrameRateOverride) {
498 // Enable touch boost if there are other layers besides exact
499 return explicitExact + noVoteLayers != layers.size();
500 } else {
501 // Enable touch boost if there are no exact layers
502 return explicitExact == 0;
503 }
504 }();
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700505
506 using fps_approx_ops::operator<;
507
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800508 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700509 bestRefreshRate->getFps() < touchRefreshRate.getFps()) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700510 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700511 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700512 return touchRefreshRate;
513 }
514
Ady Abrahamde7156e2020-02-28 17:29:39 -0800515 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800516}
517
Ady Abraham62a0be22020-12-08 16:54:10 -0800518std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
519groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
520 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
521 for (const auto& layer : layers) {
522 auto iter = layersByUid.emplace(layer.ownerUid,
523 std::vector<const RefreshRateConfigs::LayerRequirement*>());
524 auto& layersWithSameUid = iter.first->second;
525 layersWithSameUid.push_back(&layer);
526 }
527
528 // Remove uids that can't have a frame rate override
529 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
530 const auto& layersWithSameUid = iter->second;
531 bool skipUid = false;
532 for (const auto& layer : layersWithSameUid) {
533 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
534 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
535 skipUid = true;
536 break;
537 }
538 }
539 if (skipUid) {
540 iter = layersByUid.erase(iter);
541 } else {
542 ++iter;
543 }
544 }
545
546 return layersByUid;
547}
548
549std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
550 const AllRefreshRatesMapType& refreshRates) {
551 std::vector<RefreshRateScore> scores;
552 scores.reserve(refreshRates.size());
553 for (const auto& [ignored, refreshRate] : refreshRates) {
554 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
555 }
556 std::sort(scores.begin(), scores.end(),
557 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
558 return scores;
559}
560
561RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700562 const std::vector<LayerRequirement>& layers, Fps displayFrameRate,
563 GlobalSignals globalSignals) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800564 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800565 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800566
Ady Abraham64c2fc02020-12-29 12:07:50 -0800567 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800568 std::lock_guard lock(mLock);
569 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
570 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
571 groupLayersByUid(layers);
572 UidToFrameRateOverride frameRateOverrides;
573 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800574 // Layers with ExplicitExactOrMultiple expect touch boost
575 const bool hasExplicitExactOrMultiple =
576 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
577 [](const auto& layer) {
578 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
579 });
580
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700581 if (globalSignals.touch && hasExplicitExactOrMultiple) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800582 continue;
583 }
584
Ady Abraham62a0be22020-12-08 16:54:10 -0800585 for (auto& score : scores) {
586 score.score = 0;
587 }
588
589 for (const auto& layer : layersWithSameUid) {
590 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
591 continue;
592 }
593
594 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800595 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
596 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800597 for (RefreshRateScore& score : scores) {
598 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
599 /*isSeamlessSwitch*/ true);
600 score.score += layer->weight * layerScore;
601 }
602 }
603
604 // We just care about the refresh rates which are a divider of the
605 // display refresh rate
606 auto iter =
607 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
608 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
609 });
610 scores.erase(iter, scores.end());
611
612 // If we never scored any layers, we don't have a preferred frame rate
613 if (std::all_of(scores.begin(), scores.end(),
614 [](const RefreshRateScore& score) { return score.score == 0; })) {
615 continue;
616 }
617
618 // Now that we scored all the refresh rates we need to pick the one that got the highest
619 // score.
620 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700621 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800622 }
623
624 return frameRateOverrides;
625}
626
Ady Abraham34702102020-02-10 14:12:05 -0800627template <typename Iter>
628const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200629 constexpr auto kEpsilon = 0.0001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800630 const RefreshRate* bestRefreshRate = begin->refreshRate;
631 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800632 for (auto i = begin; i != end; ++i) {
633 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100634 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800635
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100636 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800637
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200638 if (score > max * (1 + kEpsilon)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800639 max = score;
640 bestRefreshRate = refreshRate;
641 }
642 }
643
Ady Abraham34702102020-02-10 14:12:05 -0800644 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800645}
646
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100647std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100648 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800649 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100650
651 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
652 : *mCurrentRefreshRate;
653 const auto& min = *mMinSupportedRefreshRate;
654
655 if (current != min) {
656 const auto& refreshRate = timerExpired ? min : current;
657 return refreshRate.getFps();
658 }
659
660 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700661}
662
663const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200664 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100665 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200666 return *refreshRate;
667 }
668 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100669 ALOGE("Can't find min refresh rate by policy with the same mode group"
670 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200671 mCurrentRefreshRate->toString().c_str());
672 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700673 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800674}
675
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100676RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800677 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700678 return getMaxRefreshRateByPolicyLocked();
679}
680
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200681const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200682 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
683 const auto& refreshRate = (**it);
Marin Shalamanov8cd8a992021-09-14 23:22:49 +0200684 if (anchorGroup == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200685 return refreshRate;
686 }
687 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100688 ALOGE("Can't find max refresh rate by policy with the same mode group"
689 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200690 mCurrentRefreshRate->toString().c_str());
691 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700692 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800693}
694
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100695RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800696 std::lock_guard lock(mLock);
697 return *mCurrentRefreshRate;
698}
699
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100700RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800701 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800702 return getCurrentRefreshRateByPolicyLocked();
703}
704
705const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700706 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
707 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800708 return *mCurrentRefreshRate;
709 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100710 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800711}
712
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100713void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800714 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200715
716 // Invalidate the cached invocation to getBestRefreshRate. This forces
717 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
718 lastBestRefreshRateInvocation.reset();
719
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100720 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800721}
722
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100723RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
rnlee3bd610662021-06-23 16:27:57 -0700724 Config config)
725 : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700726 initializeIdleTimer();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100727 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100728}
729
Ady Abraham9a2ea342021-09-03 17:32:34 -0700730void RefreshRateConfigs::initializeIdleTimer() {
Ady Abraham6d885932021-09-03 18:05:48 -0700731 if (mConfig.idleTimerTimeoutMs > 0) {
Ady Abraham9a2ea342021-09-03 17:32:34 -0700732 const auto getCallback = [this]() -> std::optional<IdleTimerCallbacks::Callbacks> {
733 std::scoped_lock lock(mIdleTimerCallbacksMutex);
734 if (!mIdleTimerCallbacks.has_value()) return {};
Ady Abraham6d885932021-09-03 18:05:48 -0700735 return mConfig.supportKernelIdleTimer ? mIdleTimerCallbacks->kernel
736 : mIdleTimerCallbacks->platform;
Ady Abraham9a2ea342021-09-03 17:32:34 -0700737 };
738
739 mIdleTimer.emplace(
Ady Abraham6d885932021-09-03 18:05:48 -0700740 "IdleTimer", std::chrono::milliseconds(mConfig.idleTimerTimeoutMs),
Ady Abraham9a2ea342021-09-03 17:32:34 -0700741 [getCallback] {
742 if (const auto callback = getCallback()) callback->onReset();
743 },
744 [getCallback] {
745 if (const auto callback = getCallback()) callback->onExpired();
746 });
Ady Abraham9a2ea342021-09-03 17:32:34 -0700747 }
748}
749
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100750void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
751 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100752 std::lock_guard lock(mLock);
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200753
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100754 // The current mode should be supported
755 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
756 return mode->getId() == currentModeId;
757 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700758
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200759 // Invalidate the cached invocation to getBestRefreshRate. This forces
760 // the refresh rate to be recomputed on the next call to getBestRefreshRate.
761 lastBestRefreshRateInvocation.reset();
762
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100763 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100764 for (const auto& mode : modes) {
765 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100766 mRefreshRates.emplace(modeId,
Ady Abraham6b7ad652021-06-23 17:34:57 -0700767 std::make_unique<RefreshRate>(mode, RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100768 if (modeId == currentModeId) {
769 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700770 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800771 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700772
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100773 std::vector<const RefreshRate*> sortedModes;
774 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100775 // Reset the policy because the old one may no longer be valid.
776 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100777 mDisplayManagerPolicy.defaultMode = currentModeId;
778 mMinSupportedRefreshRate = sortedModes.front();
779 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800780
781 mSupportsFrameRateOverride = false;
rnlee3bd610662021-06-23 16:27:57 -0700782 if (mConfig.enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100783 for (const auto& mode1 : sortedModes) {
784 for (const auto& mode2 : sortedModes) {
785 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800786 mSupportsFrameRateOverride = true;
787 break;
788 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800789 }
790 }
791 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800792
Ady Abrahamabc27602020-04-08 17:20:29 -0700793 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800794}
795
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100796bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100797 // defaultMode must be a valid mode, and within the given refresh rate range.
798 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700799 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100800 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700801 return false;
802 }
803 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700804 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100805 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700806 return false;
807 }
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700808
809 using namespace fps_approx_ops;
810 return policy.appRequestRange.min <= policy.primaryRange.min &&
811 policy.appRequestRange.max >= policy.primaryRange.max;
Steven Thomasd4071902020-03-24 16:02:53 -0700812}
813
814status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800815 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100816 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100817 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100818 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 mDisplayManagerPolicy = policy;
823 if (*getCurrentPolicyLocked() == previousPolicy) {
824 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100825 }
Ady Abraham2139f732019-11-13 18:56:40 -0800826 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100827 return NO_ERROR;
828}
829
Steven Thomasd4071902020-03-24 16:02:53 -0700830status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100831 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100832 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700833 return BAD_VALUE;
834 }
Marin Shalamanov4c7831e2021-06-08 20:44:06 +0200835 lastBestRefreshRateInvocation.reset();
Steven Thomasd4071902020-03-24 16:02:53 -0700836 Policy previousPolicy = *getCurrentPolicyLocked();
837 mOverridePolicy = policy;
838 if (*getCurrentPolicyLocked() == previousPolicy) {
839 return CURRENT_POLICY_UNCHANGED;
840 }
841 constructAvailableRefreshRates();
842 return NO_ERROR;
843}
844
845const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
846 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
847}
848
849RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
850 std::lock_guard lock(mLock);
851 return *getCurrentPolicyLocked();
852}
853
854RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
855 std::lock_guard lock(mLock);
856 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100857}
858
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100859bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100860 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700861 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ady Abraham6b7ad652021-06-23 17:34:57 -0700862 if (refreshRate->getModeId() == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100863 return true;
864 }
865 }
866 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800867}
868
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100869void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800870 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
871 std::vector<const RefreshRate*>* outRefreshRates) {
872 outRefreshRates->clear();
873 outRefreshRates->reserve(mRefreshRates.size());
874 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800875 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100876 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Ady Abraham6b7ad652021-06-23 17:34:57 -0700877 refreshRate->getModeId().value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800878 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800879 }
880 }
881
882 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
883 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100884 if (refreshRate1->mode->getVsyncPeriod() !=
885 refreshRate2->mode->getVsyncPeriod()) {
886 return refreshRate1->mode->getVsyncPeriod() >
887 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700888 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100889 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700890 }
Ady Abraham2139f732019-11-13 18:56:40 -0800891 });
892}
893
894void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100895 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700896 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100897 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100898 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700899
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100900 auto filterRefreshRates =
901 [&](Fps min, Fps max, const char* listName,
902 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
903 getSortedRefreshRateListLocked(
904 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
905 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800906
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100907 return mode->getHeight() == defaultMode->getHeight() &&
908 mode->getWidth() == defaultMode->getWidth() &&
909 mode->getDpiX() == defaultMode->getDpiX() &&
910 mode->getDpiY() == defaultMode->getDpiY() &&
911 (policy->allowGroupSwitching ||
912 mode->getGroup() == defaultMode->getGroup()) &&
913 refreshRate.inPolicy(min, max);
914 },
915 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800916
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100917 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
918 "No matching modes for %s range: min=%s max=%s", listName,
919 to_string(min).c_str(), to_string(max).c_str());
920 auto stringifyRefreshRates = [&]() -> std::string {
921 std::string str;
922 for (auto refreshRate : *outRefreshRates) {
923 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
924 }
925 return str;
926 };
927 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
928 };
Steven Thomasf734df42020-04-13 21:09:28 -0700929
930 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
931 &mPrimaryRefreshRates);
932 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
933 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800934}
935
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100936Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700937 using namespace fps_approx_ops;
938
939 if (frameRate <= mKnownFrameRates.front()) {
940 return mKnownFrameRates.front();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700941 }
942
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700943 if (frameRate >= mKnownFrameRates.back()) {
944 return mKnownFrameRates.back();
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700945 }
946
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100947 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700948 isStrictlyLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700949
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700950 const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
951 const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700952 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
953}
954
Ana Krulecb9afd792020-06-11 13:16:15 -0700955RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
956 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100957 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700958 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
959 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
TreeHugger Robot758ab612021-06-22 19:17:29 +0000960 const auto& currentPolicy = getCurrentPolicyLocked();
Ana Krulecb9afd792020-06-11 13:16:15 -0700961
962 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
963 // the min allowed refresh rate is higher than the device min, we do not want to enable the
964 // timer.
965 if (deviceMin < minByPolicy) {
966 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
967 }
968 if (minByPolicy == maxByPolicy) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000969 // when min primary range in display manager policy is below device min turn on the timer.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700970 if (isApproxLess(currentPolicy->primaryRange.min, deviceMin.getFps())) {
TreeHugger Robot758ab612021-06-22 19:17:29 +0000971 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
Ana Krulecb9afd792020-06-11 13:16:15 -0700972 }
973 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
974 }
975 // Turn on the timer in all other cases.
976 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
977}
978
Ady Abraham62a0be22020-12-08 16:54:10 -0800979int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700980 // This calculation needs to be in sync with the java code
981 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200982
983 // The threshold must be smaller than 0.001 in order to differentiate
984 // between the fractional pairs (e.g. 59.94 and 60).
985 constexpr float kThreshold = 0.0009f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800986 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700987 const auto numPeriodsRounded = std::round(numPeriods);
988 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800989 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700990 }
991
Ady Abraham62f216c2020-10-13 19:07:23 -0700992 return static_cast<int>(numPeriodsRounded);
993}
994
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200995bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700996 if (isStrictlyLess(bigger, smaller)) {
Marin Shalamanov15a0fc62021-08-16 18:20:21 +0200997 return isFractionalPairOrMultiple(bigger, smaller);
998 }
999
1000 const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
1001 constexpr float kCoef = 1000.f / 1001.f;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001002 return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
1003 isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
Marin Shalamanov15a0fc62021-08-16 18:20:21 +02001004}
1005
Marin Shalamanovba421a82020-11-10 21:49:26 +01001006void RefreshRateConfigs::dump(std::string& result) const {
1007 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001008 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +01001009 mDisplayManagerPolicy.toString().c_str());
1010 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
1011 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001012 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +01001013 currentPolicy.toString().c_str());
1014 }
1015
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001016 auto mode = mCurrentRefreshRate->mode;
1017 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +01001018
1019 result.append("Refresh rates:\n");
1020 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001021 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +01001022 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
1023 }
1024
Ady Abraham64c2fc02020-12-29 12:07:50 -08001025 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
1026 mSupportsFrameRateOverride ? "yes" : "no");
Ady Abraham6d885932021-09-03 18:05:48 -07001027 base::StringAppendF(&result, "Idle timer: (%s) %s\n",
1028 mConfig.supportKernelIdleTimer ? "kernel" : "platform",
Ady Abraham9a2ea342021-09-03 17:32:34 -07001029 mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Marin Shalamanovba421a82020-11-10 21:49:26 +01001030 result.append("\n");
1031}
1032
Ady Abraham2139f732019-11-13 18:56:40 -08001033} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001034
1035// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08001036#pragma clang diagnostic pop // ignored "-Wextra"