blob: 150f925fe00a55cf0c6fb7c2beefd93f2af6c758 [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 {
Ady Abraham2139f732019-11-13 18:56:40 -080030
31using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080032using RefreshRate = RefreshRateConfigs::RefreshRate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080033
Ady Abrahama6b676e2020-05-27 14:29:09 -070034std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
35 switch (vote) {
36 case LayerVoteType::NoVote:
37 return "NoVote";
38 case LayerVoteType::Min:
39 return "Min";
40 case LayerVoteType::Max:
41 return "Max";
42 case LayerVoteType::Heuristic:
43 return "Heuristic";
44 case LayerVoteType::ExplicitDefault:
45 return "ExplicitDefault";
46 case LayerVoteType::ExplicitExactOrMultiple:
47 return "ExplicitExactOrMultiple";
48 }
49}
50
Marin Shalamanovb6674e72020-11-06 13:05:57 +010051std::string RefreshRateConfigs::Policy::toString() const {
Marin Shalamanov30b0b3c2020-10-13 19:15:06 +020052 return base::StringPrintf("default config ID: %d, allowGroupSwitching = %d"
53 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]",
54 defaultConfig.value(), allowGroupSwitching, primaryRange.min,
55 primaryRange.max, appRequestRange.min, appRequestRange.max);
56}
57
Ady Abraham8a82ba62020-01-17 12:43:17 -080058const RefreshRate& RefreshRateConfigs::getRefreshRateForContent(
59 const std::vector<LayerRequirement>& layers) const {
Ady Abraham2139f732019-11-13 18:56:40 -080060 std::lock_guard lock(mLock);
Ady Abrahamdec1a412020-01-24 10:23:50 -080061 int contentFramerate = 0;
62 int explicitContentFramerate = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -080063 for (const auto& layer : layers) {
Ady Abrahamdec1a412020-01-24 10:23:50 -080064 const auto desiredRefreshRateRound = round<int>(layer.desiredRefreshRate);
Ady Abraham71c437d2020-01-31 15:56:57 -080065 if (layer.vote == LayerVoteType::ExplicitDefault ||
66 layer.vote == LayerVoteType::ExplicitExactOrMultiple) {
Ady Abrahamdec1a412020-01-24 10:23:50 -080067 if (desiredRefreshRateRound > explicitContentFramerate) {
68 explicitContentFramerate = desiredRefreshRateRound;
Ady Abraham8a82ba62020-01-17 12:43:17 -080069 }
70 } else {
Ady Abrahamdec1a412020-01-24 10:23:50 -080071 if (desiredRefreshRateRound > contentFramerate) {
72 contentFramerate = desiredRefreshRateRound;
Ady Abraham8a82ba62020-01-17 12:43:17 -080073 }
74 }
75 }
76
Ady Abrahamdec1a412020-01-24 10:23:50 -080077 if (explicitContentFramerate != 0) {
Ady Abraham8a82ba62020-01-17 12:43:17 -080078 contentFramerate = explicitContentFramerate;
Ady Abrahamdec1a412020-01-24 10:23:50 -080079 } else if (contentFramerate == 0) {
Ady Abrahamabc27602020-04-08 17:20:29 -070080 contentFramerate = round<int>(mMaxSupportedRefreshRate->getFps());
Ady Abraham8a82ba62020-01-17 12:43:17 -080081 }
Ady Abraham8a82ba62020-01-17 12:43:17 -080082 ATRACE_INT("ContentFPS", contentFramerate);
83
Ady Abraham2139f732019-11-13 18:56:40 -080084 // Find the appropriate refresh rate with minimal error
Steven Thomasf734df42020-04-13 21:09:28 -070085 auto iter = min_element(mPrimaryRefreshRates.cbegin(), mPrimaryRefreshRates.cend(),
Ady Abraham2139f732019-11-13 18:56:40 -080086 [contentFramerate](const auto& lhs, const auto& rhs) -> bool {
87 return std::abs(lhs->fps - contentFramerate) <
88 std::abs(rhs->fps - contentFramerate);
89 });
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080090
Ady Abraham2139f732019-11-13 18:56:40 -080091 // Some content aligns better on higher refresh rate. For example for 45fps we should choose
92 // 90Hz config. However we should still prefer a lower refresh rate if the content doesn't
93 // align well with both
94 const RefreshRate* bestSoFar = *iter;
95 constexpr float MARGIN = 0.05f;
96 float ratio = (*iter)->fps / contentFramerate;
97 if (std::abs(std::round(ratio) - ratio) > MARGIN) {
Steven Thomasf734df42020-04-13 21:09:28 -070098 while (iter != mPrimaryRefreshRates.cend()) {
Ady Abraham2139f732019-11-13 18:56:40 -080099 ratio = (*iter)->fps / contentFramerate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800100
Ady Abraham2139f732019-11-13 18:56:40 -0800101 if (std::abs(std::round(ratio) - ratio) <= MARGIN) {
102 bestSoFar = *iter;
103 break;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800104 }
Ady Abraham2139f732019-11-13 18:56:40 -0800105 ++iter;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800106 }
107 }
108
Ady Abraham2139f732019-11-13 18:56:40 -0800109 return *bestSoFar;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800110}
111
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800112std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
113 nsecs_t displayPeriod) const {
114 auto [displayFramesQuot, displayFramesRem] = std::div(layerPeriod, displayPeriod);
115 if (displayFramesRem <= MARGIN_FOR_PERIOD_CALCULATION ||
116 std::abs(displayFramesRem - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
117 displayFramesQuot++;
118 displayFramesRem = 0;
119 }
120
121 return {displayFramesQuot, displayFramesRem};
122}
123
Steven Thomasbb374322020-04-28 22:47:16 -0700124const RefreshRate& RefreshRateConfigs::getBestRefreshRate(
Ady Abrahamdfd62162020-06-10 16:11:56 -0700125 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
126 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800127 ATRACE_CALL();
128 ALOGV("getRefreshRateForContent %zu layers", layers.size());
129
Ady Abrahamdfd62162020-06-10 16:11:56 -0700130 if (outSignalsConsidered) *outSignalsConsidered = {};
131 const auto setTouchConsidered = [&] {
132 if (outSignalsConsidered) {
133 outSignalsConsidered->touch = true;
134 }
135 };
136
137 const auto setIdleConsidered = [&] {
138 if (outSignalsConsidered) {
139 outSignalsConsidered->idle = true;
140 }
141 };
142
Ady Abraham8a82ba62020-01-17 12:43:17 -0800143 std::lock_guard lock(mLock);
144
145 int noVoteLayers = 0;
146 int minVoteLayers = 0;
147 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800148 int explicitDefaultVoteLayers = 0;
149 int explicitExactOrMultipleVoteLayers = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800150 float maxExplicitWeight = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800151 for (const auto& layer : layers) {
Ady Abraham6fb599b2020-03-05 13:48:22 -0800152 if (layer.vote == LayerVoteType::NoVote) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800153 noVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800154 } else if (layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800155 minVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800156 } else if (layer.vote == LayerVoteType::Max) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800157 maxVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800158 } else if (layer.vote == LayerVoteType::ExplicitDefault) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800159 explicitDefaultVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800160 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
161 } else if (layer.vote == LayerVoteType::ExplicitExactOrMultiple) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800162 explicitExactOrMultipleVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800163 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
164 }
165 }
166
Alec Mouri11232a22020-05-14 18:06:25 -0700167 const bool hasExplicitVoteLayers =
168 explicitDefaultVoteLayers > 0 || explicitExactOrMultipleVoteLayers > 0;
169
Steven Thomasf734df42020-04-13 21:09:28 -0700170 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
171 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700172 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700173 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700174 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700175 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800176 }
177
Alec Mouri11232a22020-05-14 18:06:25 -0700178 // If the primary range consists of a single refresh rate then we can only
179 // move out the of range if layers explicitly request a different refresh
180 // rate.
181 const Policy* policy = getCurrentPolicyLocked();
182 const bool primaryRangeIsSingleRate = policy->primaryRange.min == policy->primaryRange.max;
183
Ady Abrahamdfd62162020-06-10 16:11:56 -0700184 if (!globalSignals.touch && globalSignals.idle &&
185 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700186 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700187 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700188 return getMinRefreshRateByPolicyLocked();
189 }
190
Steven Thomasdebafed2020-05-18 17:30:35 -0700191 if (layers.empty() || noVoteLayers == layers.size()) {
192 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700193 }
194
Ady Abraham8a82ba62020-01-17 12:43:17 -0800195 // Only if all layers want Min we should return Min
196 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700197 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700198 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800199 }
200
Ady Abraham8a82ba62020-01-17 12:43:17 -0800201 // Find the best refresh rate based on score
202 std::vector<std::pair<const RefreshRate*, float>> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700203 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800204
Steven Thomasf734df42020-04-13 21:09:28 -0700205 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800206 scores.emplace_back(refreshRate, 0.0f);
207 }
208
209 for (const auto& layer : layers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700210 ALOGV("Calculating score for %s (%s, weight %.2f)", layer.name.c_str(),
211 layerVoteTypeString(layer.vote).c_str(), layer.weight);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800212 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800213 continue;
214 }
215
Ady Abraham71c437d2020-01-31 15:56:57 -0800216 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800217
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800218 for (auto i = 0u; i < scores.size(); i++) {
Steven Thomasf734df42020-04-13 21:09:28 -0700219 bool inPrimaryRange =
220 scores[i].first->inPolicy(policy->primaryRange.min, policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700221 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abraham20c029c2020-07-06 12:58:05 -0700222 !(layer.focused && layer.vote == LayerVoteType::ExplicitDefault)) {
223 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700224 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700225 continue;
226 }
227
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800228 // If the layer wants Max, give higher score to the higher refresh rate
229 if (layer.vote == LayerVoteType::Max) {
230 const auto ratio = scores[i].first->fps / scores.back().first->fps;
231 // use ratio^2 to get a lower score the more we get further from peak
232 const auto layerScore = ratio * ratio;
233 ALOGV("%s (Max, weight %.2f) gives %s score of %.2f", layer.name.c_str(), weight,
234 scores[i].first->name.c_str(), layerScore);
235 scores[i].second += weight * layerScore;
236 continue;
Ady Abraham71c437d2020-01-31 15:56:57 -0800237 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800238
Ady Abrahamabc27602020-04-08 17:20:29 -0700239 const auto displayPeriod = scores[i].first->hwcConfig->getVsyncPeriod();
Ady Abrahamdec1a412020-01-24 10:23:50 -0800240 const auto layerPeriod = round<nsecs_t>(1e9f / layer.desiredRefreshRate);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800241 if (layer.vote == LayerVoteType::ExplicitDefault) {
242 const auto layerScore = [&]() {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800243 // Find the actual rate the layer will render, assuming
244 // that layerPeriod is the minimal time to render a frame
245 auto actualLayerPeriod = displayPeriod;
246 int multiplier = 1;
247 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
248 multiplier++;
249 actualLayerPeriod = displayPeriod * multiplier;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800250 }
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800251 return std::min(1.0f,
252 static_cast<float>(layerPeriod) /
253 static_cast<float>(actualLayerPeriod));
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800254 }();
255
256 ALOGV("%s (ExplicitDefault, weight %.2f) %.2fHz gives %s score of %.2f",
257 layer.name.c_str(), weight, 1e9f / layerPeriod, scores[i].first->name.c_str(),
258 layerScore);
259 scores[i].second += weight * layerScore;
260 continue;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800261 }
262
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800263 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
264 layer.vote == LayerVoteType::Heuristic) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700265 const auto layerScore = [&] {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800266 // Calculate how many display vsyncs we need to present a single frame for this
267 // layer
268 const auto [displayFramesQuot, displayFramesRem] =
269 getDisplayFrames(layerPeriod, displayPeriod);
270 static constexpr size_t MAX_FRAMES_TO_FIT =
271 10; // Stop calculating when score < 0.1
272 if (displayFramesRem == 0) {
273 // Layer desired refresh rate matches the display rate.
274 return 1.0f;
275 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800276
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800277 if (displayFramesQuot == 0) {
278 // Layer desired refresh rate is higher the display rate.
279 return (static_cast<float>(layerPeriod) /
280 static_cast<float>(displayPeriod)) *
281 (1.0f / (MAX_FRAMES_TO_FIT + 1));
282 }
283
284 // Layer desired refresh rate is lower the display rate. Check how well it fits
285 // the cadence
286 auto diff = std::abs(displayFramesRem - (displayPeriod - displayFramesRem));
287 int iter = 2;
288 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
289 diff = diff - (displayPeriod - diff);
290 iter++;
291 }
292
293 return 1.0f / iter;
294 }();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700295 ALOGV("%s (%s, weight %.2f) %.2fHz gives %s score of %.2f", layer.name.c_str(),
296 layerVoteTypeString(layer.vote).c_str(), weight, 1e9f / layerPeriod,
297 scores[i].first->name.c_str(), layerScore);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800298 scores[i].second += weight * layerScore;
299 continue;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800300 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800301 }
302 }
303
Ady Abraham34702102020-02-10 14:12:05 -0800304 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
305 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
306 // or the lower otherwise.
307 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
308 ? getBestRefreshRate(scores.rbegin(), scores.rend())
309 : getBestRefreshRate(scores.begin(), scores.end());
310
Alec Mouri11232a22020-05-14 18:06:25 -0700311 if (primaryRangeIsSingleRate) {
312 // If we never scored any layers, then choose the rate from the primary
313 // range instead of picking a random score from the app range.
314 if (std::all_of(scores.begin(), scores.end(),
315 [](std::pair<const RefreshRate*, float> p) { return p.second == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700316 ALOGV("layers not scored - choose %s",
317 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700318 return getMaxRefreshRateByPolicyLocked();
319 } else {
320 return *bestRefreshRate;
321 }
322 }
323
Steven Thomasf734df42020-04-13 21:09:28 -0700324 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
325 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
326 // vote we should not change it if we get a touch event. Only apply touch boost if it will
327 // actually increase the refresh rate over the normal selection.
328 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700329
Ady Abrahamdfd62162020-06-10 16:11:56 -0700330 if (globalSignals.touch && explicitDefaultVoteLayers == 0 &&
Steven Thomasf734df42020-04-13 21:09:28 -0700331 bestRefreshRate->fps < touchRefreshRate.fps) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700332 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700333 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700334 return touchRefreshRate;
335 }
336
Ady Abrahamde7156e2020-02-28 17:29:39 -0800337 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800338}
339
340template <typename Iter>
341const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800342 constexpr auto EPSILON = 0.001f;
Ady Abrahamde7156e2020-02-28 17:29:39 -0800343 const RefreshRate* bestRefreshRate = begin->first;
344 float max = begin->second;
Ady Abraham34702102020-02-10 14:12:05 -0800345 for (auto i = begin; i != end; ++i) {
346 const auto [refreshRate, score] = *i;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800347 ALOGV("%s scores %.2f", refreshRate->name.c_str(), score);
348
Ady Abrahamdec1a412020-01-24 10:23:50 -0800349 ATRACE_INT(refreshRate->name.c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800350
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800351 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800352 max = score;
353 bestRefreshRate = refreshRate;
354 }
355 }
356
Ady Abraham34702102020-02-10 14:12:05 -0800357 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800358}
359
Ady Abraham2139f732019-11-13 18:56:40 -0800360const AllRefreshRatesMapType& RefreshRateConfigs::getAllRefreshRates() const {
361 return mRefreshRates;
362}
363
364const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicy() const {
365 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700366 return getMinRefreshRateByPolicyLocked();
367}
368
369const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
370 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800371}
372
373const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
374 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700375 return getMaxRefreshRateByPolicyLocked();
376}
377
378const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
379 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800380}
381
382const RefreshRate& RefreshRateConfigs::getCurrentRefreshRate() const {
383 std::lock_guard lock(mLock);
384 return *mCurrentRefreshRate;
385}
386
Ana Krulec5d477912020-02-07 12:02:38 -0800387const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
388 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800389 return getCurrentRefreshRateByPolicyLocked();
390}
391
392const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700393 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
394 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800395 return *mCurrentRefreshRate;
396 }
Steven Thomasd4071902020-03-24 16:02:53 -0700397 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultConfig);
Ana Krulec5d477912020-02-07 12:02:38 -0800398}
399
Ady Abraham2139f732019-11-13 18:56:40 -0800400void RefreshRateConfigs::setCurrentConfigId(HwcConfigIndexType configId) {
401 std::lock_guard lock(mLock);
Ady Abraham2e1dd892020-03-05 13:48:36 -0800402 mCurrentRefreshRate = mRefreshRates.at(configId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800403}
404
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800405RefreshRateConfigs::RefreshRateConfigs(
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800406 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs,
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700407 HwcConfigIndexType currentConfigId)
408 : mKnownFrameRates(constructKnownFrameRates(configs)) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700409 LOG_ALWAYS_FATAL_IF(configs.empty());
410 LOG_ALWAYS_FATAL_IF(currentConfigId.value() >= configs.size());
411
412 for (auto configId = HwcConfigIndexType(0); configId.value() < configs.size(); configId++) {
413 const auto& config = configs.at(static_cast<size_t>(configId.value()));
414 const float fps = 1e9f / config->getVsyncPeriod();
415 mRefreshRates.emplace(configId,
416 std::make_unique<RefreshRate>(configId, config,
Steven Thomasf734df42020-04-13 21:09:28 -0700417 base::StringPrintf("%.0ffps", fps), fps,
Ady Abrahamabc27602020-04-08 17:20:29 -0700418 RefreshRate::ConstructorTag(0)));
419 if (configId == currentConfigId) {
420 mCurrentRefreshRate = mRefreshRates.at(configId).get();
421 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800422 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700423
424 std::vector<const RefreshRate*> sortedConfigs;
425 getSortedRefreshRateList([](const RefreshRate&) { return true; }, &sortedConfigs);
426 mDisplayManagerPolicy.defaultConfig = currentConfigId;
427 mMinSupportedRefreshRate = sortedConfigs.front();
428 mMaxSupportedRefreshRate = sortedConfigs.back();
429 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800430}
431
Steven Thomasd4071902020-03-24 16:02:53 -0700432bool RefreshRateConfigs::isPolicyValid(const Policy& policy) {
433 // defaultConfig must be a valid config, and within the given refresh rate range.
434 auto iter = mRefreshRates.find(policy.defaultConfig);
435 if (iter == mRefreshRates.end()) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100436 ALOGE("Default config is not found.");
Steven Thomasd4071902020-03-24 16:02:53 -0700437 return false;
438 }
439 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700440 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100441 ALOGE("Default config is not in the primary range.");
Steven Thomasd4071902020-03-24 16:02:53 -0700442 return false;
443 }
Steven Thomasf734df42020-04-13 21:09:28 -0700444 return policy.appRequestRange.min <= policy.primaryRange.min &&
445 policy.appRequestRange.max >= policy.primaryRange.max;
Steven Thomasd4071902020-03-24 16:02:53 -0700446}
447
448status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800449 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700450 if (!isPolicyValid(policy)) {
Marin Shalamanovb6674e72020-11-06 13:05:57 +0100451 ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100452 return BAD_VALUE;
453 }
Steven Thomasd4071902020-03-24 16:02:53 -0700454 Policy previousPolicy = *getCurrentPolicyLocked();
455 mDisplayManagerPolicy = policy;
456 if (*getCurrentPolicyLocked() == previousPolicy) {
457 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100458 }
Ady Abraham2139f732019-11-13 18:56:40 -0800459 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100460 return NO_ERROR;
461}
462
Steven Thomasd4071902020-03-24 16:02:53 -0700463status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100464 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700465 if (policy && !isPolicyValid(*policy)) {
466 return BAD_VALUE;
467 }
468 Policy previousPolicy = *getCurrentPolicyLocked();
469 mOverridePolicy = policy;
470 if (*getCurrentPolicyLocked() == previousPolicy) {
471 return CURRENT_POLICY_UNCHANGED;
472 }
473 constructAvailableRefreshRates();
474 return NO_ERROR;
475}
476
477const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
478 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
479}
480
481RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
482 std::lock_guard lock(mLock);
483 return *getCurrentPolicyLocked();
484}
485
486RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
487 std::lock_guard lock(mLock);
488 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100489}
490
491bool RefreshRateConfigs::isConfigAllowed(HwcConfigIndexType config) const {
492 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700493 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100494 if (refreshRate->configId == config) {
495 return true;
496 }
497 }
498 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800499}
500
501void RefreshRateConfigs::getSortedRefreshRateList(
502 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
503 std::vector<const RefreshRate*>* outRefreshRates) {
504 outRefreshRates->clear();
505 outRefreshRates->reserve(mRefreshRates.size());
506 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800507 if (shouldAddRefreshRate(*refreshRate)) {
Ady Abraham2139f732019-11-13 18:56:40 -0800508 ALOGV("getSortedRefreshRateList: config %d added to list policy",
Ady Abraham2e1dd892020-03-05 13:48:36 -0800509 refreshRate->configId.value());
510 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800511 }
512 }
513
514 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
515 [](const auto refreshRate1, const auto refreshRate2) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700516 if (refreshRate1->hwcConfig->getVsyncPeriod() !=
517 refreshRate2->hwcConfig->getVsyncPeriod()) {
518 return refreshRate1->hwcConfig->getVsyncPeriod() >
519 refreshRate2->hwcConfig->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700520 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -0700521 return refreshRate1->hwcConfig->getConfigGroup() >
522 refreshRate2->hwcConfig->getConfigGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700523 }
Ady Abraham2139f732019-11-13 18:56:40 -0800524 });
525}
526
527void RefreshRateConfigs::constructAvailableRefreshRates() {
528 // Filter configs based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700529 const Policy* policy = getCurrentPolicyLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700530 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig)->hwcConfig;
Steven Thomasf734df42020-04-13 21:09:28 -0700531 ALOGV("constructAvailableRefreshRates: default %d group %d primaryRange=[%.2f %.2f]"
532 " appRequestRange=[%.2f %.2f]",
533 policy->defaultConfig.value(), defaultConfig->getConfigGroup(), policy->primaryRange.min,
534 policy->primaryRange.max, policy->appRequestRange.min, policy->appRequestRange.max);
Ady Abrahamabc27602020-04-08 17:20:29 -0700535
Steven Thomasf734df42020-04-13 21:09:28 -0700536 auto filterRefreshRates = [&](float min, float max, const char* listName,
537 std::vector<const RefreshRate*>* outRefreshRates) {
538 getSortedRefreshRateList(
539 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
540 const auto& hwcConfig = refreshRate.hwcConfig;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800541
Steven Thomasf734df42020-04-13 21:09:28 -0700542 return hwcConfig->getHeight() == defaultConfig->getHeight() &&
543 hwcConfig->getWidth() == defaultConfig->getWidth() &&
544 hwcConfig->getDpiX() == defaultConfig->getDpiX() &&
545 hwcConfig->getDpiY() == defaultConfig->getDpiY() &&
546 (policy->allowGroupSwitching ||
547 hwcConfig->getConfigGroup() == defaultConfig->getConfigGroup()) &&
548 refreshRate.inPolicy(min, max);
549 },
550 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800551
Steven Thomasf734df42020-04-13 21:09:28 -0700552 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
553 "No matching configs for %s range: min=%.0f max=%.0f", listName, min,
554 max);
555 auto stringifyRefreshRates = [&]() -> std::string {
556 std::string str;
557 for (auto refreshRate : *outRefreshRates) {
558 base::StringAppendF(&str, "%s ", refreshRate->name.c_str());
559 }
560 return str;
561 };
562 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
563 };
564
565 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
566 &mPrimaryRefreshRates);
567 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
568 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800569}
570
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700571std::vector<float> RefreshRateConfigs::constructKnownFrameRates(
572 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs) {
573 std::vector<float> knownFrameRates = {24.0f, 30.0f, 45.0f, 60.0f, 72.0f};
574 knownFrameRates.reserve(knownFrameRates.size() + configs.size());
575
576 // Add all supported refresh rates to the set
577 for (const auto& config : configs) {
578 const auto refreshRate = 1e9f / config->getVsyncPeriod();
579 knownFrameRates.emplace_back(refreshRate);
580 }
581
582 // Sort and remove duplicates
583 const auto frameRatesEqual = [](float a, float b) { return std::abs(a - b) <= 0.01f; };
584 std::sort(knownFrameRates.begin(), knownFrameRates.end());
585 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
586 frameRatesEqual),
587 knownFrameRates.end());
588 return knownFrameRates;
589}
590
591float RefreshRateConfigs::findClosestKnownFrameRate(float frameRate) const {
592 if (frameRate <= *mKnownFrameRates.begin()) {
593 return *mKnownFrameRates.begin();
594 }
595
596 if (frameRate >= *std::prev(mKnownFrameRates.end())) {
597 return *std::prev(mKnownFrameRates.end());
598 }
599
600 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate);
601
602 const auto distance1 = std::abs(frameRate - *lowerBound);
603 const auto distance2 = std::abs(frameRate - *std::prev(lowerBound));
604 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
605}
606
Ana Krulecb9afd792020-06-11 13:16:15 -0700607RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
608 std::lock_guard lock(mLock);
609 const auto& deviceMin = getMinRefreshRate();
610 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
611 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
612
613 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
614 // the min allowed refresh rate is higher than the device min, we do not want to enable the
615 // timer.
616 if (deviceMin < minByPolicy) {
617 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
618 }
619 if (minByPolicy == maxByPolicy) {
620 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
621 // max are all the same. This saves us extra unnecessary calls to sysprop.
622 if (deviceMin == minByPolicy) {
623 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
624 }
625 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
626 }
627 // Turn on the timer in all other cases.
628 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
629}
630
Ady Abraham0bb6a472020-10-12 10:22:13 -0700631void RefreshRateConfigs::setPreferredRefreshRateForUid(uid_t uid, float refreshRateHz) {
632 if (refreshRateHz > 0 && refreshRateHz < 1) {
633 return;
634 }
635
636 std::lock_guard lock(mLock);
637 if (refreshRateHz != 0) {
638 mPreferredRefreshRateForUid[uid] = refreshRateHz;
639 } else {
640 mPreferredRefreshRateForUid.erase(uid);
641 }
642}
643
644int RefreshRateConfigs::getRefreshRateDividerForUid(uid_t uid) const {
645 constexpr float kThreshold = 0.1f;
646 std::lock_guard lock(mLock);
647
648 const auto iter = mPreferredRefreshRateForUid.find(uid);
649 if (iter == mPreferredRefreshRateForUid.end()) {
650 return 1;
651 }
652
653 const auto refreshRateHz = iter->second;
654 const auto numPeriods = mCurrentRefreshRate->getFps() / refreshRateHz;
655 const auto numPeriodsRounded = std::round(numPeriods);
656 if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
657 return 1;
658 }
659
660 return static_cast<int>(numPeriods);
661}
662
Ady Abraham2139f732019-11-13 18:56:40 -0800663} // namespace android::scheduler