• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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  */
16 
17 // #define LOG_NDEBUG 0
18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
19 
20 // TODO(b/129481165): remove the #pragma below and fix conversion issues
21 #pragma clang diagnostic push
22 #pragma clang diagnostic ignored "-Wextra"
23 
24 #include <chrono>
25 #include <cmath>
26 
27 #include <android-base/properties.h>
28 #include <android-base/stringprintf.h>
29 #include <ftl/enum.h>
30 #include <utils/Trace.h>
31 
32 #include "../SurfaceFlingerProperties.h"
33 #include "RefreshRateConfigs.h"
34 
35 #undef LOG_TAG
36 #define LOG_TAG "RefreshRateConfigs"
37 
38 namespace android::scheduler {
39 namespace {
40 
41 struct RefreshRateScore {
42     DisplayModeIterator modeIt;
43     float overallScore;
44     struct {
45         float modeBelowThreshold;
46         float modeAboveThreshold;
47     } fixedRateBelowThresholdLayersScore;
48 };
49 
50 template <typename Iterator>
getMaxScoreRefreshRate(Iterator begin,Iterator end)51 const DisplayModePtr& getMaxScoreRefreshRate(Iterator begin, Iterator end) {
52     const auto it =
53             std::max_element(begin, end, [](RefreshRateScore max, RefreshRateScore current) {
54                 const auto& [modeIt, overallScore, _] = current;
55 
56                 std::string name = to_string(modeIt->second->getFps());
57                 ALOGV("%s scores %.2f", name.c_str(), overallScore);
58 
59                 ATRACE_INT(name.c_str(), static_cast<int>(std::round(overallScore * 100)));
60 
61                 constexpr float kEpsilon = 0.0001f;
62                 return overallScore > max.overallScore * (1 + kEpsilon);
63             });
64 
65     return it->modeIt->second;
66 }
67 
68 constexpr RefreshRateConfigs::GlobalSignals kNoSignals;
69 
formatLayerInfo(const RefreshRateConfigs::LayerRequirement & layer,float weight)70 std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
71     return base::StringPrintf("%s (type=%s, weight=%.2f, seamlessness=%s) %s", layer.name.c_str(),
72                               ftl::enum_string(layer.vote).c_str(), weight,
73                               ftl::enum_string(layer.seamlessness).c_str(),
74                               to_string(layer.desiredRefreshRate).c_str());
75 }
76 
constructKnownFrameRates(const DisplayModes & modes)77 std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
78     std::vector<Fps> knownFrameRates = {24_Hz, 30_Hz, 45_Hz, 60_Hz, 72_Hz};
79     knownFrameRates.reserve(knownFrameRates.size() + modes.size());
80 
81     // Add all supported refresh rates.
82     for (const auto& [id, mode] : modes) {
83         knownFrameRates.push_back(mode->getFps());
84     }
85 
86     // Sort and remove duplicates.
87     std::sort(knownFrameRates.begin(), knownFrameRates.end(), isStrictlyLess);
88     knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
89                                       isApproxEqual),
90                           knownFrameRates.end());
91     return knownFrameRates;
92 }
93 
94 // The Filter is a `bool(const DisplayMode&)` predicate.
95 template <typename Filter>
sortByRefreshRate(const DisplayModes & modes,Filter && filter)96 std::vector<DisplayModeIterator> sortByRefreshRate(const DisplayModes& modes, Filter&& filter) {
97     std::vector<DisplayModeIterator> sortedModes;
98     sortedModes.reserve(modes.size());
99 
100     for (auto it = modes.begin(); it != modes.end(); ++it) {
101         const auto& [id, mode] = *it;
102 
103         if (filter(*mode)) {
104             ALOGV("%s: including mode %d", __func__, id.value());
105             sortedModes.push_back(it);
106         }
107     }
108 
109     std::sort(sortedModes.begin(), sortedModes.end(), [](auto it1, auto it2) {
110         const auto& mode1 = it1->second;
111         const auto& mode2 = it2->second;
112 
113         if (mode1->getVsyncPeriod() == mode2->getVsyncPeriod()) {
114             return mode1->getGroup() > mode2->getGroup();
115         }
116 
117         return mode1->getVsyncPeriod() > mode2->getVsyncPeriod();
118     });
119 
120     return sortedModes;
121 }
122 
canModesSupportFrameRateOverride(const std::vector<DisplayModeIterator> & sortedModes)123 bool canModesSupportFrameRateOverride(const std::vector<DisplayModeIterator>& sortedModes) {
124     for (const auto it1 : sortedModes) {
125         const auto& mode1 = it1->second;
126         for (const auto it2 : sortedModes) {
127             const auto& mode2 = it2->second;
128 
129             if (RefreshRateConfigs::getFrameRateDivisor(mode1->getFps(), mode2->getFps()) >= 2) {
130                 return true;
131             }
132         }
133     }
134     return false;
135 }
136 
137 } // namespace
138 
toString() const139 std::string RefreshRateConfigs::Policy::toString() const {
140     return base::StringPrintf("{defaultModeId=%d, allowGroupSwitching=%s"
141                               ", primaryRange=%s, appRequestRange=%s}",
142                               defaultMode.value(), allowGroupSwitching ? "true" : "false",
143                               to_string(primaryRange).c_str(), to_string(appRequestRange).c_str());
144 }
145 
getDisplayFrames(nsecs_t layerPeriod,nsecs_t displayPeriod) const146 std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
147                                                                  nsecs_t displayPeriod) const {
148     auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
149     if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
150         std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
151         quotient++;
152         remainder = 0;
153     }
154 
155     return {quotient, remainder};
156 }
157 
calculateNonExactMatchingLayerScoreLocked(const LayerRequirement & layer,Fps refreshRate) const158 float RefreshRateConfigs::calculateNonExactMatchingLayerScoreLocked(const LayerRequirement& layer,
159                                                                     Fps refreshRate) const {
160     constexpr float kScoreForFractionalPairs = .8f;
161 
162     const auto displayPeriod = refreshRate.getPeriodNsecs();
163     const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
164     if (layer.vote == LayerVoteType::ExplicitDefault) {
165         // Find the actual rate the layer will render, assuming
166         // that layerPeriod is the minimal period to render a frame.
167         // For example if layerPeriod is 20ms and displayPeriod is 16ms,
168         // then the actualLayerPeriod will be 32ms, because it is the
169         // smallest multiple of the display period which is >= layerPeriod.
170         auto actualLayerPeriod = displayPeriod;
171         int multiplier = 1;
172         while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
173             multiplier++;
174             actualLayerPeriod = displayPeriod * multiplier;
175         }
176 
177         // Because of the threshold we used above it's possible that score is slightly
178         // above 1.
179         return std::min(1.0f,
180                         static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
181     }
182 
183     if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
184         layer.vote == LayerVoteType::Heuristic) {
185         if (isFractionalPairOrMultiple(refreshRate, layer.desiredRefreshRate)) {
186             return kScoreForFractionalPairs;
187         }
188 
189         // Calculate how many display vsyncs we need to present a single frame for this
190         // layer
191         const auto [displayFramesQuotient, displayFramesRemainder] =
192                 getDisplayFrames(layerPeriod, displayPeriod);
193         static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
194         if (displayFramesRemainder == 0) {
195             // Layer desired refresh rate matches the display rate.
196             return 1.0f;
197         }
198 
199         if (displayFramesQuotient == 0) {
200             // Layer desired refresh rate is higher than the display rate.
201             return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
202                     (1.0f / (MAX_FRAMES_TO_FIT + 1));
203         }
204 
205         // Layer desired refresh rate is lower than the display rate. Check how well it fits
206         // the cadence.
207         auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
208         int iter = 2;
209         while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
210             diff = diff - (displayPeriod - diff);
211             iter++;
212         }
213 
214         return (1.0f / iter);
215     }
216 
217     return 0;
218 }
219 
calculateLayerScoreLocked(const LayerRequirement & layer,Fps refreshRate,bool isSeamlessSwitch) const220 float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer, Fps refreshRate,
221                                                     bool isSeamlessSwitch) const {
222     // Slightly prefer seamless switches.
223     constexpr float kSeamedSwitchPenalty = 0.95f;
224     const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
225 
226     // If the layer wants Max, give higher score to the higher refresh rate
227     if (layer.vote == LayerVoteType::Max) {
228         const auto& maxRefreshRate = mAppRequestRefreshRates.back()->second;
229         const auto ratio = refreshRate.getValue() / maxRefreshRate->getFps().getValue();
230         // use ratio^2 to get a lower score the more we get further from peak
231         return ratio * ratio;
232     }
233 
234     if (layer.vote == LayerVoteType::ExplicitExact) {
235         const int divisor = getFrameRateDivisor(refreshRate, layer.desiredRefreshRate);
236         if (mSupportsFrameRateOverrideByContent) {
237             // Since we support frame rate override, allow refresh rates which are
238             // multiples of the layer's request, as those apps would be throttled
239             // down to run at the desired refresh rate.
240             return divisor > 0;
241         }
242 
243         return divisor == 1;
244     }
245 
246     // If the layer frame rate is a divisor of the refresh rate it should score
247     // the highest score.
248     if (getFrameRateDivisor(refreshRate, layer.desiredRefreshRate) > 0) {
249         return 1.0f * seamlessness;
250     }
251 
252     // The layer frame rate is not a divisor of the refresh rate,
253     // there is a small penalty attached to the score to favor the frame rates
254     // the exactly matches the display refresh rate or a multiple.
255     constexpr float kNonExactMatchingPenalty = 0.95f;
256     return calculateNonExactMatchingLayerScoreLocked(layer, refreshRate) * seamlessness *
257             kNonExactMatchingPenalty;
258 }
259 
getBestRefreshRate(const std::vector<LayerRequirement> & layers,GlobalSignals signals) const260 auto RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
261                                             GlobalSignals signals) const
262         -> std::pair<DisplayModePtr, GlobalSignals> {
263     std::lock_guard lock(mLock);
264 
265     if (mGetBestRefreshRateCache &&
266         mGetBestRefreshRateCache->arguments == std::make_pair(layers, signals)) {
267         return mGetBestRefreshRateCache->result;
268     }
269 
270     const auto result = getBestRefreshRateLocked(layers, signals);
271     mGetBestRefreshRateCache = GetBestRefreshRateCache{{layers, signals}, result};
272     return result;
273 }
274 
getBestRefreshRateLocked(const std::vector<LayerRequirement> & layers,GlobalSignals signals) const275 auto RefreshRateConfigs::getBestRefreshRateLocked(const std::vector<LayerRequirement>& layers,
276                                                   GlobalSignals signals) const
277         -> std::pair<DisplayModePtr, GlobalSignals> {
278     using namespace fps_approx_ops;
279     ATRACE_CALL();
280     ALOGV("%s: %zu layers", __func__, layers.size());
281 
282     int noVoteLayers = 0;
283     int minVoteLayers = 0;
284     int maxVoteLayers = 0;
285     int explicitDefaultVoteLayers = 0;
286     int explicitExactOrMultipleVoteLayers = 0;
287     int explicitExact = 0;
288     float maxExplicitWeight = 0;
289     int seamedFocusedLayers = 0;
290 
291     for (const auto& layer : layers) {
292         switch (layer.vote) {
293             case LayerVoteType::NoVote:
294                 noVoteLayers++;
295                 break;
296             case LayerVoteType::Min:
297                 minVoteLayers++;
298                 break;
299             case LayerVoteType::Max:
300                 maxVoteLayers++;
301                 break;
302             case LayerVoteType::ExplicitDefault:
303                 explicitDefaultVoteLayers++;
304                 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
305                 break;
306             case LayerVoteType::ExplicitExactOrMultiple:
307                 explicitExactOrMultipleVoteLayers++;
308                 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
309                 break;
310             case LayerVoteType::ExplicitExact:
311                 explicitExact++;
312                 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
313                 break;
314             case LayerVoteType::Heuristic:
315                 break;
316         }
317 
318         if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
319             seamedFocusedLayers++;
320         }
321     }
322 
323     const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
324             explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
325 
326     const Policy* policy = getCurrentPolicyLocked();
327     const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
328     // If the default mode group is different from the group of current mode,
329     // this means a layer requesting a seamed mode switch just disappeared and
330     // we should switch back to the default group.
331     // However if a seamed layer is still present we anchor around the group
332     // of the current mode, in order to prevent unnecessary seamed mode switches
333     // (e.g. when pausing a video playback).
334     const auto anchorGroup =
335             seamedFocusedLayers > 0 ? mActiveModeIt->second->getGroup() : defaultMode->getGroup();
336 
337     // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
338     // selected a refresh rate to see if we should apply touch boost.
339     if (signals.touch && !hasExplicitVoteLayers) {
340         const DisplayModePtr& max = getMaxRefreshRateByPolicyLocked(anchorGroup);
341         ALOGV("TouchBoost - choose %s", to_string(max->getFps()).c_str());
342         return {max, GlobalSignals{.touch = true}};
343     }
344 
345     // If the primary range consists of a single refresh rate then we can only
346     // move out the of range if layers explicitly request a different refresh
347     // rate.
348     const bool primaryRangeIsSingleRate =
349             isApproxEqual(policy->primaryRange.min, policy->primaryRange.max);
350 
351     if (!signals.touch && signals.idle && !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
352         const DisplayModePtr& min = getMinRefreshRateByPolicyLocked();
353         ALOGV("Idle - choose %s", to_string(min->getFps()).c_str());
354         return {min, GlobalSignals{.idle = true}};
355     }
356 
357     if (layers.empty() || noVoteLayers == layers.size()) {
358         const DisplayModePtr& max = getMaxRefreshRateByPolicyLocked(anchorGroup);
359         ALOGV("no layers with votes - choose %s", to_string(max->getFps()).c_str());
360         return {max, kNoSignals};
361     }
362 
363     // Only if all layers want Min we should return Min
364     if (noVoteLayers + minVoteLayers == layers.size()) {
365         const DisplayModePtr& min = getMinRefreshRateByPolicyLocked();
366         ALOGV("all layers Min - choose %s", to_string(min->getFps()).c_str());
367         return {min, kNoSignals};
368     }
369 
370     // Find the best refresh rate based on score
371     std::vector<RefreshRateScore> scores;
372     scores.reserve(mAppRequestRefreshRates.size());
373 
374     for (const DisplayModeIterator modeIt : mAppRequestRefreshRates) {
375         scores.emplace_back(RefreshRateScore{modeIt, 0.0f});
376     }
377 
378     for (const auto& layer : layers) {
379         ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
380               ftl::enum_string(layer.vote).c_str(), layer.weight,
381               layer.desiredRefreshRate.getValue());
382         if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
383             continue;
384         }
385 
386         const auto weight = layer.weight;
387 
388         for (auto& [modeIt, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
389             const auto& [id, mode] = *modeIt;
390             const bool isSeamlessSwitch = mode->getGroup() == mActiveModeIt->second->getGroup();
391 
392             if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
393                 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
394                       formatLayerInfo(layer, weight).c_str(), to_string(*mode).c_str(),
395                       to_string(*mActiveModeIt->second).c_str());
396                 continue;
397             }
398 
399             if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
400                 !layer.focused) {
401                 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
402                       " Current mode = %s",
403                       formatLayerInfo(layer, weight).c_str(), to_string(*mode).c_str(),
404                       to_string(*mActiveModeIt->second).c_str());
405                 continue;
406             }
407 
408             // Layers with default seamlessness vote for the current mode group if
409             // there are layers with seamlessness=SeamedAndSeamless and for the default
410             // mode group otherwise. In second case, if the current mode group is different
411             // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
412             // disappeared.
413             const bool isInPolicyForDefault = mode->getGroup() == anchorGroup;
414             if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
415                 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
416                       to_string(*mode).c_str(), to_string(*mActiveModeIt->second).c_str());
417                 continue;
418             }
419 
420             const bool inPrimaryRange = policy->primaryRange.includes(mode->getFps());
421             if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
422                 !(layer.focused &&
423                   (layer.vote == LayerVoteType::ExplicitDefault ||
424                    layer.vote == LayerVoteType::ExplicitExact))) {
425                 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
426                 // refresh rates outside the primary range.
427                 continue;
428             }
429 
430             const float layerScore =
431                     calculateLayerScoreLocked(layer, mode->getFps(), isSeamlessSwitch);
432             const float weightedLayerScore = weight * layerScore;
433 
434             // Layer with fixed source has a special consideration which depends on the
435             // mConfig.frameRateMultipleThreshold. We don't want these layers to score
436             // refresh rates above the threshold, but we also don't want to favor the lower
437             // ones by having a greater number of layers scoring them. Instead, we calculate
438             // the score independently for these layers and later decide which
439             // refresh rates to add it. For example, desired 24 fps with 120 Hz threshold should not
440             // score 120 Hz, but desired 60 fps should contribute to the score.
441             const bool fixedSourceLayer = [](LayerVoteType vote) {
442                 switch (vote) {
443                     case LayerVoteType::ExplicitExactOrMultiple:
444                     case LayerVoteType::Heuristic:
445                         return true;
446                     case LayerVoteType::NoVote:
447                     case LayerVoteType::Min:
448                     case LayerVoteType::Max:
449                     case LayerVoteType::ExplicitDefault:
450                     case LayerVoteType::ExplicitExact:
451                         return false;
452                 }
453             }(layer.vote);
454             const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
455                     layer.desiredRefreshRate <
456                             Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
457             if (fixedSourceLayer && layerBelowThreshold) {
458                 const bool modeAboveThreshold =
459                         mode->getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
460                 if (modeAboveThreshold) {
461                     ALOGV("%s gives %s fixed source (above threshold) score of %.4f",
462                           formatLayerInfo(layer, weight).c_str(), to_string(mode->getFps()).c_str(),
463                           layerScore);
464                     fixedRateBelowThresholdLayersScore.modeAboveThreshold += weightedLayerScore;
465                 } else {
466                     ALOGV("%s gives %s fixed source (below threshold) score of %.4f",
467                           formatLayerInfo(layer, weight).c_str(), to_string(mode->getFps()).c_str(),
468                           layerScore);
469                     fixedRateBelowThresholdLayersScore.modeBelowThreshold += weightedLayerScore;
470                 }
471             } else {
472                 ALOGV("%s gives %s score of %.4f", formatLayerInfo(layer, weight).c_str(),
473                       to_string(mode->getFps()).c_str(), layerScore);
474                 overallScore += weightedLayerScore;
475             }
476         }
477     }
478 
479     // We want to find the best refresh rate without the fixed source layers,
480     // so we could know whether we should add the modeAboveThreshold scores or not.
481     // If the best refresh rate is already above the threshold, it means that
482     // some non-fixed source layers already scored it, so we can just add the score
483     // for all fixed source layers, even the ones that are above the threshold.
484     const bool maxScoreAboveThreshold = [&] {
485         if (mConfig.frameRateMultipleThreshold == 0 || scores.empty()) {
486             return false;
487         }
488 
489         const auto maxScoreIt =
490                 std::max_element(scores.begin(), scores.end(),
491                                  [](RefreshRateScore max, RefreshRateScore current) {
492                                      const auto& [modeIt, overallScore, _] = current;
493                                      return overallScore > max.overallScore;
494                                  });
495         ALOGV("%s is the best refresh rate without fixed source layers. It is %s the threshold for "
496               "refresh rate multiples",
497               to_string(maxScoreIt->modeIt->second->getFps()).c_str(),
498               maxScoreAboveThreshold ? "above" : "below");
499         return maxScoreIt->modeIt->second->getFps() >=
500                 Fps::fromValue(mConfig.frameRateMultipleThreshold);
501     }();
502 
503     // Now we can add the fixed rate layers score
504     for (auto& [modeIt, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
505         overallScore += fixedRateBelowThresholdLayersScore.modeBelowThreshold;
506         if (maxScoreAboveThreshold) {
507             overallScore += fixedRateBelowThresholdLayersScore.modeAboveThreshold;
508         }
509         ALOGV("%s adjusted overallScore is %.4f", to_string(modeIt->second->getFps()).c_str(),
510               overallScore);
511     }
512 
513     // Now that we scored all the refresh rates we need to pick the one that got the highest
514     // overallScore. In case of a tie we will pick the higher refresh rate if any of the layers
515     // wanted Max, or the lower otherwise.
516     const DisplayModePtr& bestRefreshRate = maxVoteLayers > 0
517             ? getMaxScoreRefreshRate(scores.rbegin(), scores.rend())
518             : getMaxScoreRefreshRate(scores.begin(), scores.end());
519 
520     if (primaryRangeIsSingleRate) {
521         // If we never scored any layers, then choose the rate from the primary
522         // range instead of picking a random score from the app range.
523         if (std::all_of(scores.begin(), scores.end(),
524                         [](RefreshRateScore score) { return score.overallScore == 0; })) {
525             const DisplayModePtr& max = getMaxRefreshRateByPolicyLocked(anchorGroup);
526             ALOGV("layers not scored - choose %s", to_string(max->getFps()).c_str());
527             return {max, kNoSignals};
528         } else {
529             return {bestRefreshRate, kNoSignals};
530         }
531     }
532 
533     // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
534     // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
535     // vote we should not change it if we get a touch event. Only apply touch boost if it will
536     // actually increase the refresh rate over the normal selection.
537     const DisplayModePtr& touchRefreshRate = getMaxRefreshRateByPolicyLocked(anchorGroup);
538 
539     const bool touchBoostForExplicitExact = [&] {
540         if (mSupportsFrameRateOverrideByContent) {
541             // Enable touch boost if there are other layers besides exact
542             return explicitExact + noVoteLayers != layers.size();
543         } else {
544             // Enable touch boost if there are no exact layers
545             return explicitExact == 0;
546         }
547     }();
548 
549     using fps_approx_ops::operator<;
550 
551     if (signals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
552         bestRefreshRate->getFps() < touchRefreshRate->getFps()) {
553         ALOGV("TouchBoost - choose %s", to_string(touchRefreshRate->getFps()).c_str());
554         return {touchRefreshRate, GlobalSignals{.touch = true}};
555     }
556 
557     return {bestRefreshRate, kNoSignals};
558 }
559 
560 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement> & layers)561 groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
562     std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
563     for (const auto& layer : layers) {
564         auto iter = layersByUid.emplace(layer.ownerUid,
565                                         std::vector<const RefreshRateConfigs::LayerRequirement*>());
566         auto& layersWithSameUid = iter.first->second;
567         layersWithSameUid.push_back(&layer);
568     }
569 
570     // Remove uids that can't have a frame rate override
571     for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
572         const auto& layersWithSameUid = iter->second;
573         bool skipUid = false;
574         for (const auto& layer : layersWithSameUid) {
575             if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
576                 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
577                 skipUid = true;
578                 break;
579             }
580         }
581         if (skipUid) {
582             iter = layersByUid.erase(iter);
583         } else {
584             ++iter;
585         }
586     }
587 
588     return layersByUid;
589 }
590 
getFrameRateOverrides(const std::vector<LayerRequirement> & layers,Fps displayRefreshRate,GlobalSignals globalSignals) const591 RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
592         const std::vector<LayerRequirement>& layers, Fps displayRefreshRate,
593         GlobalSignals globalSignals) const {
594     ATRACE_CALL();
595 
596     ALOGV("%s: %zu layers", __func__, layers.size());
597 
598     std::lock_guard lock(mLock);
599 
600     std::vector<RefreshRateScore> scores;
601     scores.reserve(mDisplayModes.size());
602 
603     for (auto it = mDisplayModes.begin(); it != mDisplayModes.end(); ++it) {
604         scores.emplace_back(RefreshRateScore{it, 0.0f});
605     }
606 
607     std::sort(scores.begin(), scores.end(), [](const auto& lhs, const auto& rhs) {
608         const auto& mode1 = lhs.modeIt->second;
609         const auto& mode2 = rhs.modeIt->second;
610         return isStrictlyLess(mode1->getFps(), mode2->getFps());
611     });
612 
613     std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
614             groupLayersByUid(layers);
615     UidToFrameRateOverride frameRateOverrides;
616     for (const auto& [uid, layersWithSameUid] : layersByUid) {
617         // Layers with ExplicitExactOrMultiple expect touch boost
618         const bool hasExplicitExactOrMultiple =
619                 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
620                             [](const auto& layer) {
621                                 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
622                             });
623 
624         if (globalSignals.touch && hasExplicitExactOrMultiple) {
625             continue;
626         }
627 
628         for (auto& [_, score, _1] : scores) {
629             score = 0;
630         }
631 
632         for (const auto& layer : layersWithSameUid) {
633             if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
634                 continue;
635             }
636 
637             LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
638                                 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
639                                 layer->vote != LayerVoteType::ExplicitExact);
640             for (auto& [modeIt, score, _] : scores) {
641                 constexpr bool isSeamlessSwitch = true;
642                 const auto layerScore = calculateLayerScoreLocked(*layer, modeIt->second->getFps(),
643                                                                   isSeamlessSwitch);
644                 score += layer->weight * layerScore;
645             }
646         }
647 
648         // We just care about the refresh rates which are a divisor of the
649         // display refresh rate
650         const auto it = std::remove_if(scores.begin(), scores.end(), [&](RefreshRateScore score) {
651             const auto& [id, mode] = *score.modeIt;
652             return getFrameRateDivisor(displayRefreshRate, mode->getFps()) == 0;
653         });
654         scores.erase(it, scores.end());
655 
656         // If we never scored any layers, we don't have a preferred frame rate
657         if (std::all_of(scores.begin(), scores.end(),
658                         [](RefreshRateScore score) { return score.overallScore == 0; })) {
659             continue;
660         }
661 
662         // Now that we scored all the refresh rates we need to pick the one that got the highest
663         // score.
664         const DisplayModePtr& bestRefreshRate =
665                 getMaxScoreRefreshRate(scores.begin(), scores.end());
666 
667         frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
668     }
669 
670     return frameRateOverrides;
671 }
672 
onKernelTimerChanged(std::optional<DisplayModeId> desiredActiveModeId,bool timerExpired) const673 std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
674         std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
675     std::lock_guard lock(mLock);
676 
677     const DisplayModePtr& current = desiredActiveModeId
678             ? mDisplayModes.get(*desiredActiveModeId)->get()
679             : mActiveModeIt->second;
680 
681     const DisplayModePtr& min = mMinRefreshRateModeIt->second;
682     if (current == min) {
683         return {};
684     }
685 
686     const auto& mode = timerExpired ? min : current;
687     return mode->getFps();
688 }
689 
getMinRefreshRateByPolicyLocked() const690 const DisplayModePtr& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
691     for (const DisplayModeIterator modeIt : mPrimaryRefreshRates) {
692         const auto& mode = modeIt->second;
693         if (mActiveModeIt->second->getGroup() == mode->getGroup()) {
694             return mode;
695         }
696     }
697 
698     ALOGE("Can't find min refresh rate by policy with the same mode group"
699           " as the current mode %s",
700           to_string(*mActiveModeIt->second).c_str());
701 
702     // Default to the lowest refresh rate.
703     return mPrimaryRefreshRates.front()->second;
704 }
705 
getMaxRefreshRateByPolicy() const706 DisplayModePtr RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
707     std::lock_guard lock(mLock);
708     return getMaxRefreshRateByPolicyLocked();
709 }
710 
getMaxRefreshRateByPolicyLocked(int anchorGroup) const711 const DisplayModePtr& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
712     for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); ++it) {
713         const auto& mode = (*it)->second;
714         if (anchorGroup == mode->getGroup()) {
715             return mode;
716         }
717     }
718 
719     ALOGE("Can't find max refresh rate by policy with the same mode group"
720           " as the current mode %s",
721           to_string(*mActiveModeIt->second).c_str());
722 
723     // Default to the highest refresh rate.
724     return mPrimaryRefreshRates.back()->second;
725 }
726 
getActiveMode() const727 DisplayModePtr RefreshRateConfigs::getActiveMode() const {
728     std::lock_guard lock(mLock);
729     return mActiveModeIt->second;
730 }
731 
setActiveModeId(DisplayModeId modeId)732 void RefreshRateConfigs::setActiveModeId(DisplayModeId modeId) {
733     std::lock_guard lock(mLock);
734 
735     // Invalidate the cached invocation to getBestRefreshRate. This forces
736     // the refresh rate to be recomputed on the next call to getBestRefreshRate.
737     mGetBestRefreshRateCache.reset();
738 
739     mActiveModeIt = mDisplayModes.find(modeId);
740     LOG_ALWAYS_FATAL_IF(mActiveModeIt == mDisplayModes.end());
741 }
742 
RefreshRateConfigs(DisplayModes modes,DisplayModeId activeModeId,Config config)743 RefreshRateConfigs::RefreshRateConfigs(DisplayModes modes, DisplayModeId activeModeId,
744                                        Config config)
745       : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
746     initializeIdleTimer();
747     updateDisplayModes(std::move(modes), activeModeId);
748 }
749 
initializeIdleTimer()750 void RefreshRateConfigs::initializeIdleTimer() {
751     if (mConfig.idleTimerTimeout > 0ms) {
752         mIdleTimer.emplace(
753                 "IdleTimer", mConfig.idleTimerTimeout,
754                 [this] {
755                     std::scoped_lock lock(mIdleTimerCallbacksMutex);
756                     if (const auto callbacks = getIdleTimerCallbacks()) {
757                         callbacks->onReset();
758                     }
759                 },
760                 [this] {
761                     std::scoped_lock lock(mIdleTimerCallbacksMutex);
762                     if (const auto callbacks = getIdleTimerCallbacks()) {
763                         callbacks->onExpired();
764                     }
765                 });
766     }
767 }
768 
updateDisplayModes(DisplayModes modes,DisplayModeId activeModeId)769 void RefreshRateConfigs::updateDisplayModes(DisplayModes modes, DisplayModeId activeModeId) {
770     std::lock_guard lock(mLock);
771 
772     // Invalidate the cached invocation to getBestRefreshRate. This forces
773     // the refresh rate to be recomputed on the next call to getBestRefreshRate.
774     mGetBestRefreshRateCache.reset();
775 
776     mDisplayModes = std::move(modes);
777     mActiveModeIt = mDisplayModes.find(activeModeId);
778     LOG_ALWAYS_FATAL_IF(mActiveModeIt == mDisplayModes.end());
779 
780     const auto sortedModes =
781             sortByRefreshRate(mDisplayModes, [](const DisplayMode&) { return true; });
782     mMinRefreshRateModeIt = sortedModes.front();
783     mMaxRefreshRateModeIt = sortedModes.back();
784 
785     // Reset the policy because the old one may no longer be valid.
786     mDisplayManagerPolicy = {};
787     mDisplayManagerPolicy.defaultMode = activeModeId;
788 
789     mSupportsFrameRateOverrideByContent =
790             mConfig.enableFrameRateOverride && canModesSupportFrameRateOverride(sortedModes);
791 
792     constructAvailableRefreshRates();
793 }
794 
isPolicyValidLocked(const Policy & policy) const795 bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
796     // defaultMode must be a valid mode, and within the given refresh rate range.
797     if (const auto mode = mDisplayModes.get(policy.defaultMode)) {
798         if (!policy.primaryRange.includes(mode->get()->getFps())) {
799             ALOGE("Default mode is not in the primary range.");
800             return false;
801         }
802     } else {
803         ALOGE("Default mode is not found.");
804         return false;
805     }
806 
807     using namespace fps_approx_ops;
808     return policy.appRequestRange.min <= policy.primaryRange.min &&
809             policy.appRequestRange.max >= policy.primaryRange.max;
810 }
811 
setDisplayManagerPolicy(const Policy & policy)812 status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
813     std::lock_guard lock(mLock);
814     if (!isPolicyValidLocked(policy)) {
815         ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
816         return BAD_VALUE;
817     }
818     mGetBestRefreshRateCache.reset();
819     Policy previousPolicy = *getCurrentPolicyLocked();
820     mDisplayManagerPolicy = policy;
821     if (*getCurrentPolicyLocked() == previousPolicy) {
822         return CURRENT_POLICY_UNCHANGED;
823     }
824     constructAvailableRefreshRates();
825     return NO_ERROR;
826 }
827 
setOverridePolicy(const std::optional<Policy> & policy)828 status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
829     std::lock_guard lock(mLock);
830     if (policy && !isPolicyValidLocked(*policy)) {
831         return BAD_VALUE;
832     }
833     mGetBestRefreshRateCache.reset();
834     Policy previousPolicy = *getCurrentPolicyLocked();
835     mOverridePolicy = policy;
836     if (*getCurrentPolicyLocked() == previousPolicy) {
837         return CURRENT_POLICY_UNCHANGED;
838     }
839     constructAvailableRefreshRates();
840     return NO_ERROR;
841 }
842 
getCurrentPolicyLocked() const843 const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
844     return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
845 }
846 
getCurrentPolicy() const847 RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
848     std::lock_guard lock(mLock);
849     return *getCurrentPolicyLocked();
850 }
851 
getDisplayManagerPolicy() const852 RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
853     std::lock_guard lock(mLock);
854     return mDisplayManagerPolicy;
855 }
856 
isModeAllowed(DisplayModeId modeId) const857 bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
858     std::lock_guard lock(mLock);
859     return std::any_of(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
860                        [modeId](DisplayModeIterator modeIt) {
861                            return modeIt->second->getId() == modeId;
862                        });
863 }
864 
constructAvailableRefreshRates()865 void RefreshRateConfigs::constructAvailableRefreshRates() {
866     // Filter modes based on current policy and sort on refresh rate.
867     const Policy* policy = getCurrentPolicyLocked();
868     ALOGV("%s: %s ", __func__, policy->toString().c_str());
869 
870     const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
871 
872     const auto filterRefreshRates = [&](FpsRange range, const char* rangeName) REQUIRES(mLock) {
873         const auto filter = [&](const DisplayMode& mode) {
874             return mode.getResolution() == defaultMode->getResolution() &&
875                     mode.getDpi() == defaultMode->getDpi() &&
876                     (policy->allowGroupSwitching || mode.getGroup() == defaultMode->getGroup()) &&
877                     range.includes(mode.getFps());
878         };
879 
880         const auto modes = sortByRefreshRate(mDisplayModes, filter);
881         LOG_ALWAYS_FATAL_IF(modes.empty(), "No matching modes for %s range %s", rangeName,
882                             to_string(range).c_str());
883 
884         const auto stringifyModes = [&] {
885             std::string str;
886             for (const auto modeIt : modes) {
887                 str += to_string(modeIt->second->getFps());
888                 str.push_back(' ');
889             }
890             return str;
891         };
892         ALOGV("%s refresh rates: %s", rangeName, stringifyModes().c_str());
893 
894         return modes;
895     };
896 
897     mPrimaryRefreshRates = filterRefreshRates(policy->primaryRange, "primary");
898     mAppRequestRefreshRates = filterRefreshRates(policy->appRequestRange, "app request");
899 }
900 
findClosestKnownFrameRate(Fps frameRate) const901 Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
902     using namespace fps_approx_ops;
903 
904     if (frameRate <= mKnownFrameRates.front()) {
905         return mKnownFrameRates.front();
906     }
907 
908     if (frameRate >= mKnownFrameRates.back()) {
909         return mKnownFrameRates.back();
910     }
911 
912     auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
913                                        isStrictlyLess);
914 
915     const auto distance1 = std::abs(frameRate.getValue() - lowerBound->getValue());
916     const auto distance2 = std::abs(frameRate.getValue() - std::prev(lowerBound)->getValue());
917     return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
918 }
919 
getIdleTimerAction() const920 RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
921     std::lock_guard lock(mLock);
922 
923     const Fps deviceMinFps = mMinRefreshRateModeIt->second->getFps();
924     const DisplayModePtr& minByPolicy = getMinRefreshRateByPolicyLocked();
925 
926     // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
927     // the min allowed refresh rate is higher than the device min, we do not want to enable the
928     // timer.
929     if (isStrictlyLess(deviceMinFps, minByPolicy->getFps())) {
930         return KernelIdleTimerAction::TurnOff;
931     }
932 
933     const DisplayModePtr& maxByPolicy = getMaxRefreshRateByPolicyLocked();
934     if (minByPolicy == maxByPolicy) {
935         // Turn on the timer when the min of the primary range is below the device min.
936         if (const Policy* currentPolicy = getCurrentPolicyLocked();
937             isApproxLess(currentPolicy->primaryRange.min, deviceMinFps)) {
938             return KernelIdleTimerAction::TurnOn;
939         }
940         return KernelIdleTimerAction::TurnOff;
941     }
942 
943     // Turn on the timer in all other cases.
944     return KernelIdleTimerAction::TurnOn;
945 }
946 
getFrameRateDivisor(Fps displayRefreshRate,Fps layerFrameRate)947 int RefreshRateConfigs::getFrameRateDivisor(Fps displayRefreshRate, Fps layerFrameRate) {
948     // This calculation needs to be in sync with the java code
949     // in DisplayManagerService.getDisplayInfoForFrameRateOverride
950 
951     // The threshold must be smaller than 0.001 in order to differentiate
952     // between the fractional pairs (e.g. 59.94 and 60).
953     constexpr float kThreshold = 0.0009f;
954     const auto numPeriods = displayRefreshRate.getValue() / layerFrameRate.getValue();
955     const auto numPeriodsRounded = std::round(numPeriods);
956     if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
957         return 0;
958     }
959 
960     return static_cast<int>(numPeriodsRounded);
961 }
962 
isFractionalPairOrMultiple(Fps smaller,Fps bigger)963 bool RefreshRateConfigs::isFractionalPairOrMultiple(Fps smaller, Fps bigger) {
964     if (isStrictlyLess(bigger, smaller)) {
965         return isFractionalPairOrMultiple(bigger, smaller);
966     }
967 
968     const auto multiplier = std::round(bigger.getValue() / smaller.getValue());
969     constexpr float kCoef = 1000.f / 1001.f;
970     return isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier / kCoef)) ||
971             isApproxEqual(bigger, Fps::fromValue(smaller.getValue() * multiplier * kCoef));
972 }
973 
dump(std::string & result) const974 void RefreshRateConfigs::dump(std::string& result) const {
975     using namespace std::string_literals;
976 
977     std::lock_guard lock(mLock);
978 
979     const auto activeModeId = mActiveModeIt->first;
980     result += "   activeModeId="s;
981     result += std::to_string(activeModeId.value());
982 
983     result += "\n   displayModes=\n"s;
984     for (const auto& [id, mode] : mDisplayModes) {
985         result += "      "s;
986         result += to_string(*mode);
987         result += '\n';
988     }
989 
990     base::StringAppendF(&result, "   displayManagerPolicy=%s\n",
991                         mDisplayManagerPolicy.toString().c_str());
992 
993     if (const Policy& currentPolicy = *getCurrentPolicyLocked();
994         mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
995         base::StringAppendF(&result, "   overridePolicy=%s\n", currentPolicy.toString().c_str());
996     }
997 
998     base::StringAppendF(&result, "   supportsFrameRateOverrideByContent=%s\n",
999                         mSupportsFrameRateOverrideByContent ? "true" : "false");
1000 
1001     result += "   idleTimer="s;
1002     if (mIdleTimer) {
1003         result += mIdleTimer->dump();
1004     } else {
1005         result += "off"s;
1006     }
1007 
1008     if (const auto controller = mConfig.kernelIdleTimerController) {
1009         base::StringAppendF(&result, " (kernel via %s)", ftl::enum_string(*controller).c_str());
1010     } else {
1011         result += " (platform)"s;
1012     }
1013 
1014     result += '\n';
1015 }
1016 
getIdleTimerTimeout()1017 std::chrono::milliseconds RefreshRateConfigs::getIdleTimerTimeout() {
1018     return mConfig.idleTimerTimeout;
1019 }
1020 
1021 } // namespace android::scheduler
1022 
1023 // TODO(b/129481165): remove the #pragma below and fix conversion issues
1024 #pragma clang diagnostic pop // ignored "-Wextra"
1025