blob: 2eb4df1d9563d2eabf23d78f0c3cd27c7c414faf [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
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080020#include "RefreshRateConfigs.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080021#include <android-base/stringprintf.h>
22#include <utils/Trace.h>
23#include <chrono>
24#include <cmath>
25
Ady Abraham5b8afb5a2020-03-06 14:57:26 -080026#undef LOG_TAG
27#define LOG_TAG "RefreshRateConfigs"
28
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080029namespace android::scheduler {
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010030namespace {
31std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +010032 return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010033 RefreshRateConfigs::layerVoteTypeString(layer.vote).c_str(), weight,
Marin Shalamanove8a663d2020-11-24 17:48:00 +010034 toString(layer.seamlessness).c_str(),
35 to_string(layer.desiredRefreshRate).c_str());
Marin Shalamanov53fc11d2020-11-20 14:00:13 +010036}
37} // namespace
Ady Abraham2139f732019-11-13 18:56:40 -080038
39using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080040using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080041
Marin Shalamanov46084422020-10-13 12:33:42 +020042std::string RefreshRate::toString() const {
43 return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
Marin Shalamanove8a663d2020-11-24 17:48:00 +010044 getConfigId().value(), hwcConfig->getId(), getFps().getValue(),
Marin Shalamanov46084422020-10-13 12:33:42 +020045 hwcConfig->getWidth(), hwcConfig->getHeight(), getConfigGroup());
46}
47
Ady Abrahama6b676e2020-05-27 14:29:09 -070048std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
49 switch (vote) {
50 case LayerVoteType::NoVote:
51 return "NoVote";
52 case LayerVoteType::Min:
53 return "Min";
54 case LayerVoteType::Max:
55 return "Max";
56 case LayerVoteType::Heuristic:
57 return "Heuristic";
58 case LayerVoteType::ExplicitDefault:
59 return "ExplicitDefault";
60 case LayerVoteType::ExplicitExactOrMultiple:
61 return "ExplicitExactOrMultiple";
62 }
63}
64
Marin Shalamanovb6674e72020-11-06 13:05:57 +010065std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020066 return base::StringPrintf("default config ID: %d, allowGroupSwitching = %d"
Marin Shalamanove8a663d2020-11-24 17:48:00 +010067 ", primary range: %s, app request range: %s",
68 defaultConfig.value(), allowGroupSwitching,
69 primaryRange.toString().c_str(), appRequestRange.toString().c_str());
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020070}
71
Ady Abraham4ccdcb42020-02-11 17:34:34 -080072std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
73 nsecs_t displayPeriod) const {
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +000074 auto [displayFramesQuot, displayFramesRem] = std::div(layerPeriod, displayPeriod);
75 if (displayFramesRem <= MARGIN_FOR_PERIOD_CALCULATION ||
76 std::abs(displayFramesRem - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
77 displayFramesQuot++;
78 displayFramesRem = 0;
Ady Abraham4ccdcb42020-02-11 17:34:34 -080079 }
80
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +000081 return {displayFramesQuot, displayFramesRem};
Ady Abraham4ccdcb42020-02-11 17:34:34 -080082}
83
Steven Thomasbb374322020-04-28 22:47:16 -070084const RefreshRate& RefreshRateConfigs::getBestRefreshRate(
Ady Abrahamdfd62162020-06-10 16:11:56 -070085 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
86 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -080087 ATRACE_CALL();
Marin Shalamanov46084422020-10-13 12:33:42 +020088 ALOGV("getBestRefreshRate %zu layers", layers.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -080089
Ady Abrahamdfd62162020-06-10 16:11:56 -070090 if (outSignalsConsidered) *outSignalsConsidered = {};
91 const auto setTouchConsidered = [&] {
92 if (outSignalsConsidered) {
93 outSignalsConsidered->touch = true;
94 }
95 };
96
97 const auto setIdleConsidered = [&] {
98 if (outSignalsConsidered) {
99 outSignalsConsidered->idle = true;
100 }
101 };
102
Ady Abraham8a82ba62020-01-17 12:43:17 -0800103 std::lock_guard lock(mLock);
104
105 int noVoteLayers = 0;
106 int minVoteLayers = 0;
107 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800108 int explicitDefaultVoteLayers = 0;
109 int explicitExactOrMultipleVoteLayers = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800110 float maxExplicitWeight = 0;
Marin Shalamanov46084422020-10-13 12:33:42 +0200111 int seamedLayers = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800112 for (const auto& layer : layers) {
Ady Abraham6fb599b2020-03-05 13:48:22 -0800113 if (layer.vote == LayerVoteType::NoVote) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800114 noVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800115 } else if (layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800116 minVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800117 } else if (layer.vote == LayerVoteType::Max) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800118 maxVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800119 } else if (layer.vote == LayerVoteType::ExplicitDefault) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800120 explicitDefaultVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800121 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
122 } else if (layer.vote == LayerVoteType::ExplicitExactOrMultiple) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800123 explicitExactOrMultipleVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800124 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
125 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200126
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100127 if (layer.seamlessness == Seamlessness::SeamedAndSeamless) {
Marin Shalamanov46084422020-10-13 12:33:42 +0200128 seamedLayers++;
129 }
Ady Abraham6fb599b2020-03-05 13:48:22 -0800130 }
131
Alec Mouri11232a22020-05-14 18:06:25 -0700132 const bool hasExplicitVoteLayers =
133 explicitDefaultVoteLayers > 0 || explicitExactOrMultipleVoteLayers > 0;
134
Steven Thomasf734df42020-04-13 21:09:28 -0700135 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
136 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700137 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700138 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700139 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700140 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800141 }
142
Alec Mouri11232a22020-05-14 18:06:25 -0700143 // If the primary range consists of a single refresh rate then we can only
144 // move out the of range if layers explicitly request a different refresh
145 // rate.
146 const Policy* policy = getCurrentPolicyLocked();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100147 const bool primaryRangeIsSingleRate =
148 policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700149
Ady Abrahamdfd62162020-06-10 16:11:56 -0700150 if (!globalSignals.touch && globalSignals.idle &&
151 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700152 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700153 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700154 return getMinRefreshRateByPolicyLocked();
155 }
156
Steven Thomasdebafed2020-05-18 17:30:35 -0700157 if (layers.empty() || noVoteLayers == layers.size()) {
158 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700159 }
160
Ady Abraham8a82ba62020-01-17 12:43:17 -0800161 // Only if all layers want Min we should return Min
162 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700163 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700164 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800165 }
166
Ady Abraham8a82ba62020-01-17 12:43:17 -0800167 // Find the best refresh rate based on score
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000168 std::vector<std::pair<const RefreshRate*, float>> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700169 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800170
Steven Thomasf734df42020-04-13 21:09:28 -0700171 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000172 scores.emplace_back(refreshRate, 0.0f);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800173 }
174
Marin Shalamanov46084422020-10-13 12:33:42 +0200175 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig);
176
Ady Abraham8a82ba62020-01-17 12:43:17 -0800177 for (const auto& layer : layers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700178 ALOGV("Calculating score for %s (%s, weight %.2f)", layer.name.c_str(),
179 layerVoteTypeString(layer.vote).c_str(), layer.weight);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800180 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800181 continue;
182 }
183
Ady Abraham71c437d2020-01-31 15:56:57 -0800184 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800185
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800186 for (auto i = 0u; i < scores.size(); i++) {
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000187 const bool isSeamlessSwitch =
188 scores[i].first->getConfigGroup() == mCurrentRefreshRate->getConfigGroup();
Marin Shalamanov46084422020-10-13 12:33:42 +0200189
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100190 if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
191 ALOGV("%s ignores %s to avoid non-seamless switch. Current config = %s",
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000192 formatLayerInfo(layer, weight).c_str(), scores[i].first->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100193 mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200194 continue;
195 }
196
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100197 if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
198 !layer.focused) {
199 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
200 " Current config = %s",
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000201 formatLayerInfo(layer, weight).c_str(), scores[i].first->toString().c_str(),
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100202 mCurrentRefreshRate->toString().c_str());
203 continue;
204 }
205
206 // Layers with default seamlessness vote for the current config group if
207 // there are layers with seamlessness=SeamedAndSeamless and for the default
208 // config group otherwise. In second case, if the current config group is different
209 // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
210 // disappeared.
211 const bool isInPolicyForDefault = seamedLayers > 0
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000212 ? scores[i].first->getConfigGroup() == mCurrentRefreshRate->getConfigGroup()
213 : scores[i].first->getConfigGroup() == defaultConfig->getConfigGroup();
Marin Shalamanov53fc11d2020-11-20 14:00:13 +0100214
215 if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault &&
216 !layer.focused) {
217 ALOGV("%s ignores %s. Current config = %s", formatLayerInfo(layer, weight).c_str(),
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000218 scores[i].first->toString().c_str(), mCurrentRefreshRate->toString().c_str());
Marin Shalamanov46084422020-10-13 12:33:42 +0200219 continue;
220 }
221
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000222 bool inPrimaryRange =
223 scores[i].first->inPolicy(policy->primaryRange.min, policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700224 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abraham20c029c2020-07-06 12:58:05 -0700225 !(layer.focused && layer.vote == LayerVoteType::ExplicitDefault)) {
226 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700227 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700228 continue;
229 }
230
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000231 // If the layer wants Max, give higher score to the higher refresh rate
232 if (layer.vote == LayerVoteType::Max) {
233 const auto ratio =
234 scores[i].first->fps.getValue() / scores.back().first->fps.getValue();
235 // use ratio^2 to get a lower score the more we get further from peak
236 const auto layerScore = ratio * ratio;
237 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
238 scores[i].first->getName().c_str(), layerScore);
239 scores[i].second += weight * layerScore;
240 continue;
241 }
242
243 const auto displayPeriod = scores[i].first->hwcConfig->getVsyncPeriod();
244 const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
245 if (layer.vote == LayerVoteType::ExplicitDefault) {
246 const auto layerScore = [&]() {
247 // Find the actual rate the layer will render, assuming
248 // that layerPeriod is the minimal time to render a frame
249 auto actualLayerPeriod = displayPeriod;
250 int multiplier = 1;
251 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
252 multiplier++;
253 actualLayerPeriod = displayPeriod * multiplier;
254 }
255 return std::min(1.0f,
256 static_cast<float>(layerPeriod) /
257 static_cast<float>(actualLayerPeriod));
258 }();
259
260 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
261 scores[i].first->getName().c_str(), layerScore);
262 scores[i].second += weight * layerScore;
263 continue;
264 }
265
266 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
267 layer.vote == LayerVoteType::Heuristic) {
268 const auto layerScore = [&] {
269 // Calculate how many display vsyncs we need to present a single frame for this
270 // layer
271 const auto [displayFramesQuot, displayFramesRem] =
272 getDisplayFrames(layerPeriod, displayPeriod);
273 static constexpr size_t MAX_FRAMES_TO_FIT =
274 10; // Stop calculating when score < 0.1
275 if (displayFramesRem == 0) {
276 // Layer desired refresh rate matches the display rate.
277 return 1.0f;
278 }
279
280 if (displayFramesQuot == 0) {
281 // Layer desired refresh rate is higher the display rate.
282 return (static_cast<float>(layerPeriod) /
283 static_cast<float>(displayPeriod)) *
284 (1.0f / (MAX_FRAMES_TO_FIT + 1));
285 }
286
287 // Layer desired refresh rate is lower the display rate. Check how well it fits
288 // the cadence
289 auto diff = std::abs(displayFramesRem - (displayPeriod - displayFramesRem));
290 int iter = 2;
291 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
292 diff = diff - (displayPeriod - diff);
293 iter++;
294 }
295
296 return 1.0f / iter;
297 }();
298 // Slightly prefer seamless switches.
299 constexpr float kSeamedSwitchPenalty = 0.95f;
300 const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
301 ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
302 scores[i].first->getName().c_str(), layerScore);
303 scores[i].second += weight * layerScore * seamlessness;
304 continue;
305 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800306 }
307 }
308
Ady Abraham34702102020-02-10 14:12:05 -0800309 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
310 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
311 // or the lower otherwise.
312 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
313 ? getBestRefreshRate(scores.rbegin(), scores.rend())
314 : getBestRefreshRate(scores.begin(), scores.end());
315
Alec Mouri11232a22020-05-14 18:06:25 -0700316 if (primaryRangeIsSingleRate) {
317 // If we never scored any layers, then choose the rate from the primary
318 // range instead of picking a random score from the app range.
319 if (std::all_of(scores.begin(), scores.end(),
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000320 [](std::pair<const RefreshRate*, float> p) { return p.second == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700321 ALOGV("layers not scored - choose %s",
322 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700323 return getMaxRefreshRateByPolicyLocked();
324 } else {
325 return *bestRefreshRate;
326 }
327 }
328
Steven Thomasf734df42020-04-13 21:09:28 -0700329 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
330 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
331 // vote we should not change it if we get a touch event. Only apply touch boost if it will
332 // actually increase the refresh rate over the normal selection.
333 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700334
Ady Abrahamdfd62162020-06-10 16:11:56 -0700335 if (globalSignals.touch && explicitDefaultVoteLayers == 0 &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100336 bestRefreshRate->fps.lessThanWithMargin(touchRefreshRate.fps)) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700337 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700338 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700339 return touchRefreshRate;
340 }
341
Ady Abrahamde7156e2020-02-28 17:29:39 -0800342 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800343}
344
345template <typename Iter>
346const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800347 constexpr auto EPSILON = 0.001f;
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000348 const RefreshRate* bestRefreshRate = begin->first;
349 float max = begin->second;
Ady Abraham34702102020-02-10 14:12:05 -0800350 for (auto i = begin; i != end; ++i) {
351 const auto [refreshRate, score] = *i;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100352 ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800353
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100354 ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800355
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800356 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800357 max = score;
358 bestRefreshRate = refreshRate;
359 }
360 }
361
Ady Abraham34702102020-02-10 14:12:05 -0800362 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800363}
364
Ady Abraham2139f732019-11-13 18:56:40 -0800365const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicy() const {
366 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700367 return getMinRefreshRateByPolicyLocked();
368}
369
370const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200371 for (auto refreshRate : mPrimaryRefreshRates) {
372 if (mCurrentRefreshRate->getConfigGroup() == refreshRate->getConfigGroup()) {
373 return *refreshRate;
374 }
375 }
376 ALOGE("Can't find min refresh rate by policy with the same config group"
377 " as the current config %s",
378 mCurrentRefreshRate->toString().c_str());
379 // Defaulting to the lowest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700380 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800381}
382
383const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
384 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700385 return getMaxRefreshRateByPolicyLocked();
386}
387
388const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
Marin Shalamanov46084422020-10-13 12:33:42 +0200389 for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
390 const auto& refreshRate = (**it);
391 if (mCurrentRefreshRate->getConfigGroup() == refreshRate.getConfigGroup()) {
392 return refreshRate;
393 }
394 }
395 ALOGE("Can't find max refresh rate by policy with the same config group"
396 " as the current config %s",
397 mCurrentRefreshRate->toString().c_str());
398 // Defaulting to the highest refresh rate
Steven Thomasf734df42020-04-13 21:09:28 -0700399 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800400}
401
402const RefreshRate& RefreshRateConfigs::getCurrentRefreshRate() const {
403 std::lock_guard lock(mLock);
404 return *mCurrentRefreshRate;
405}
406
Ana Krulec5d477912020-02-07 12:02:38 -0800407const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
408 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800409 return getCurrentRefreshRateByPolicyLocked();
410}
411
412const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700413 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
414 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800415 return *mCurrentRefreshRate;
416 }
Steven Thomasd4071902020-03-24 16:02:53 -0700417 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultConfig);
Ana Krulec5d477912020-02-07 12:02:38 -0800418}
419
Ady Abraham2139f732019-11-13 18:56:40 -0800420void RefreshRateConfigs::setCurrentConfigId(HwcConfigIndexType configId) {
421 std::lock_guard lock(mLock);
Ady Abraham2e1dd892020-03-05 13:48:36 -0800422 mCurrentRefreshRate = mRefreshRates.at(configId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800423}
424
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800425RefreshRateConfigs::RefreshRateConfigs(
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800426 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs,
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700427 HwcConfigIndexType currentConfigId)
428 : mKnownFrameRates(constructKnownFrameRates(configs)) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700429 LOG_ALWAYS_FATAL_IF(configs.empty());
430 LOG_ALWAYS_FATAL_IF(currentConfigId.value() >= configs.size());
431
432 for (auto configId = HwcConfigIndexType(0); configId.value() < configs.size(); configId++) {
433 const auto& config = configs.at(static_cast<size_t>(configId.value()));
Ady Abrahamabc27602020-04-08 17:20:29 -0700434 mRefreshRates.emplace(configId,
435 std::make_unique<RefreshRate>(configId, config,
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100436 Fps::fromPeriodNsecs(
437 config->getVsyncPeriod()),
Ady Abrahamabc27602020-04-08 17:20:29 -0700438 RefreshRate::ConstructorTag(0)));
439 if (configId == currentConfigId) {
440 mCurrentRefreshRate = mRefreshRates.at(configId).get();
441 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800442 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700443
444 std::vector<const RefreshRate*> sortedConfigs;
445 getSortedRefreshRateList([](const RefreshRate&) { return true; }, &sortedConfigs);
446 mDisplayManagerPolicy.defaultConfig = currentConfigId;
447 mMinSupportedRefreshRate = sortedConfigs.front();
448 mMaxSupportedRefreshRate = sortedConfigs.back();
449 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800450}
451
Steven Thomasd4071902020-03-24 16:02:53 -0700452bool RefreshRateConfigs::isPolicyValid(const Policy& policy) {
453 // defaultConfig must be a valid config, and within the given refresh rate range.
454 auto iter = mRefreshRates.find(policy.defaultConfig);
455 if (iter == mRefreshRates.end()) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100456 ALOGE("Default config is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700457 return false;
458 }
459 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700460 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100461 ALOGE("Default config is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700462 return false;
463 }
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100464 return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
465 policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
Steven Thomasd4071902020-03-24 16:02:53 -0700466}
467
468status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800469 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700470 if (!isPolicyValid(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100471 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100472 return BAD_VALUE;
473 }
Steven Thomasd4071902020-03-24 16:02:53 -0700474 Policy previousPolicy = *getCurrentPolicyLocked();
475 mDisplayManagerPolicy = policy;
476 if (*getCurrentPolicyLocked() == previousPolicy) {
477 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100478 }
Ady Abraham2139f732019-11-13 18:56:40 -0800479 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100480 return NO_ERROR;
481}
482
Steven Thomasd4071902020-03-24 16:02:53 -0700483status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100484 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700485 if (policy && !isPolicyValid(*policy)) {
486 return BAD_VALUE;
487 }
488 Policy previousPolicy = *getCurrentPolicyLocked();
489 mOverridePolicy = policy;
490 if (*getCurrentPolicyLocked() == previousPolicy) {
491 return CURRENT_POLICY_UNCHANGED;
492 }
493 constructAvailableRefreshRates();
494 return NO_ERROR;
495}
496
497const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
498 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
499}
500
501RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
502 std::lock_guard lock(mLock);
503 return *getCurrentPolicyLocked();
504}
505
506RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
507 std::lock_guard lock(mLock);
508 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100509}
510
511bool RefreshRateConfigs::isConfigAllowed(HwcConfigIndexType config) const {
512 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700513 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100514 if (refreshRate->configId == config) {
515 return true;
516 }
517 }
518 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800519}
520
521void RefreshRateConfigs::getSortedRefreshRateList(
522 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
523 std::vector<const RefreshRate*>* outRefreshRates) {
524 outRefreshRates->clear();
525 outRefreshRates->reserve(mRefreshRates.size());
526 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800527 if (shouldAddRefreshRate(*refreshRate)) {
Ady Abraham2139f732019-11-13 18:56:40 -0800528 ALOGV("getSortedRefreshRateList: config %d added to list policy",
Ady Abraham2e1dd892020-03-05 13:48:36 -0800529 refreshRate->configId.value());
530 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800531 }
532 }
533
534 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
535 [](const auto refreshRate1, const auto refreshRate2) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700536 if (refreshRate1->hwcConfig->getVsyncPeriod() !=
537 refreshRate2->hwcConfig->getVsyncPeriod()) {
538 return refreshRate1->hwcConfig->getVsyncPeriod() >
539 refreshRate2->hwcConfig->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700540 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -0700541 return refreshRate1->hwcConfig->getConfigGroup() >
542 refreshRate2->hwcConfig->getConfigGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700543 }
Ady Abraham2139f732019-11-13 18:56:40 -0800544 });
545}
546
547void RefreshRateConfigs::constructAvailableRefreshRates() {
548 // Filter configs based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700549 const Policy* policy = getCurrentPolicyLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700550 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig)->hwcConfig;
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100551 ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
Ady Abrahamabc27602020-04-08 17:20:29 -0700552
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100553 auto filterRefreshRates = [&](Fps min, Fps max, const char* listName,
Steven Thomasf734df42020-04-13 21:09:28 -0700554 std::vector<const RefreshRate*>* outRefreshRates) {
555 getSortedRefreshRateList(
556 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
557 const auto& hwcConfig = refreshRate.hwcConfig;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800558
Steven Thomasf734df42020-04-13 21:09:28 -0700559 return hwcConfig->getHeight() == defaultConfig->getHeight() &&
560 hwcConfig->getWidth() == defaultConfig->getWidth() &&
561 hwcConfig->getDpiX() == defaultConfig->getDpiX() &&
562 hwcConfig->getDpiY() == defaultConfig->getDpiY() &&
563 (policy->allowGroupSwitching ||
564 hwcConfig->getConfigGroup() == defaultConfig->getConfigGroup()) &&
565 refreshRate.inPolicy(min, max);
566 },
567 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800568
Steven Thomasf734df42020-04-13 21:09:28 -0700569 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100570 "No matching configs for %s range: min=%s max=%s", listName,
571 to_string(min).c_str(), to_string(max).c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700572 auto stringifyRefreshRates = [&]() -> std::string {
573 std::string str;
574 for (auto refreshRate : *outRefreshRates) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100575 base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700576 }
577 return str;
578 };
579 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
580 };
581
582 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
583 &mPrimaryRefreshRates);
584 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
585 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800586}
587
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100588std::vector<Fps> RefreshRateConfigs::constructKnownFrameRates(
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700589 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100590 std::vector<Fps> knownFrameRates = {Fps(24.0f), Fps(30.0f), Fps(45.0f), Fps(60.0f), Fps(72.0f)};
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700591 knownFrameRates.reserve(knownFrameRates.size() + configs.size());
592
593 // Add all supported refresh rates to the set
594 for (const auto& config : configs) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100595 const auto refreshRate = Fps::fromPeriodNsecs(config->getVsyncPeriod());
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700596 knownFrameRates.emplace_back(refreshRate);
597 }
598
599 // Sort and remove duplicates
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100600 std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700601 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100602 Fps::EqualsWithMargin()),
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700603 knownFrameRates.end());
604 return knownFrameRates;
605}
606
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100607Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
608 if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700609 return *mKnownFrameRates.begin();
610 }
611
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100612 if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700613 return *std::prev(mKnownFrameRates.end());
614 }
615
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100616 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
617 Fps::comparesLess);
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700618
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100619 const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
620 const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700621 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
622}
623
Ana Krulecb9afd792020-06-11 13:16:15 -0700624RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
625 std::lock_guard lock(mLock);
626 const auto& deviceMin = getMinRefreshRate();
627 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
628 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
629
630 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
631 // the min allowed refresh rate is higher than the device min, we do not want to enable the
632 // timer.
633 if (deviceMin < minByPolicy) {
634 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
635 }
636 if (minByPolicy == maxByPolicy) {
637 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
638 // max are all the same. This saves us extra unnecessary calls to sysprop.
639 if (deviceMin == minByPolicy) {
640 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
641 }
642 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
643 }
644 // Turn on the timer in all other cases.
645 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
646}
647
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000648void RefreshRateConfigs::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
649 if (frameRateOverride.frameRateHz > 0 && frameRateOverride.frameRateHz < 1) {
650 return;
651 }
652
653 std::lock_guard lock(mLock);
654 if (frameRateOverride.frameRateHz != 0) {
655 mPreferredRefreshRateForUid[frameRateOverride.uid] = Fps(frameRateOverride.frameRateHz);
656 } else {
657 mPreferredRefreshRateForUid.erase(frameRateOverride.uid);
658 }
659}
660
661int RefreshRateConfigs::getRefreshRateDividerForUid(uid_t uid) const {
662 std::lock_guard lock(mLock);
663
664 const auto iter = mPreferredRefreshRateForUid.find(uid);
665 if (iter == mPreferredRefreshRateForUid.end()) {
666 return 1;
667 }
668
Ady Abraham62f216c2020-10-13 19:07:23 -0700669 // This calculation needs to be in sync with the java code
670 // in DisplayManagerService.getDisplayInfoForFrameRateOverride
671 constexpr float kThreshold = 0.1f;
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000672 const auto refreshRateHz = iter->second;
673 const auto numPeriods = mCurrentRefreshRate->getFps().getValue() / refreshRateHz.getValue();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700674 const auto numPeriodsRounded = std::round(numPeriods);
675 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000676 return 1;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700677 }
678
Ady Abraham62f216c2020-10-13 19:07:23 -0700679 return static_cast<int>(numPeriodsRounded);
680}
681
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000682std::vector<FrameRateOverride> RefreshRateConfigs::getFrameRateOverrides() {
Ady Abraham62f216c2020-10-13 19:07:23 -0700683 std::lock_guard lock(mLock);
Ady Abrahamdbb6dcf2020-12-28 22:22:12 +0000684 std::vector<FrameRateOverride> overrides;
685 overrides.reserve(mPreferredRefreshRateForUid.size());
686
687 for (const auto [uid, frameRate] : mPreferredRefreshRateForUid) {
688 overrides.emplace_back(FrameRateOverride{uid, frameRate.getValue()});
689 }
690
691 return overrides;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700692}
693
Marin Shalamanovba421a82020-11-10 21:49:26 +0100694void RefreshRateConfigs::dump(std::string& result) const {
695 std::lock_guard lock(mLock);
696 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (DisplayManager): %s\n\n",
697 mDisplayManagerPolicy.toString().c_str());
698 scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
699 if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
700 base::StringAppendF(&result, "DesiredDisplayConfigSpecs (Override): %s\n\n",
701 currentPolicy.toString().c_str());
702 }
703
704 auto config = mCurrentRefreshRate->hwcConfig;
705 base::StringAppendF(&result, "Current config: %s\n", mCurrentRefreshRate->toString().c_str());
706
707 result.append("Refresh rates:\n");
708 for (const auto& [id, refreshRate] : mRefreshRates) {
709 config = refreshRate->hwcConfig;
710 base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
711 }
712
713 result.append("\n");
714}
715
Ady Abraham2139f732019-11-13 18:56:40 -0800716} // namespace android::scheduler