blob: b062acd948e614e802b9b1f1988f9d7550de29fe [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 Abraham8a82ba62020-01-17 12:43:17 -080025#include <android-base/stringprintf.h>
26#include <utils/Trace.h>
27#include <chrono>
28#include <cmath>
Ady Abraham4899ff82021-01-06 13:53:29 -080029#include "../SurfaceFlingerProperties.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080030
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080031#undef LOG_TAG
32#define LOG_TAG "RefreshRateConfigs"
33
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080034namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010035namespace {
36std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010037 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010038 RefreshRateConfigs::layerVoteTypeString(layer.vote).c_str(), weight,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010039 toString(layer.seamlessness).c_str(),
40 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010041}
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010042
Marin Shalamanova7fe3042021-01-29 21:02:08 +010043std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010044 std::vector<Fps> knownFrameRates = {Fps(24.0f), Fps(30.0f), Fps(45.0f), Fps(60.0f), Fps(72.0f)};
Marin Shalamanova7fe3042021-01-29 21:02:08 +010045 knownFrameRates.reserve(knownFrameRates.size() + modes.size());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010046
47 // Add all supported refresh rates to the set
Marin Shalamanova7fe3042021-01-29 21:02:08 +010048 for (const auto& mode : modes) {
49 const auto refreshRate = Fps::fromPeriodNsecs(mode->getVsyncPeriod());
Marin Shalamanoveadf2e72020-12-10 15:35:28 +010050 knownFrameRates.emplace_back(refreshRate);
51 }
52
53 // Sort and remove duplicates
54 std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
55 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
56 Fps::EqualsWithMargin()),
57 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
Marin Shalamanov46084422020-10-13 12:33:42 +020066std::string RefreshRate::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010067 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010068 getModeId().value(), mode->getHwcId(), getFps().getValue(),
69 mode->getWidth(), mode->getHeight(), getModeGroup());
Marin Shalamanov46084422020-10-13 12:33:42 +020070}
71
Ady Abrahama6b676e2020-05-27 14:29:09 -070072std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
73 switch (vote) {
74 case LayerVoteType::NoVote:
75 return "NoVote";
76 case LayerVoteType::Min:
77 return "Min";
78 case LayerVoteType::Max:
79 return "Max";
80 case LayerVoteType::Heuristic:
81 return "Heuristic";
82 case LayerVoteType::ExplicitDefault:
83 return "ExplicitDefault";
84 case LayerVoteType::ExplicitExactOrMultiple:
85 return "ExplicitExactOrMultiple";
Ady Abrahamdd5bfa92021-01-07 17:56:08 -080086 case LayerVoteType::ExplicitExact:
87 return "ExplicitExact";
Ady Abrahama6b676e2020-05-27 14:29:09 -070088 }
89}
90
Marin Shalamanovb6674e72020-11-06 13:05:57 +010091std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov228f46b2021-01-28 21:11:45 +010092 return base::StringPrintf("default mode ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010093 ", primary range: %s, app request range: %s",
Marin Shalamanova7fe3042021-01-29 21:02:08 +010094 defaultMode.value(), allowGroupSwitching,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010095 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020096}
97
Ady Abraham4ccdcb42020-02-11 17:34:34 -080098std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
99 nsecs_t displayPeriod) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800100 auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
101 if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
102 std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
103 quotient++;
104 remainder = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800105 }
106
Ady Abraham62a0be22020-12-08 16:54:10 -0800107 return {quotient, remainder};
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800108}
109
Ady Abraham62a0be22020-12-08 16:54:10 -0800110float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
111 const RefreshRate& refreshRate,
112 bool isSeamlessSwitch) const {
113 // Slightly prefer seamless switches.
114 constexpr float kSeamedSwitchPenalty = 0.95f;
115 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
116
117 // If the layer wants Max, give higher score to the higher refresh rate
118 if (layer.vote == LayerVoteType::Max) {
119 const auto ratio =
120 refreshRate.fps.getValue() / mAppRequestRefreshRates.back()->fps.getValue();
121 // use ratio^2 to get a lower score the more we get further from peak
122 return ratio * ratio;
123 }
124
125 const auto displayPeriod = refreshRate.getVsyncPeriod();
126 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
127 if (layer.vote == LayerVoteType::ExplicitDefault) {
128 // Find the actual rate the layer will render, assuming
129 // that layerPeriod is the minimal time to render a frame
130 auto actualLayerPeriod = displayPeriod;
131 int multiplier = 1;
132 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
133 multiplier++;
134 actualLayerPeriod = displayPeriod * multiplier;
135 }
136 return std::min(1.0f,
137 static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
138 }
139
140 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
141 layer.vote == LayerVoteType::Heuristic) {
142 // Calculate how many display vsyncs we need to present a single frame for this
143 // layer
144 const auto [displayFramesQuotient, displayFramesRemainder] =
145 getDisplayFrames(layerPeriod, displayPeriod);
146 static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
147 if (displayFramesRemainder == 0) {
148 // Layer desired refresh rate matches the display rate.
149 return 1.0f * seamlessness;
150 }
151
152 if (displayFramesQuotient == 0) {
153 // Layer desired refresh rate is higher than the display rate.
154 return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
155 (1.0f / (MAX_FRAMES_TO_FIT + 1));
156 }
157
158 // Layer desired refresh rate is lower than the display rate. Check how well it fits
159 // the cadence.
160 auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
161 int iter = 2;
162 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
163 diff = diff - (displayPeriod - diff);
164 iter++;
165 }
166
167 return (1.0f / iter) * seamlessness;
168 }
169
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800170 if (layer.vote == LayerVoteType::ExplicitExact) {
171 const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
172 if (mSupportsFrameRateOverride) {
173 // Since we support frame rate override, allow refresh rates which are
174 // multiples of the layer's request, as those apps would be throttled
175 // down to run at the desired refresh rate.
176 return divider > 0;
177 }
178
179 return divider == 1;
180 }
181
Ady Abraham62a0be22020-12-08 16:54:10 -0800182 return 0;
183}
184
185struct RefreshRateScore {
186 const RefreshRate* refreshRate;
187 float score;
188};
189
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100190RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
191 const GlobalSignals& globalSignals,
192 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800193 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +0200194 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800195
Ady Abrahamdfd62162020-06-10 16:11:56 -0700196 if (outSignalsConsidered) *outSignalsConsidered = {};
197 const auto setTouchConsidered = [&] {
198 if (outSignalsConsidered) {
199 outSignalsConsidered->touch = true;
200 }
201 };
202
203 const auto setIdleConsidered = [&] {
204 if (outSignalsConsidered) {
205 outSignalsConsidered->idle = true;
206 }
207 };
208
Ady Abraham8a82ba62020-01-17 12:43:17 -0800209 std::lock_guard lock(mLock);
210
211 int noVoteLayers = 0;
212 int minVoteLayers = 0;
213 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800214 int explicitDefaultVoteLayers = 0;
215 int explicitExactOrMultipleVoteLayers = 0;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800216 int explicitExact = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800217 float maxExplicitWeight = 0;
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100218 int seamedFocusedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800219 for (const auto& layer : layers) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800220 switch (layer.vote) {
221 case LayerVoteType::NoVote:
222 noVoteLayers++;
223 break;
224 case LayerVoteType::Min:
225 minVoteLayers++;
226 break;
227 case LayerVoteType::Max:
228 maxVoteLayers++;
229 break;
230 case LayerVoteType::ExplicitDefault:
231 explicitDefaultVoteLayers++;
232 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
233 break;
234 case LayerVoteType::ExplicitExactOrMultiple:
235 explicitExactOrMultipleVoteLayers++;
236 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
237 break;
238 case LayerVoteType::ExplicitExact:
239 explicitExact++;
240 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
241 break;
242 case LayerVoteType::Heuristic:
243 break;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800244 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200245
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100246 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
247 seamedFocusedLayers++;
Marin Shalamanov46084422020-10-13 12:33:42 +0200248 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800249 }
250
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800251 const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
252 explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
Alec Mouri11232a22020-05-14 18:06:25 -0700253
Steven Thomasf734df42020-04-13 21:09:28 -0700254 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
255 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700256 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700257 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700258 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700259 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800260 }
261
Alec Mouri11232a22020-05-14 18:06:25 -0700262 // If the primary range consists of a single refresh rate then we can only
263 // move out the of range if layers explicitly request a different refresh
264 // rate.
265 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100266 const bool primaryRangeIsSingleRate =
267 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700268
Ady Abrahamdfd62162020-06-10 16:11:56 -0700269 if (!globalSignals.touch && globalSignals.idle &&
270 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700271 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700272 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700273 return getMinRefreshRateByPolicyLocked();
274 }
275
Steven Thomasdebafed2020-05-18 17:30:35 -0700276 if (layers.empty() || noVoteLayers == layers.size()) {
277 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700278 }
279
Ady Abraham8a82ba62020-01-17 12:43:17 -0800280 // Only if all layers want Min we should return Min
281 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700282 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700283 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800284 }
285
Ady Abraham8a82ba62020-01-17 12:43:17 -0800286 // Find the best refresh rate based on score
Ady Abraham62a0be22020-12-08 16:54:10 -0800287 std::vector<RefreshRateScore> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700288 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800289
Steven Thomasf734df42020-04-13 21:09:28 -0700290 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800291 scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
Ady Abraham8a82ba62020-01-17 12:43:17 -0800292 }
293
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100294 const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
Marin Shalamanov46084422020-10-13 12:33:42 +0200295
Ady Abraham8a82ba62020-01-17 12:43:17 -0800296 for (const auto& layer : layers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700297 ALOGV("Calculating score for %s (%s, weight %.2f)", layer.name.c_str(),
298 layerVoteTypeString(layer.vote).c_str(), layer.weight);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800299 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800300 continue;
301 }
302
Ady Abraham71c437d2020-01-31 15:56:57 -0800303 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800304
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800305 for (auto i = 0u; i < scores.size(); i++) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100306 const bool isSeamlessSwitch =
307 scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200308
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100309 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100310 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800311 formatLayerInfo(layer, weight).c_str(),
312 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100313 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200314 continue;
315 }
316
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100317 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
318 !layer.focused) {
319 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100320 " Current mode = %s",
Ady Abraham62a0be22020-12-08 16:54:10 -0800321 formatLayerInfo(layer, weight).c_str(),
322 scores[i].refreshRate->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100323 mCurrentRefreshRate->toString().c_str());
324 continue;
325 }
326
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100327 // Layers with default seamlessness vote for the current mode group if
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100328 // there are layers with seamlessness=SeamedAndSeamless and for the default
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100329 // mode group otherwise. In second case, if the current mode group is different
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100330 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
331 // disappeared.
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100332 const bool isInPolicyForDefault = seamedFocusedLayers > 0
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100333 ? scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup()
334 : scores[i].refreshRate->getModeGroup() == defaultMode->getModeGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100335
Marin Shalamanovae0b5352021-03-24 12:56:08 +0100336 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100337 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800338 scores[i].refreshRate->toString().c_str(),
339 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200340 continue;
341 }
342
Ady Abraham62a0be22020-12-08 16:54:10 -0800343 bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
344 policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700345 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800346 !(layer.focused &&
347 (layer.vote == LayerVoteType::ExplicitDefault ||
348 layer.vote == LayerVoteType::ExplicitExact))) {
Ady Abraham20c029c2020-07-06 12:58:05 -0700349 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700350 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700351 continue;
352 }
353
Ady Abraham62a0be22020-12-08 16:54:10 -0800354 const auto layerScore =
355 calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
356 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
357 scores[i].refreshRate->getName().c_str(), layerScore);
358 scores[i].score += weight * layerScore;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800359 }
360 }
361
Ady Abraham34702102020-02-10 14:12:05 -0800362 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
363 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
364 // or the lower otherwise.
365 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
366 ? getBestRefreshRate(scores.rbegin(), scores.rend())
367 : getBestRefreshRate(scores.begin(), scores.end());
368
Alec Mouri11232a22020-05-14 18:06:25 -0700369 if (primaryRangeIsSingleRate) {
370 // If we never scored any layers, then choose the rate from the primary
371 // range instead of picking a random score from the app range.
372 if (std::all_of(scores.begin(), scores.end(),
Ady Abraham62a0be22020-12-08 16:54:10 -0800373 [](RefreshRateScore score) { return score.score == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700374 ALOGV("layers not scored - choose %s",
375 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700376 return getMaxRefreshRateByPolicyLocked();
377 } else {
378 return *bestRefreshRate;
379 }
380 }
381
Steven Thomasf734df42020-04-13 21:09:28 -0700382 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
383 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
384 // vote we should not change it if we get a touch event. Only apply touch boost if it will
385 // actually increase the refresh rate over the normal selection.
386 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700387
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800388 bool touchBoostForExplicitExact = explicitExact == 0 || mSupportsFrameRateOverride;
389 if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100390 bestRefreshRate->fps.lessThanWithMargin(touchRefreshRate.fps)) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700391 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700392 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700393 return touchRefreshRate;
394 }
395
Ady Abrahamde7156e2020-02-28 17:29:39 -0800396 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800397}
398
Ady Abraham62a0be22020-12-08 16:54:10 -0800399std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
400groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
401 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
402 for (const auto& layer : layers) {
403 auto iter = layersByUid.emplace(layer.ownerUid,
404 std::vector<const RefreshRateConfigs::LayerRequirement*>());
405 auto& layersWithSameUid = iter.first->second;
406 layersWithSameUid.push_back(&layer);
407 }
408
409 // Remove uids that can't have a frame rate override
410 for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
411 const auto& layersWithSameUid = iter->second;
412 bool skipUid = false;
413 for (const auto& layer : layersWithSameUid) {
414 if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
415 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
416 skipUid = true;
417 break;
418 }
419 }
420 if (skipUid) {
421 iter = layersByUid.erase(iter);
422 } else {
423 ++iter;
424 }
425 }
426
427 return layersByUid;
428}
429
430std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
431 const AllRefreshRatesMapType& refreshRates) {
432 std::vector<RefreshRateScore> scores;
433 scores.reserve(refreshRates.size());
434 for (const auto& [ignored, refreshRate] : refreshRates) {
435 scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
436 }
437 std::sort(scores.begin(), scores.end(),
438 [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
439 return scores;
440}
441
442RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800443 const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800444 ATRACE_CALL();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800445 if (!mSupportsFrameRateOverride) return {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800446
Ady Abraham64c2fc02020-12-29 12:07:50 -0800447 ALOGV("getFrameRateOverrides %zu layers", layers.size());
Ady Abraham62a0be22020-12-08 16:54:10 -0800448 std::lock_guard lock(mLock);
449 std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
450 std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
451 groupLayersByUid(layers);
452 UidToFrameRateOverride frameRateOverrides;
453 for (const auto& [uid, layersWithSameUid] : layersByUid) {
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800454 // Layers with ExplicitExactOrMultiple expect touch boost
455 const bool hasExplicitExactOrMultiple =
456 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
457 [](const auto& layer) {
458 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
459 });
460
461 if (touch && hasExplicitExactOrMultiple) {
462 continue;
463 }
464
Ady Abraham62a0be22020-12-08 16:54:10 -0800465 for (auto& score : scores) {
466 score.score = 0;
467 }
468
469 for (const auto& layer : layersWithSameUid) {
470 if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
471 continue;
472 }
473
474 LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800475 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
476 layer->vote != LayerVoteType::ExplicitExact);
Ady Abraham62a0be22020-12-08 16:54:10 -0800477 for (RefreshRateScore& score : scores) {
478 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
479 /*isSeamlessSwitch*/ true);
480 score.score += layer->weight * layerScore;
481 }
482 }
483
484 // We just care about the refresh rates which are a divider of the
485 // display refresh rate
486 auto iter =
487 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
488 return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
489 });
490 scores.erase(iter, scores.end());
491
492 // If we never scored any layers, we don't have a preferred frame rate
493 if (std::all_of(scores.begin(), scores.end(),
494 [](const RefreshRateScore& score) { return score.score == 0; })) {
495 continue;
496 }
497
498 // Now that we scored all the refresh rates we need to pick the one that got the highest
499 // score.
500 const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
Ady Abraham5cc2e262021-03-25 13:09:17 -0700501 frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
Ady Abraham62a0be22020-12-08 16:54:10 -0800502 }
503
504 return frameRateOverrides;
505}
506
Ady Abraham34702102020-02-10 14:12:05 -0800507template <typename Iter>
508const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800509 constexpr auto EPSILON = 0.001f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800510 const RefreshRate* bestRefreshRate = begin->refreshRate;
511 float max = begin->score;
Ady Abraham34702102020-02-10 14:12:05 -0800512 for (auto i = begin; i != end; ++i) {
513 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100514 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800515
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100516 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800517
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800518 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800519 max = score;
520 bestRefreshRate = refreshRate;
521 }
522 }
523
Ady Abraham34702102020-02-10 14:12:05 -0800524 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800525}
526
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100527std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
Marin Shalamanov23c44202020-12-22 19:09:20 +0100528 std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
Ady Abraham2139f732019-11-13 18:56:40 -0800529 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100530
531 const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
532 : *mCurrentRefreshRate;
533 const auto& min = *mMinSupportedRefreshRate;
534
535 if (current != min) {
536 const auto& refreshRate = timerExpired ? min : current;
537 return refreshRate.getFps();
538 }
539
540 return {};
Steven Thomasf734df42020-04-13 21:09:28 -0700541}
542
543const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200544 for (auto refreshRate : mPrimaryRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100545 if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200546 return *refreshRate;
547 }
548 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100549 ALOGE("Can't find min refresh rate by policy with the same mode group"
550 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200551 mCurrentRefreshRate->toString().c_str());
552 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700553 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800554}
555
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100556RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800557 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700558 return getMaxRefreshRateByPolicyLocked();
559}
560
561const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200562 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
563 const auto& refreshRate = (**it);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100564 if (mCurrentRefreshRate->getModeGroup() == refreshRate.getModeGroup()) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200565 return refreshRate;
566 }
567 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100568 ALOGE("Can't find max refresh rate by policy with the same mode group"
569 " as the current mode %s",
Marin Shalamanov46084422020-10-13 12:33:42 +0200570 mCurrentRefreshRate->toString().c_str());
571 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700572 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800573}
574
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100575RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
Ady Abraham2139f732019-11-13 18:56:40 -0800576 std::lock_guard lock(mLock);
577 return *mCurrentRefreshRate;
578}
579
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100580RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
Ana Krulec5d477912020-02-07 12:02:38 -0800581 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800582 return getCurrentRefreshRateByPolicyLocked();
583}
584
585const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700586 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
587 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800588 return *mCurrentRefreshRate;
589 }
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100590 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
Ana Krulec5d477912020-02-07 12:02:38 -0800591}
592
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100593void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
Ady Abraham2139f732019-11-13 18:56:40 -0800594 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100595 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800596}
597
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100598RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800599 bool enableFrameRateOverride)
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100600 : mKnownFrameRates(constructKnownFrameRates(modes)),
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800601 mEnableFrameRateOverride(enableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100602 updateDisplayModes(modes, currentModeId);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100603}
604
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100605void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
606 DisplayModeId currentModeId) {
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100607 std::lock_guard lock(mLock);
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100608 // The current mode should be supported
609 LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
610 return mode->getId() == currentModeId;
611 }));
Ady Abrahamabc27602020-04-08 17:20:29 -0700612
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100613 mRefreshRates.clear();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100614 for (const auto& mode : modes) {
615 const auto modeId = mode->getId();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100616 mRefreshRates.emplace(modeId,
Marin Shalamanovf22e6ac2021-02-10 20:45:15 +0100617 std::make_unique<RefreshRate>(modeId, mode, mode->getFps(),
Ady Abrahamabc27602020-04-08 17:20:29 -0700618 RefreshRate::ConstructorTag(0)));
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100619 if (modeId == currentModeId) {
620 mCurrentRefreshRate = mRefreshRates.at(modeId).get();
Ady Abrahamabc27602020-04-08 17:20:29 -0700621 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800622 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700623
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100624 std::vector<const RefreshRate*> sortedModes;
625 getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
Marin Shalamanov75f37252021-02-10 21:43:57 +0100626 // Reset the policy because the old one may no longer be valid.
627 mDisplayManagerPolicy = {};
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100628 mDisplayManagerPolicy.defaultMode = currentModeId;
629 mMinSupportedRefreshRate = sortedModes.front();
630 mMaxSupportedRefreshRate = sortedModes.back();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800631
632 mSupportsFrameRateOverride = false;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800633 if (mEnableFrameRateOverride) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100634 for (const auto& mode1 : sortedModes) {
635 for (const auto& mode2 : sortedModes) {
636 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
Ady Abraham4899ff82021-01-06 13:53:29 -0800637 mSupportsFrameRateOverride = true;
638 break;
639 }
Ady Abraham64c2fc02020-12-29 12:07:50 -0800640 }
641 }
642 }
Ady Abraham4899ff82021-01-06 13:53:29 -0800643
Ady Abrahamabc27602020-04-08 17:20:29 -0700644 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800645}
646
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100647bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100648 // defaultMode must be a valid mode, and within the given refresh rate range.
649 auto iter = mRefreshRates.find(policy.defaultMode);
Steven Thomasd4071902020-03-24 16:02:53 -0700650 if (iter == mRefreshRates.end()) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100651 ALOGE("Default mode is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700652 return false;
653 }
654 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700655 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100656 ALOGE("Default mode is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700657 return false;
658 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100659 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
660 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700661}
662
663status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800664 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100665 if (!isPolicyValidLocked(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100666 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100667 return BAD_VALUE;
668 }
Steven Thomasd4071902020-03-24 16:02:53 -0700669 Policy previousPolicy = *getCurrentPolicyLocked();
670 mDisplayManagerPolicy = policy;
671 if (*getCurrentPolicyLocked() == previousPolicy) {
672 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100673 }
Ady Abraham2139f732019-11-13 18:56:40 -0800674 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100675 return NO_ERROR;
676}
677
Steven Thomasd4071902020-03-24 16:02:53 -0700678status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100679 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100680 if (policy && !isPolicyValidLocked(*policy)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700681 return BAD_VALUE;
682 }
683 Policy previousPolicy = *getCurrentPolicyLocked();
684 mOverridePolicy = policy;
685 if (*getCurrentPolicyLocked() == previousPolicy) {
686 return CURRENT_POLICY_UNCHANGED;
687 }
688 constructAvailableRefreshRates();
689 return NO_ERROR;
690}
691
692const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
693 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
694}
695
696RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
697 std::lock_guard lock(mLock);
698 return *getCurrentPolicyLocked();
699}
700
701RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
702 std::lock_guard lock(mLock);
703 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100704}
705
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100706bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100707 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700708 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100709 if (refreshRate->modeId == modeId) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100710 return true;
711 }
712 }
713 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800714}
715
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100716void RefreshRateConfigs::getSortedRefreshRateListLocked(
Ady Abraham2139f732019-11-13 18:56:40 -0800717 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
718 std::vector<const RefreshRate*>* outRefreshRates) {
719 outRefreshRates->clear();
720 outRefreshRates->reserve(mRefreshRates.size());
721 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800722 if (shouldAddRefreshRate(*refreshRate)) {
Marin Shalamanov228f46b2021-01-28 21:11:45 +0100723 ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100724 refreshRate->modeId.value());
Ady Abraham2e1dd892020-03-05 13:48:36 -0800725 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800726 }
727 }
728
729 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
730 [](const auto refreshRate1, const auto refreshRate2) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100731 if (refreshRate1->mode->getVsyncPeriod() !=
732 refreshRate2->mode->getVsyncPeriod()) {
733 return refreshRate1->mode->getVsyncPeriod() >
734 refreshRate2->mode->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700735 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100736 return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700737 }
Ady Abraham2139f732019-11-13 18:56:40 -0800738 });
739}
740
741void RefreshRateConfigs::constructAvailableRefreshRates() {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100742 // Filter modes based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700743 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100744 const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100745 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700746
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100747 auto filterRefreshRates =
748 [&](Fps min, Fps max, const char* listName,
749 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
750 getSortedRefreshRateListLocked(
751 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
752 const auto& mode = refreshRate.mode;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800753
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100754 return mode->getHeight() == defaultMode->getHeight() &&
755 mode->getWidth() == defaultMode->getWidth() &&
756 mode->getDpiX() == defaultMode->getDpiX() &&
757 mode->getDpiY() == defaultMode->getDpiY() &&
758 (policy->allowGroupSwitching ||
759 mode->getGroup() == defaultMode->getGroup()) &&
760 refreshRate.inPolicy(min, max);
761 },
762 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800763
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100764 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
765 "No matching modes for %s range: min=%s max=%s", listName,
766 to_string(min).c_str(), to_string(max).c_str());
767 auto stringifyRefreshRates = [&]() -> std::string {
768 std::string str;
769 for (auto refreshRate : *outRefreshRates) {
770 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
771 }
772 return str;
773 };
774 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
775 };
Steven Thomasf734df42020-04-13 21:09:28 -0700776
777 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
778 &mPrimaryRefreshRates);
779 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
780 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800781}
782
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100783Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
784 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700785 return *mKnownFrameRates.begin();
786 }
787
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100788 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700789 return *std::prev(mKnownFrameRates.end());
790 }
791
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100792 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
793 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700794
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100795 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
796 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700797 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
798}
799
Ana Krulecb9afd792020-06-11 13:16:15 -0700800RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
801 std::lock_guard lock(mLock);
Marin Shalamanoveadf2e72020-12-10 15:35:28 +0100802 const auto& deviceMin = *mMinSupportedRefreshRate;
Ana Krulecb9afd792020-06-11 13:16:15 -0700803 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
804 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
805
806 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
807 // the min allowed refresh rate is higher than the device min, we do not want to enable the
808 // timer.
809 if (deviceMin < minByPolicy) {
810 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
811 }
812 if (minByPolicy == maxByPolicy) {
813 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
814 // max are all the same. This saves us extra unnecessary calls to sysprop.
815 if (deviceMin == minByPolicy) {
816 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
817 }
818 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
819 }
820 // Turn on the timer in all other cases.
821 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
822}
823
Ady Abraham62a0be22020-12-08 16:54:10 -0800824int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700825 // This calculation needs to be in sync with the java code
826 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
827 constexpr float kThreshold = 0.1f;
Ady Abraham62a0be22020-12-08 16:54:10 -0800828 const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700829 const auto numPeriodsRounded = std::round(numPeriods);
830 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800831 return 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700832 }
833
Ady Abraham62f216c2020-10-13 19:07:23 -0700834 return static_cast<int>(numPeriodsRounded);
835}
836
Marin Shalamanovba421a82020-11-10 21:49:26 +0100837void RefreshRateConfigs::dump(std::string& result) const {
838 std::lock_guard lock(mLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100839 base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100840 mDisplayManagerPolicy.toString().c_str());
841 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
842 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100843 base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
Marin Shalamanovba421a82020-11-10 21:49:26 +0100844 currentPolicy.toString().c_str());
845 }
846
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100847 auto mode = mCurrentRefreshRate->mode;
848 base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
Marin Shalamanovba421a82020-11-10 21:49:26 +0100849
850 result.append("Refresh rates:\n");
851 for (const auto& [id, refreshRate] : mRefreshRates) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100852 mode = refreshRate->mode;
Marin Shalamanovba421a82020-11-10 21:49:26 +0100853 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
854 }
855
Ady Abraham64c2fc02020-12-29 12:07:50 -0800856 base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
857 mSupportsFrameRateOverride ? "yes" : "no");
Marin Shalamanovba421a82020-11-10 21:49:26 +0100858 result.append("\n");
859}
860
Ady Abraham2139f732019-11-13 18:56:40 -0800861} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100862
863// TODO(b/129481165): remove the #pragma below and fix conversion issues
Ady Abrahamdd5bfa92021-01-07 17:56:08 -0800864#pragma clang diagnostic pop // ignored "-Wextra"