blob: ea279552871d87d6e7f9616cf7ae285563084913 [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(
118 const std::vector<LayerRequirement>& layers, bool touchActive, bool idle,
Ady Abraham6fb599b2020-03-05 13:48:22 -0800119 bool* touchConsidered) const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800120 ATRACE_CALL();
121 ALOGV("getRefreshRateForContent %zu layers", layers.size());
122
Ady Abrahama6b676e2020-05-27 14:29:09 -0700123 if (touchConsidered) *touchConsidered = false;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800124 std::lock_guard lock(mLock);
125
126 int noVoteLayers = 0;
127 int minVoteLayers = 0;
128 int maxVoteLayers = 0;
Ady Abraham71c437d2020-01-31 15:56:57 -0800129 int explicitDefaultVoteLayers = 0;
130 int explicitExactOrMultipleVoteLayers = 0;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800131 float maxExplicitWeight = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800132 for (const auto& layer : layers) {
Ady Abraham6fb599b2020-03-05 13:48:22 -0800133 if (layer.vote == LayerVoteType::NoVote) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800134 noVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800135 } else if (layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800136 minVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800137 } else if (layer.vote == LayerVoteType::Max) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800138 maxVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800139 } else if (layer.vote == LayerVoteType::ExplicitDefault) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800140 explicitDefaultVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800141 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
142 } else if (layer.vote == LayerVoteType::ExplicitExactOrMultiple) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800143 explicitExactOrMultipleVoteLayers++;
Ady Abraham6fb599b2020-03-05 13:48:22 -0800144 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
145 }
146 }
147
Alec Mouri11232a22020-05-14 18:06:25 -0700148 const bool hasExplicitVoteLayers =
149 explicitDefaultVoteLayers > 0 || explicitExactOrMultipleVoteLayers > 0;
150
Steven Thomasf734df42020-04-13 21:09:28 -0700151 // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
152 // selected a refresh rate to see if we should apply touch boost.
Alec Mouri11232a22020-05-14 18:06:25 -0700153 if (touchActive && !hasExplicitVoteLayers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700154 ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
155 if (touchConsidered) *touchConsidered = true;
Steven Thomasf734df42020-04-13 21:09:28 -0700156 return getMaxRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800157 }
158
Alec Mouri11232a22020-05-14 18:06:25 -0700159 // If the primary range consists of a single refresh rate then we can only
160 // move out the of range if layers explicitly request a different refresh
161 // rate.
162 const Policy* policy = getCurrentPolicyLocked();
163 const bool primaryRangeIsSingleRate = policy->primaryRange.min == policy->primaryRange.max;
164
165 if (!touchActive && idle && !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700166 ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasbb374322020-04-28 22:47:16 -0700167 return getMinRefreshRateByPolicyLocked();
168 }
169
Steven Thomasdebafed2020-05-18 17:30:35 -0700170 if (layers.empty() || noVoteLayers == layers.size()) {
171 return getMaxRefreshRateByPolicyLocked();
Steven Thomasbb374322020-04-28 22:47:16 -0700172 }
173
Ady Abraham8a82ba62020-01-17 12:43:17 -0800174 // Only if all layers want Min we should return Min
175 if (noVoteLayers + minVoteLayers == layers.size()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700176 ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700177 return getMinRefreshRateByPolicyLocked();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800178 }
179
Ady Abraham8a82ba62020-01-17 12:43:17 -0800180 // Find the best refresh rate based on score
181 std::vector<std::pair<const RefreshRate*, float>> scores;
Steven Thomasf734df42020-04-13 21:09:28 -0700182 scores.reserve(mAppRequestRefreshRates.size());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800183
Steven Thomasf734df42020-04-13 21:09:28 -0700184 for (const auto refreshRate : mAppRequestRefreshRates) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800185 scores.emplace_back(refreshRate, 0.0f);
186 }
187
188 for (const auto& layer : layers) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700189 ALOGV("Calculating score for %s (%s, weight %.2f)", layer.name.c_str(),
190 layerVoteTypeString(layer.vote).c_str(), layer.weight);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800191 if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800192 continue;
193 }
194
Ady Abraham71c437d2020-01-31 15:56:57 -0800195 auto weight = layer.weight;
Ady Abraham71c437d2020-01-31 15:56:57 -0800196
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800197 for (auto i = 0u; i < scores.size(); i++) {
Steven Thomasf734df42020-04-13 21:09:28 -0700198 bool inPrimaryRange =
199 scores[i].first->inPolicy(policy->primaryRange.min, policy->primaryRange.max);
Alec Mouri11232a22020-05-14 18:06:25 -0700200 if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
201 layer.vote != LayerVoteType::ExplicitDefault &&
Steven Thomasf734df42020-04-13 21:09:28 -0700202 layer.vote != LayerVoteType::ExplicitExactOrMultiple) {
203 // Only layers with explicit frame rate settings are allowed to score refresh rates
204 // outside the primary range.
205 continue;
206 }
207
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800208 // If the layer wants Max, give higher score to the higher refresh rate
209 if (layer.vote == LayerVoteType::Max) {
210 const auto ratio = scores[i].first->fps / scores.back().first->fps;
211 // use ratio^2 to get a lower score the more we get further from peak
212 const auto layerScore = ratio * ratio;
213 ALOGV("%s (Max, weight %.2f) gives %s score of %.2f", layer.name.c_str(), weight,
214 scores[i].first->name.c_str(), layerScore);
215 scores[i].second += weight * layerScore;
216 continue;
Ady Abraham71c437d2020-01-31 15:56:57 -0800217 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800218
Ady Abrahamabc27602020-04-08 17:20:29 -0700219 const auto displayPeriod = scores[i].first->hwcConfig->getVsyncPeriod();
Ady Abrahamdec1a412020-01-24 10:23:50 -0800220 const auto layerPeriod = round<nsecs_t>(1e9f / layer.desiredRefreshRate);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800221 if (layer.vote == LayerVoteType::ExplicitDefault) {
222 const auto layerScore = [&]() {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800223 // Find the actual rate the layer will render, assuming
224 // that layerPeriod is the minimal time to render a frame
225 auto actualLayerPeriod = displayPeriod;
226 int multiplier = 1;
227 while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
228 multiplier++;
229 actualLayerPeriod = displayPeriod * multiplier;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800230 }
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800231 return std::min(1.0f,
232 static_cast<float>(layerPeriod) /
233 static_cast<float>(actualLayerPeriod));
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800234 }();
235
236 ALOGV("%s (ExplicitDefault, weight %.2f) %.2fHz gives %s score of %.2f",
237 layer.name.c_str(), weight, 1e9f / layerPeriod, scores[i].first->name.c_str(),
238 layerScore);
239 scores[i].second += weight * layerScore;
240 continue;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800241 }
242
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800243 if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
244 layer.vote == LayerVoteType::Heuristic) {
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700245 const auto layerScore = [&] {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800246 // Calculate how many display vsyncs we need to present a single frame for this
247 // layer
248 const auto [displayFramesQuot, displayFramesRem] =
249 getDisplayFrames(layerPeriod, displayPeriod);
250 static constexpr size_t MAX_FRAMES_TO_FIT =
251 10; // Stop calculating when score < 0.1
252 if (displayFramesRem == 0) {
253 // Layer desired refresh rate matches the display rate.
254 return 1.0f;
255 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800256
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800257 if (displayFramesQuot == 0) {
258 // Layer desired refresh rate is higher the display rate.
259 return (static_cast<float>(layerPeriod) /
260 static_cast<float>(displayPeriod)) *
261 (1.0f / (MAX_FRAMES_TO_FIT + 1));
262 }
263
264 // Layer desired refresh rate is lower the display rate. Check how well it fits
265 // the cadence
266 auto diff = std::abs(displayFramesRem - (displayPeriod - displayFramesRem));
267 int iter = 2;
268 while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
269 diff = diff - (displayPeriod - diff);
270 iter++;
271 }
272
273 return 1.0f / iter;
274 }();
Ady Abrahama6b676e2020-05-27 14:29:09 -0700275 ALOGV("%s (%s, weight %.2f) %.2fHz gives %s score of %.2f", layer.name.c_str(),
276 layerVoteTypeString(layer.vote).c_str(), weight, 1e9f / layerPeriod,
277 scores[i].first->name.c_str(), layerScore);
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800278 scores[i].second += weight * layerScore;
279 continue;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800280 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800281 }
282 }
283
Ady Abraham34702102020-02-10 14:12:05 -0800284 // Now that we scored all the refresh rates we need to pick the one that got the highest score.
285 // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
286 // or the lower otherwise.
287 const RefreshRate* bestRefreshRate = maxVoteLayers > 0
288 ? getBestRefreshRate(scores.rbegin(), scores.rend())
289 : getBestRefreshRate(scores.begin(), scores.end());
290
Alec Mouri11232a22020-05-14 18:06:25 -0700291 if (primaryRangeIsSingleRate) {
292 // If we never scored any layers, then choose the rate from the primary
293 // range instead of picking a random score from the app range.
294 if (std::all_of(scores.begin(), scores.end(),
295 [](std::pair<const RefreshRate*, float> p) { return p.second == 0; })) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700296 ALOGV("layers not scored - choose %s",
297 getMaxRefreshRateByPolicyLocked().getName().c_str());
Alec Mouri11232a22020-05-14 18:06:25 -0700298 return getMaxRefreshRateByPolicyLocked();
299 } else {
300 return *bestRefreshRate;
301 }
302 }
303
Steven Thomasf734df42020-04-13 21:09:28 -0700304 // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
305 // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
306 // vote we should not change it if we get a touch event. Only apply touch boost if it will
307 // actually increase the refresh rate over the normal selection.
308 const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
Alec Mouri11232a22020-05-14 18:06:25 -0700309
Steven Thomasf734df42020-04-13 21:09:28 -0700310 if (touchActive && explicitDefaultVoteLayers == 0 &&
311 bestRefreshRate->fps < touchRefreshRate.fps) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700312 if (touchConsidered) *touchConsidered = true;
313 ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
Steven Thomasf734df42020-04-13 21:09:28 -0700314 return touchRefreshRate;
315 }
316
Ady Abrahamde7156e2020-02-28 17:29:39 -0800317 return *bestRefreshRate;
Ady Abraham34702102020-02-10 14:12:05 -0800318}
319
320template <typename Iter>
321const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800322 constexpr auto EPSILON = 0.001f;
Ady Abrahamde7156e2020-02-28 17:29:39 -0800323 const RefreshRate* bestRefreshRate = begin->first;
324 float max = begin->second;
Ady Abraham34702102020-02-10 14:12:05 -0800325 for (auto i = begin; i != end; ++i) {
326 const auto [refreshRate, score] = *i;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800327 ALOGV("%s scores %.2f", refreshRate->name.c_str(), score);
328
Ady Abrahamdec1a412020-01-24 10:23:50 -0800329 ATRACE_INT(refreshRate->name.c_str(), round<int>(score * 100));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800330
Ady Abraham5b8afb5a2020-03-06 14:57:26 -0800331 if (score > max * (1 + EPSILON)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800332 max = score;
333 bestRefreshRate = refreshRate;
334 }
335 }
336
Ady Abraham34702102020-02-10 14:12:05 -0800337 return bestRefreshRate;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800338}
339
Ady Abraham2139f732019-11-13 18:56:40 -0800340const AllRefreshRatesMapType& RefreshRateConfigs::getAllRefreshRates() const {
341 return mRefreshRates;
342}
343
344const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicy() const {
345 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700346 return getMinRefreshRateByPolicyLocked();
347}
348
349const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
350 return *mPrimaryRefreshRates.front();
Ady Abraham2139f732019-11-13 18:56:40 -0800351}
352
353const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
354 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700355 return getMaxRefreshRateByPolicyLocked();
356}
357
358const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
359 return *mPrimaryRefreshRates.back();
Ady Abraham2139f732019-11-13 18:56:40 -0800360}
361
362const RefreshRate& RefreshRateConfigs::getCurrentRefreshRate() const {
363 std::lock_guard lock(mLock);
364 return *mCurrentRefreshRate;
365}
366
Ana Krulec5d477912020-02-07 12:02:38 -0800367const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
368 std::lock_guard lock(mLock);
Ana Krulec3d367c82020-02-25 15:02:01 -0800369 return getCurrentRefreshRateByPolicyLocked();
370}
371
372const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
Steven Thomasf734df42020-04-13 21:09:28 -0700373 if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
374 mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
Ana Krulec5d477912020-02-07 12:02:38 -0800375 return *mCurrentRefreshRate;
376 }
Steven Thomasd4071902020-03-24 16:02:53 -0700377 return *mRefreshRates.at(getCurrentPolicyLocked()->defaultConfig);
Ana Krulec5d477912020-02-07 12:02:38 -0800378}
379
Ady Abraham2139f732019-11-13 18:56:40 -0800380void RefreshRateConfigs::setCurrentConfigId(HwcConfigIndexType configId) {
381 std::lock_guard lock(mLock);
Ady Abraham2e1dd892020-03-05 13:48:36 -0800382 mCurrentRefreshRate = mRefreshRates.at(configId).get();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800383}
384
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800385RefreshRateConfigs::RefreshRateConfigs(
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800386 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs,
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700387 HwcConfigIndexType currentConfigId)
388 : mKnownFrameRates(constructKnownFrameRates(configs)) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700389 LOG_ALWAYS_FATAL_IF(configs.empty());
390 LOG_ALWAYS_FATAL_IF(currentConfigId.value() >= configs.size());
391
392 for (auto configId = HwcConfigIndexType(0); configId.value() < configs.size(); configId++) {
393 const auto& config = configs.at(static_cast<size_t>(configId.value()));
394 const float fps = 1e9f / config->getVsyncPeriod();
395 mRefreshRates.emplace(configId,
396 std::make_unique<RefreshRate>(configId, config,
Steven Thomasf734df42020-04-13 21:09:28 -0700397 base::StringPrintf("%.0ffps", fps), fps,
Ady Abrahamabc27602020-04-08 17:20:29 -0700398 RefreshRate::ConstructorTag(0)));
399 if (configId == currentConfigId) {
400 mCurrentRefreshRate = mRefreshRates.at(configId).get();
401 }
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800402 }
Ady Abrahamabc27602020-04-08 17:20:29 -0700403
404 std::vector<const RefreshRate*> sortedConfigs;
405 getSortedRefreshRateList([](const RefreshRate&) { return true; }, &sortedConfigs);
406 mDisplayManagerPolicy.defaultConfig = currentConfigId;
407 mMinSupportedRefreshRate = sortedConfigs.front();
408 mMaxSupportedRefreshRate = sortedConfigs.back();
409 constructAvailableRefreshRates();
Ady Abrahamb4b1e0a2019-11-20 18:25:35 -0800410}
411
Steven Thomasd4071902020-03-24 16:02:53 -0700412bool RefreshRateConfigs::isPolicyValid(const Policy& policy) {
413 // defaultConfig must be a valid config, and within the given refresh rate range.
414 auto iter = mRefreshRates.find(policy.defaultConfig);
415 if (iter == mRefreshRates.end()) {
416 return false;
417 }
418 const RefreshRate& refreshRate = *iter->second;
Steven Thomasf734df42020-04-13 21:09:28 -0700419 if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
Steven Thomasd4071902020-03-24 16:02:53 -0700420 return false;
421 }
Steven Thomasf734df42020-04-13 21:09:28 -0700422 return policy.appRequestRange.min <= policy.primaryRange.min &&
423 policy.appRequestRange.max >= policy.primaryRange.max;
Steven Thomasd4071902020-03-24 16:02:53 -0700424}
425
426status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
Ady Abraham2139f732019-11-13 18:56:40 -0800427 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700428 if (!isPolicyValid(policy)) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100429 return BAD_VALUE;
430 }
Steven Thomasd4071902020-03-24 16:02:53 -0700431 Policy previousPolicy = *getCurrentPolicyLocked();
432 mDisplayManagerPolicy = policy;
433 if (*getCurrentPolicyLocked() == previousPolicy) {
434 return CURRENT_POLICY_UNCHANGED;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100435 }
Ady Abraham2139f732019-11-13 18:56:40 -0800436 constructAvailableRefreshRates();
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100437 return NO_ERROR;
438}
439
Steven Thomasd4071902020-03-24 16:02:53 -0700440status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100441 std::lock_guard lock(mLock);
Steven Thomasd4071902020-03-24 16:02:53 -0700442 if (policy && !isPolicyValid(*policy)) {
443 return BAD_VALUE;
444 }
445 Policy previousPolicy = *getCurrentPolicyLocked();
446 mOverridePolicy = policy;
447 if (*getCurrentPolicyLocked() == previousPolicy) {
448 return CURRENT_POLICY_UNCHANGED;
449 }
450 constructAvailableRefreshRates();
451 return NO_ERROR;
452}
453
454const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
455 return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
456}
457
458RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
459 std::lock_guard lock(mLock);
460 return *getCurrentPolicyLocked();
461}
462
463RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
464 std::lock_guard lock(mLock);
465 return mDisplayManagerPolicy;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100466}
467
468bool RefreshRateConfigs::isConfigAllowed(HwcConfigIndexType config) const {
469 std::lock_guard lock(mLock);
Steven Thomasf734df42020-04-13 21:09:28 -0700470 for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100471 if (refreshRate->configId == config) {
472 return true;
473 }
474 }
475 return false;
Ady Abraham2139f732019-11-13 18:56:40 -0800476}
477
478void RefreshRateConfigs::getSortedRefreshRateList(
479 const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
480 std::vector<const RefreshRate*>* outRefreshRates) {
481 outRefreshRates->clear();
482 outRefreshRates->reserve(mRefreshRates.size());
483 for (const auto& [type, refreshRate] : mRefreshRates) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800484 if (shouldAddRefreshRate(*refreshRate)) {
Ady Abraham2139f732019-11-13 18:56:40 -0800485 ALOGV("getSortedRefreshRateList: config %d added to list policy",
Ady Abraham2e1dd892020-03-05 13:48:36 -0800486 refreshRate->configId.value());
487 outRefreshRates->push_back(refreshRate.get());
Ady Abraham2139f732019-11-13 18:56:40 -0800488 }
489 }
490
491 std::sort(outRefreshRates->begin(), outRefreshRates->end(),
492 [](const auto refreshRate1, const auto refreshRate2) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700493 if (refreshRate1->hwcConfig->getVsyncPeriod() !=
494 refreshRate2->hwcConfig->getVsyncPeriod()) {
495 return refreshRate1->hwcConfig->getVsyncPeriod() >
496 refreshRate2->hwcConfig->getVsyncPeriod();
Steven Thomasd4071902020-03-24 16:02:53 -0700497 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -0700498 return refreshRate1->hwcConfig->getConfigGroup() >
499 refreshRate2->hwcConfig->getConfigGroup();
Steven Thomasd4071902020-03-24 16:02:53 -0700500 }
Ady Abraham2139f732019-11-13 18:56:40 -0800501 });
502}
503
504void RefreshRateConfigs::constructAvailableRefreshRates() {
505 // Filter configs based on current policy and sort based on vsync period
Steven Thomasd4071902020-03-24 16:02:53 -0700506 const Policy* policy = getCurrentPolicyLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700507 const auto& defaultConfig = mRefreshRates.at(policy->defaultConfig)->hwcConfig;
Steven Thomasf734df42020-04-13 21:09:28 -0700508 ALOGV("constructAvailableRefreshRates: default %d group %d primaryRange=[%.2f %.2f]"
509 " appRequestRange=[%.2f %.2f]",
510 policy->defaultConfig.value(), defaultConfig->getConfigGroup(), policy->primaryRange.min,
511 policy->primaryRange.max, policy->appRequestRange.min, policy->appRequestRange.max);
Ady Abrahamabc27602020-04-08 17:20:29 -0700512
Steven Thomasf734df42020-04-13 21:09:28 -0700513 auto filterRefreshRates = [&](float min, float max, const char* listName,
514 std::vector<const RefreshRate*>* outRefreshRates) {
515 getSortedRefreshRateList(
516 [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
517 const auto& hwcConfig = refreshRate.hwcConfig;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800518
Steven Thomasf734df42020-04-13 21:09:28 -0700519 return hwcConfig->getHeight() == defaultConfig->getHeight() &&
520 hwcConfig->getWidth() == defaultConfig->getWidth() &&
521 hwcConfig->getDpiX() == defaultConfig->getDpiX() &&
522 hwcConfig->getDpiY() == defaultConfig->getDpiY() &&
523 (policy->allowGroupSwitching ||
524 hwcConfig->getConfigGroup() == defaultConfig->getConfigGroup()) &&
525 refreshRate.inPolicy(min, max);
526 },
527 outRefreshRates);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800528
Steven Thomasf734df42020-04-13 21:09:28 -0700529 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
530 "No matching configs for %s range: min=%.0f max=%.0f", listName, min,
531 max);
532 auto stringifyRefreshRates = [&]() -> std::string {
533 std::string str;
534 for (auto refreshRate : *outRefreshRates) {
535 base::StringAppendF(&str, "%s ", refreshRate->name.c_str());
536 }
537 return str;
538 };
539 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
540 };
541
542 filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
543 &mPrimaryRefreshRates);
544 filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
545 &mAppRequestRefreshRates);
Ady Abraham2139f732019-11-13 18:56:40 -0800546}
547
Ady Abrahamb1b9d412020-06-01 19:53:52 -0700548std::vector<float> RefreshRateConfigs::constructKnownFrameRates(
549 const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs) {
550 std::vector<float> knownFrameRates = {24.0f, 30.0f, 45.0f, 60.0f, 72.0f};
551 knownFrameRates.reserve(knownFrameRates.size() + configs.size());
552
553 // Add all supported refresh rates to the set
554 for (const auto& config : configs) {
555 const auto refreshRate = 1e9f / config->getVsyncPeriod();
556 knownFrameRates.emplace_back(refreshRate);
557 }
558
559 // Sort and remove duplicates
560 const auto frameRatesEqual = [](float a, float b) { return std::abs(a - b) <= 0.01f; };
561 std::sort(knownFrameRates.begin(), knownFrameRates.end());
562 knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
563 frameRatesEqual),
564 knownFrameRates.end());
565 return knownFrameRates;
566}
567
568float RefreshRateConfigs::findClosestKnownFrameRate(float frameRate) const {
569 if (frameRate <= *mKnownFrameRates.begin()) {
570 return *mKnownFrameRates.begin();
571 }
572
573 if (frameRate >= *std::prev(mKnownFrameRates.end())) {
574 return *std::prev(mKnownFrameRates.end());
575 }
576
577 auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate);
578
579 const auto distance1 = std::abs(frameRate - *lowerBound);
580 const auto distance2 = std::abs(frameRate - *std::prev(lowerBound));
581 return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
582}
583
Ady Abraham2139f732019-11-13 18:56:40 -0800584} // namespace android::scheduler