blob: 053d0a7a39ce884ed29f4199abda7c8715b2bfb2 [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
Ady Abraham8a82ba62020-01-17 12:43:17 -080051const RefreshRate& RefreshRateConfigs::getRefreshRateForContent(
52 const std::vector<LayerRequirement>& layers) const {
Ady Abraham2139f732019-11-13 18:56:40 -080053 std::lock_guard lock(mLock);
Ady Abrahamdec1a412020-01-24 10:23:50 -080054 int contentFramerate = 0;
55 int explicitContentFramerate = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -080056 for (const auto& layer : layers) {
Ady Abrahamdec1a412020-01-24 10:23:50 -080057 const auto desiredRefreshRateRound = round<int>(layer.desiredRefreshRate);
Ady Abraham71c437d2020-01-31 15:56:57 -080058 if (layer.vote == LayerVoteType::ExplicitDefault ||
59 layer.vote == LayerVoteType::ExplicitExactOrMultiple) {
Ady Abrahamdec1a412020-01-24 10:23:50 -080060 if (desiredRefreshRateRound > explicitContentFramerate) {
61 explicitContentFramerate = desiredRefreshRateRound;
Ady Abraham8a82ba62020-01-17 12:43:17 -080062 }
63 } else {
Ady Abrahamdec1a412020-01-24 10:23:50 -080064 if (desiredRefreshRateRound > contentFramerate) {
65 contentFramerate = desiredRefreshRateRound;
Ady Abraham8a82ba62020-01-17 12:43:17 -080066 }
67 }
68 }
69
Ady Abrahamdec1a412020-01-24 10:23:50 -080070 if (explicitContentFramerate != 0) {
Ady Abraham8a82ba62020-01-17 12:43:17 -080071 contentFramerate = explicitContentFramerate;
Ady Abrahamdec1a412020-01-24 10:23:50 -080072 } else if (contentFramerate == 0) {
Ady Abrahamabc27602020-04-08 17:20:29 -070073 contentFramerate = round<int>(mMaxSupportedRefreshRate->getFps());
Ady Abraham8a82ba62020-01-17 12:43:17 -080074 }
Ady Abraham8a82ba62020-01-17 12:43:17 -080075 ATRACE_INT("ContentFPS", contentFramerate);
76
Ady Abraham2139f732019-11-13 18:56:40 -080077 // Find the appropriate refresh rate with minimal error
Steven Thomasf734df42020-04-13 21:09:28 -070078 auto iter = min_element(mPrimaryRefreshRates.cbegin(), mPrimaryRefreshRates.cend(),
Ady Abraham2139f732019-11-13 18:56:40 -080079 [contentFramerate](const auto& lhs, const auto& rhs) -> bool {
80 return std::abs(lhs->fps - contentFramerate) <
81 std::abs(rhs->fps - contentFramerate);
82 });
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080083
Ady Abraham2139f732019-11-13 18:56:40 -080084 // Some content aligns better on higher refresh rate. For example for 45fps we should choose
85 // 90Hz config. However we should still prefer a lower refresh rate if the content doesn't
86 // align well with both
87 const RefreshRate* bestSoFar = *iter;
88 constexpr float MARGIN = 0.05f;
89 float ratio = (*iter)->fps / contentFramerate;
90 if (std::abs(std::round(ratio) - ratio) > MARGIN) {
Steven Thomasf734df42020-04-13 21:09:28 -070091 while (iter != mPrimaryRefreshRates.cend()) {
Ady Abraham2139f732019-11-13 18:56:40 -080092 ratio = (*iter)->fps / contentFramerate;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080093
Ady Abraham2139f732019-11-13 18:56:40 -080094 if (std::abs(std::round(ratio) - ratio) <= MARGIN) {
95 bestSoFar = *iter;
96 break;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080097 }
Ady Abraham2139f732019-11-13 18:56:40 -080098 ++iter;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -080099 }
100 }
101
Ady Abraham2139f732019-11-13 18:56:40 -0800102 return *bestSoFar;
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800103}
104
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800105std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
106 nsecs_t displayPeriod) const {
107 auto [displayFramesQuot, displayFramesRem] = std::div(layerPeriod, displayPeriod);
108 if (displayFramesRem <= MARGIN_FOR_PERIOD_CALCULATION ||
109 std::abs(displayFramesRem - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
110 displayFramesQuot++;
111 displayFramesRem = 0;
112 }
113
114 return {displayFramesQuot, displayFramesRem};
115}
116
Steven Thomasbb374322020-04-28 22:47:16 -0700117const RefreshRate& RefreshRateConfigs::getBestRefreshRate(
Ady Abrahamdfd62162020-06-10 16:11:56 -0700118 const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
119 GlobalSignals* outSignalsConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800120 ATRACE_CALL();
121 ALOGV("getRefreshRateForContent %zu layers", layers.size());
122
Ady Abrahamdfd62162020-06-10 16:11:56 -0700123 if (outSignalsConsidered) *outSignalsConsidered = {};
124 const auto setTouchConsidered = [&] {
125 if (outSignalsConsidered) {
126 outSignalsConsidered->touch = true;
127 }
128 };
129
130 const auto setIdleConsidered = [&] {
131 if (outSignalsConsidered) {
132 outSignalsConsidered->idle = true;
133 }
134 };
135
Ady Abraham8a82ba62020-01-17 12:43:17 -0800136 std::lock_guard lock(mLock);
137
138 int noVoteLayers = 0;
139 int minVoteLayers = 0;
140 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800141 int explicitDefaultVoteLayers = 0;
142 int explicitExactOrMultipleVoteLayers = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800143 float maxExplicitWeight = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800144 for (const auto& layer : layers) {
Ady Abraham6fb599b2020-03-05 13:48:22 -0800145 if (layer.vote == LayerVoteType::NoVote) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800146 noVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800147 } else if (layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800148 minVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800149 } else if (layer.vote == LayerVoteType::Max) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800150 maxVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800151 } else if (layer.vote == LayerVoteType::ExplicitDefault) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800152 explicitDefaultVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800153 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
154 } else if (layer.vote == LayerVoteType::ExplicitExactOrMultiple) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800155 explicitExactOrMultipleVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800156 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
157 }
158 }
159
Alec Mouri11232a22020-05-14 18:06:25 -0700160 const bool hasExplicitVoteLayers =
161 explicitDefaultVoteLayers > 0 || explicitExactOrMultipleVoteLayers > 0;
162
Steven Thomasf734df42020-04-13 21:09:28 -0700163 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
164 // selected a refresh rate to see if we should apply touch boost.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700165 if (globalSignals.touch && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700166 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700167 setTouchConsidered();
Steven Thomasf734df42020-04-13 21:09:28 -0700168 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800169 }
170
Alec Mouri11232a22020-05-14 18:06:25 -0700171 // If the primary range consists of a single refresh rate then we can only
172 // move out the of range if layers explicitly request a different refresh
173 // rate.
174 const Policy* policy = getCurrentPolicyLocked();
175 const bool primaryRangeIsSingleRate = policy->primaryRange.min == policy->primaryRange.max;
176
Ady Abrahamdfd62162020-06-10 16:11:56 -0700177 if (!globalSignals.touch && globalSignals.idle &&
178 !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700179 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Ady Abrahamdfd62162020-06-10 16:11:56 -0700180 setIdleConsidered();
Steven Thomasbb374322020-04-28 22:47:16 -0700181 return getMinRefreshRateByPolicyLocked();
182 }
183
Steven Thomasdebafed2020-05-18 17:30:35 -0700184 if (layers.empty() || noVoteLayers == layers.size()) {
185 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700186 }
187
Ady Abraham8a82ba62020-01-17 12:43:17 -0800188 // Only if all layers want Min we should return Min
189 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700190 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700191 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800192 }
193
Ady Abraham8a82ba62020-01-17 12:43:17 -0800194 // Find the best refresh rate based on score
195 std::vector<std::pair<const RefreshRate*, float>> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700196 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800197
Steven Thomasf734df42020-04-13 21:09:28 -0700198 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800199 scores.emplace_back(refreshRate, 0.0f);
200 }
201
202 for (const auto& layer : layers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700203 ALOGV("Calculating score for %s (%s, weight %.2f)", layer.name.c_str(),
204 layerVoteTypeString(layer.vote).c_str(), layer.weight);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800205 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800206 continue;
207 }
208
Ady Abraham71c437d2020-01-31 15:56:57 -0800209 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800210
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800211 for (auto i = 0u; i < scores.size(); i++) {
Steven Thomasf734df42020-04-13 21:09:28 -0700212 bool inPrimaryRange =
213 scores[i].first->inPolicy(policy->primaryRange.min, policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700214 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700215 !(layer.focused &&
216 (layer.vote == LayerVoteType::ExplicitDefault ||
217 layer.vote == LayerVoteType::ExplicitExactOrMultiple))) {
218 // Only focused layers with explicit frame rate settings are allowed to score
219 // refresh rates outside the primary range.
Steven Thomasf734df42020-04-13 21:09:28 -0700220 continue;
221 }
222
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800223 // If the layer wants Max, give higher score to the higher refresh rate
224 if (layer.vote == LayerVoteType::Max) {
225 const auto ratio = scores[i].first->fps / scores.back().first->fps;
226 // use ratio^2 to get a lower score the more we get further from peak
227 const auto layerScore = ratio * ratio;
228 ALOGV("%s (Max, weight %.2f) gives %s score of %.2f", layer.name.c_str(), weight,
229 scores[i].first->name.c_str(), layerScore);
230 scores[i].second += weight * layerScore;
231 continue;
Ady Abraham71c437d2020-01-31 15:56:57 -0800232 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800233
Ady Abrahamabc27602020-04-08 17:20:29 -0700234 const auto displayPeriod = scores[i].first->hwcConfig->getVsyncPeriod();
Ady Abrahamdec1a412020-01-24 10:23:50 -0800235 const auto layerPeriod = round<nsecs_t>(1e9f / layer.desiredRefreshRate);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800236 if (layer.vote == LayerVoteType::ExplicitDefault) {
237 const auto layerScore = [&]() {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800238 // Find the actual rate the layer will render, assuming
239 // that layerPeriod is the minimal time to render a frame
240 auto actualLayerPeriod = displayPeriod;
241 int multiplier = 1;
242 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
243 multiplier++;
244 actualLayerPeriod = displayPeriod * multiplier;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800245 }
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800246 return std::min(1.0f,
247 static_cast<float>(layerPeriod) /
248 static_cast<float>(actualLayerPeriod));
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800249 }();
250
251 ALOGV("%s (ExplicitDefault, weight %.2f) %.2fHz gives %s score of %.2f",
252 layer.name.c_str(), weight, 1e9f / layerPeriod, scores[i].first->name.c_str(),
253 layerScore);
254 scores[i].second += weight * layerScore;
255 continue;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800256 }
257
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800258 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
259 layer.vote == LayerVoteType::Heuristic) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700260 const auto layerScore = [&] {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800261 // Calculate how many display vsyncs we need to present a single frame for this
262 // layer
263 const auto [displayFramesQuot, displayFramesRem] =
264 getDisplayFrames(layerPeriod, displayPeriod);
265 static constexpr size_t MAX_FRAMES_TO_FIT =
266 10; // Stop calculating when score < 0.1
267 if (displayFramesRem == 0) {
268 // Layer desired refresh rate matches the display rate.
269 return 1.0f;
270 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800271
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800272 if (displayFramesQuot == 0) {
273 // Layer desired refresh rate is higher the display rate.
274 return (static_cast<float>(layerPeriod) /
275 static_cast<float>(displayPeriod)) *
276 (1.0f / (MAX_FRAMES_TO_FIT + 1));
277 }
278
279 // Layer desired refresh rate is lower the display rate. Check how well it fits
280 // the cadence
281 auto diff = std::abs(displayFramesRem - (displayPeriod - displayFramesRem));
282 int iter = 2;
283 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
284 diff = diff - (displayPeriod - diff);
285 iter++;
286 }
287
288 return 1.0f / iter;
289 }();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700290 ALOGV("%s (%s, weight %.2f) %.2fHz gives %s score of %.2f", layer.name.c_str(),
291 layerVoteTypeString(layer.vote).c_str(), weight, 1e9f / layerPeriod,
292 scores[i].first->name.c_str(), layerScore);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800293 scores[i].second += weight * layerScore;
294 continue;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800295 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800296 }
297 }
298
Ady Abraham34702102020-02-10 14:12:05 -0800299 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
300 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
301 // or the lower otherwise.
302 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
303 ? getBestRefreshRate(scores.rbegin(), scores.rend())
304 : getBestRefreshRate(scores.begin(), scores.end());
305
Alec Mouri11232a22020-05-14 18:06:25 -0700306 if (primaryRangeIsSingleRate) {
307 // If we never scored any layers, then choose the rate from the primary
308 // range instead of picking a random score from the app range.
309 if (std::all_of(scores.begin(), scores.end(),
310 [](std::pair<const RefreshRate*, float> p) { return p.second == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700311 ALOGV("layers not scored - choose %s",
312 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700313 return getMaxRefreshRateByPolicyLocked();
314 } else {
315 return *bestRefreshRate;
316 }
317 }
318
Steven Thomasf734df42020-04-13 21:09:28 -0700319 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
320 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
321 // vote we should not change it if we get a touch event. Only apply touch boost if it will
322 // actually increase the refresh rate over the normal selection.
323 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700324
Ady Abrahamdfd62162020-06-10 16:11:56 -0700325 if (globalSignals.touch && explicitDefaultVoteLayers == 0 &&
Steven Thomasf734df42020-04-13 21:09:28 -0700326 bestRefreshRate->fps < touchRefreshRate.fps) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700327 setTouchConsidered();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700328 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700329 return touchRefreshRate;
330 }
331
Ady Abrahamde7156e2020-02-28 17:29:39 -0800332 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800333}
334
335template <typename Iter>
336const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800337 constexpr auto EPSILON = 0.001f;
Ady Abrahamde7156e2020-02-28 17:29:39 -0800338 const RefreshRate* bestRefreshRate = begin->first;
339 float max = begin->second;
Ady Abraham34702102020-02-10 14:12:05 -0800340 for (auto i = begin; i != end; ++i) {
341 const auto [refreshRate, score] = *i;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800342 ALOGV("%s scores %.2f", refreshRate->name.c_str(), score);
343
Ady Abrahamdec1a412020-01-24 10:23:50 -0800344 ATRACE_INT(refreshRate->name.c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800345
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800346 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800347 max = score;
348 bestRefreshRate = refreshRate;
349 }
350 }
351
Ady Abraham34702102020-02-10 14:12:05 -0800352 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800353}
354
Ady Abraham2139f732019-11-13 18:56:40 -0800355const AllRefreshRatesMapType& RefreshRateConfigs::getAllRefreshRates() const {
356 return mRefreshRates;
357}
358
359const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicy() const {
360 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700361 return getMinRefreshRateByPolicyLocked();
362}
363
364const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
365 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800366}
367
368const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
369 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700370 return getMaxRefreshRateByPolicyLocked();
371}
372
373const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
374 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800375}
376
377const RefreshRate& RefreshRateConfigs::getCurrentRefreshRate() const {
378 std::lock_guard lock(mLock);
379 return *mCurrentRefreshRate;
380}
381
Ana Krulec5d477912020-02-07 12:02:38 -0800382const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
383 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800384 return getCurrentRefreshRateByPolicyLocked();
385}
386
387const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700388 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
389 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800390 return *mCurrentRefreshRate;
391 }
Steven Thomasd4071902020-03-24 16:02:53 -0700392 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultConfig);
Ana Krulec5d477912020-02-07 12:02:38 -0800393}
394
Ady Abraham2139f732019-11-13 18:56:40 -0800395void RefreshRateConfigs::setCurrentConfigId(HwcConfigIndexType configId) {
396 std::lock_guard lock(mLock);
Ady Abraham2e1dd892020-03-05 13:48:36 -0800397 mCurrentRefreshRate = mRefreshRates.at(configId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800398}
399
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800400RefreshRateConfigs::RefreshRateConfigs(
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800401 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs,
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700402 HwcConfigIndexType currentConfigId)
403 : mKnownFrameRates(constructKnownFrameRates(configs)) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700404 LOG_ALWAYS_FATAL_IF(configs.empty());
405 LOG_ALWAYS_FATAL_IF(currentConfigId.value() >= configs.size());
406
407 for (auto configId = HwcConfigIndexType(0); configId.value() < configs.size(); configId++) {
408 const auto& config = configs.at(static_cast<size_t>(configId.value()));
409 const float fps = 1e9f / config->getVsyncPeriod();
410 mRefreshRates.emplace(configId,
411 std::make_unique<RefreshRate>(configId, config,
Steven Thomasf734df42020-04-13 21:09:28 -0700412 base::StringPrintf("%.0ffps", fps), fps,
Ady Abrahamabc27602020-04-08 17:20:29 -0700413 RefreshRate::ConstructorTag(0)));
414 if (configId == currentConfigId) {
415 mCurrentRefreshRate = mRefreshRates.at(configId).get();
416 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800417 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700418
419 std::vector<const RefreshRate*> sortedConfigs;
420 getSortedRefreshRateList([](const RefreshRate&) { return true; }, &sortedConfigs);
421 mDisplayManagerPolicy.defaultConfig = currentConfigId;
422 mMinSupportedRefreshRate = sortedConfigs.front();
423 mMaxSupportedRefreshRate = sortedConfigs.back();
424 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800425}
426
Steven Thomasd4071902020-03-24 16:02:53 -0700427bool RefreshRateConfigs::isPolicyValid(const Policy& policy) {
428 // defaultConfig must be a valid config, and within the given refresh rate range.
429 auto iter = mRefreshRates.find(policy.defaultConfig);
430 if (iter == mRefreshRates.end()) {
431 return false;
432 }
433 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700434 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700435 return false;
436 }
Steven Thomasf734df42020-04-13 21:09:28 -0700437 return policy.appRequestRange.min <= policy.primaryRange.min &&
438 policy.appRequestRange.max >= policy.primaryRange.max;
Steven Thomasd4071902020-03-24 16:02:53 -0700439}
440
441status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800442 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700443 if (!isPolicyValid(policy)) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100444 return BAD_VALUE;
445 }
Steven Thomasd4071902020-03-24 16:02:53 -0700446 Policy previousPolicy = *getCurrentPolicyLocked();
447 mDisplayManagerPolicy = policy;
448 if (*getCurrentPolicyLocked() == previousPolicy) {
449 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100450 }
Ady Abraham2139f732019-11-13 18:56:40 -0800451 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100452 return NO_ERROR;
453}
454
Steven Thomasd4071902020-03-24 16:02:53 -0700455status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100456 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700457 if (policy && !isPolicyValid(*policy)) {
458 return BAD_VALUE;
459 }
460 Policy previousPolicy = *getCurrentPolicyLocked();
461 mOverridePolicy = policy;
462 if (*getCurrentPolicyLocked() == previousPolicy) {
463 return CURRENT_POLICY_UNCHANGED;
464 }
465 constructAvailableRefreshRates();
466 return NO_ERROR;
467}
468
469const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
470 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
471}
472
473RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
474 std::lock_guard lock(mLock);
475 return *getCurrentPolicyLocked();
476}
477
478RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
479 std::lock_guard lock(mLock);
480 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100481}
482
483bool RefreshRateConfigs::isConfigAllowed(HwcConfigIndexType config) const {
484 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700485 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100486 if (refreshRate->configId == config) {
487 return true;
488 }
489 }
490 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800491}
492
493void RefreshRateConfigs::getSortedRefreshRateList(
494 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
495 std::vector<const RefreshRate*>* outRefreshRates) {
496 outRefreshRates->clear();
497 outRefreshRates->reserve(mRefreshRates.size());
498 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800499 if (shouldAddRefreshRate(*refreshRate)) {
Ady Abraham2139f732019-11-13 18:56:40 -0800500 ALOGV("getSortedRefreshRateList: config %d added to list policy",
Ady Abraham2e1dd892020-03-05 13:48:36 -0800501 refreshRate->configId.value());
502 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800503 }
504 }
505
506 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
507 [](const auto refreshRate1, const auto refreshRate2) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700508 if (refreshRate1->hwcConfig->getVsyncPeriod() !=
509 refreshRate2->hwcConfig->getVsyncPeriod()) {
510 return refreshRate1->hwcConfig->getVsyncPeriod() >
511 refreshRate2->hwcConfig->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700512 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -0700513 return refreshRate1->hwcConfig->getConfigGroup() >
514 refreshRate2->hwcConfig->getConfigGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700515 }
Ady Abraham2139f732019-11-13 18:56:40 -0800516 });
517}
518
519void RefreshRateConfigs::constructAvailableRefreshRates() {
520 // Filter configs based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700521 const Policy* policy = getCurrentPolicyLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700522 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig)->hwcConfig;
Steven Thomasf734df42020-04-13 21:09:28 -0700523 ALOGV("constructAvailableRefreshRates: default %d group %d primaryRange=[%.2f %.2f]"
524 " appRequestRange=[%.2f %.2f]",
525 policy->defaultConfig.value(), defaultConfig->getConfigGroup(), policy->primaryRange.min,
526 policy->primaryRange.max, policy->appRequestRange.min, policy->appRequestRange.max);
Ady Abrahamabc27602020-04-08 17:20:29 -0700527
Steven Thomasf734df42020-04-13 21:09:28 -0700528 auto filterRefreshRates = [&](float min, float max, const char* listName,
529 std::vector<const RefreshRate*>* outRefreshRates) {
530 getSortedRefreshRateList(
531 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
532 const auto& hwcConfig = refreshRate.hwcConfig;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800533
Steven Thomasf734df42020-04-13 21:09:28 -0700534 return hwcConfig->getHeight() == defaultConfig->getHeight() &&
535 hwcConfig->getWidth() == defaultConfig->getWidth() &&
536 hwcConfig->getDpiX() == defaultConfig->getDpiX() &&
537 hwcConfig->getDpiY() == defaultConfig->getDpiY() &&
538 (policy->allowGroupSwitching ||
539 hwcConfig->getConfigGroup() == defaultConfig->getConfigGroup()) &&
540 refreshRate.inPolicy(min, max);
541 },
542 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800543
Steven Thomasf734df42020-04-13 21:09:28 -0700544 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
545 "No matching configs for %s range: min=%.0f max=%.0f", listName, min,
546 max);
547 auto stringifyRefreshRates = [&]() -> std::string {
548 std::string str;
549 for (auto refreshRate : *outRefreshRates) {
550 base::StringAppendF(&str, "%s ", refreshRate->name.c_str());
551 }
552 return str;
553 };
554 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
555 };
556
557 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
558 &mPrimaryRefreshRates);
559 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
560 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800561}
562
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700563std::vector<float> RefreshRateConfigs::constructKnownFrameRates(
564 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs) {
565 std::vector<float> knownFrameRates = {24.0f, 30.0f, 45.0f, 60.0f, 72.0f};
566 knownFrameRates.reserve(knownFrameRates.size() + configs.size());
567
568 // Add all supported refresh rates to the set
569 for (const auto& config : configs) {
570 const auto refreshRate = 1e9f / config->getVsyncPeriod();
571 knownFrameRates.emplace_back(refreshRate);
572 }
573
574 // Sort and remove duplicates
575 const auto frameRatesEqual = [](float a, float b) { return std::abs(a - b) <= 0.01f; };
576 std::sort(knownFrameRates.begin(), knownFrameRates.end());
577 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
578 frameRatesEqual),
579 knownFrameRates.end());
580 return knownFrameRates;
581}
582
583float RefreshRateConfigs::findClosestKnownFrameRate(float frameRate) const {
584 if (frameRate <= *mKnownFrameRates.begin()) {
585 return *mKnownFrameRates.begin();
586 }
587
588 if (frameRate >= *std::prev(mKnownFrameRates.end())) {
589 return *std::prev(mKnownFrameRates.end());
590 }
591
592 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate);
593
594 const auto distance1 = std::abs(frameRate - *lowerBound);
595 const auto distance2 = std::abs(frameRate - *std::prev(lowerBound));
596 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
597}
598
Ana Krulecb9afd792020-06-11 13:16:15 -0700599RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
600 std::lock_guard lock(mLock);
601 const auto& deviceMin = getMinRefreshRate();
602 const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
603 const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
604
605 // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
606 // the min allowed refresh rate is higher than the device min, we do not want to enable the
607 // timer.
608 if (deviceMin < minByPolicy) {
609 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
610 }
611 if (minByPolicy == maxByPolicy) {
612 // Do not sent the call to toggle off kernel idle timer if the device min and policy min and
613 // max are all the same. This saves us extra unnecessary calls to sysprop.
614 if (deviceMin == minByPolicy) {
615 return RefreshRateConfigs::KernelIdleTimerAction::NoChange;
616 }
617 return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
618 }
619 // Turn on the timer in all other cases.
620 return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
621}
622
Ady Abraham2139f732019-11-13 18:56:40 -0800623} // namespace android::scheduler