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 "RefreshRateConfigs.h"
25 #include <android-base/properties.h>
26 #include <android-base/stringprintf.h>
27 #include <utils/Trace.h>
28 #include <chrono>
29 #include <cmath>
30 #include "../SurfaceFlingerProperties.h"
31 
32 #undef LOG_TAG
33 #define LOG_TAG "RefreshRateConfigs"
34 
35 namespace android::scheduler {
36 namespace {
formatLayerInfo(const RefreshRateConfigs::LayerRequirement & layer,float weight)37 std::string formatLayerInfo(const RefreshRateConfigs::LayerRequirement& layer, float weight) {
38     return base::StringPrintf("%s (type=%s, weight=%.2f seamlessness=%s) %s", layer.name.c_str(),
39                               RefreshRateConfigs::layerVoteTypeString(layer.vote).c_str(), weight,
40                               toString(layer.seamlessness).c_str(),
41                               to_string(layer.desiredRefreshRate).c_str());
42 }
43 
constructKnownFrameRates(const DisplayModes & modes)44 std::vector<Fps> constructKnownFrameRates(const DisplayModes& modes) {
45     std::vector<Fps> knownFrameRates = {Fps(24.0f), Fps(30.0f), Fps(45.0f), Fps(60.0f), Fps(72.0f)};
46     knownFrameRates.reserve(knownFrameRates.size() + modes.size());
47 
48     // Add all supported refresh rates to the set
49     for (const auto& mode : modes) {
50         const auto refreshRate = Fps::fromPeriodNsecs(mode->getVsyncPeriod());
51         knownFrameRates.emplace_back(refreshRate);
52     }
53 
54     // Sort and remove duplicates
55     std::sort(knownFrameRates.begin(), knownFrameRates.end(), Fps::comparesLess);
56     knownFrameRates.erase(std::unique(knownFrameRates.begin(), knownFrameRates.end(),
57                                       Fps::EqualsWithMargin()),
58                           knownFrameRates.end());
59     return knownFrameRates;
60 }
61 
62 } // namespace
63 
64 using AllRefreshRatesMapType = RefreshRateConfigs::AllRefreshRatesMapType;
65 using RefreshRate = RefreshRateConfigs::RefreshRate;
66 
toString() const67 std::string RefreshRate::toString() const {
68     return base::StringPrintf("{id=%d, hwcId=%d, fps=%.2f, width=%d, height=%d group=%d}",
69                               getModeId().value(), mode->getHwcId(), getFps().getValue(),
70                               mode->getWidth(), mode->getHeight(), getModeGroup());
71 }
72 
layerVoteTypeString(LayerVoteType vote)73 std::string RefreshRateConfigs::layerVoteTypeString(LayerVoteType vote) {
74     switch (vote) {
75         case LayerVoteType::NoVote:
76             return "NoVote";
77         case LayerVoteType::Min:
78             return "Min";
79         case LayerVoteType::Max:
80             return "Max";
81         case LayerVoteType::Heuristic:
82             return "Heuristic";
83         case LayerVoteType::ExplicitDefault:
84             return "ExplicitDefault";
85         case LayerVoteType::ExplicitExactOrMultiple:
86             return "ExplicitExactOrMultiple";
87         case LayerVoteType::ExplicitExact:
88             return "ExplicitExact";
89     }
90 }
91 
toString() const92 std::string RefreshRateConfigs::Policy::toString() const {
93     return base::StringPrintf("default mode ID: %d, allowGroupSwitching = %d"
94                               ", primary range: %s, app request range: %s",
95                               defaultMode.value(), allowGroupSwitching,
96                               primaryRange.toString().c_str(), appRequestRange.toString().c_str());
97 }
98 
getDisplayFrames(nsecs_t layerPeriod,nsecs_t displayPeriod) const99 std::pair<nsecs_t, nsecs_t> RefreshRateConfigs::getDisplayFrames(nsecs_t layerPeriod,
100                                                                  nsecs_t displayPeriod) const {
101     auto [quotient, remainder] = std::div(layerPeriod, displayPeriod);
102     if (remainder <= MARGIN_FOR_PERIOD_CALCULATION ||
103         std::abs(remainder - displayPeriod) <= MARGIN_FOR_PERIOD_CALCULATION) {
104         quotient++;
105         remainder = 0;
106     }
107 
108     return {quotient, remainder};
109 }
110 
isVoteAllowed(const LayerRequirement & layer,const RefreshRate & refreshRate) const111 bool RefreshRateConfigs::isVoteAllowed(const LayerRequirement& layer,
112                                        const RefreshRate& refreshRate) const {
113     switch (layer.vote) {
114         case LayerVoteType::ExplicitExactOrMultiple:
115         case LayerVoteType::Heuristic:
116             if (mConfig.frameRateMultipleThreshold != 0 &&
117                 refreshRate.getFps().greaterThanOrEqualWithMargin(
118                         Fps(mConfig.frameRateMultipleThreshold)) &&
119                 layer.desiredRefreshRate.lessThanWithMargin(
120                         Fps(mConfig.frameRateMultipleThreshold / 2))) {
121                 // Don't vote high refresh rates past the threshold for layers with a low desired
122                 // refresh rate. For example, desired 24 fps with 120 Hz threshold means no vote for
123                 // 120 Hz, but desired 60 fps should have a vote.
124                 return false;
125             }
126             break;
127         case LayerVoteType::ExplicitDefault:
128         case LayerVoteType::ExplicitExact:
129         case LayerVoteType::Max:
130         case LayerVoteType::Min:
131         case LayerVoteType::NoVote:
132             break;
133     }
134     return true;
135 }
136 
calculateLayerScoreLocked(const LayerRequirement & layer,const RefreshRate & refreshRate,bool isSeamlessSwitch) const137 float RefreshRateConfigs::calculateLayerScoreLocked(const LayerRequirement& layer,
138                                                     const RefreshRate& refreshRate,
139                                                     bool isSeamlessSwitch) const {
140     if (!isVoteAllowed(layer, refreshRate)) {
141         return 0;
142     }
143 
144     // Slightly prefer seamless switches.
145     constexpr float kSeamedSwitchPenalty = 0.95f;
146     const float seamlessness = isSeamlessSwitch ? 1.0f : kSeamedSwitchPenalty;
147 
148     // If the layer wants Max, give higher score to the higher refresh rate
149     if (layer.vote == LayerVoteType::Max) {
150         const auto ratio = refreshRate.getFps().getValue() /
151                 mAppRequestRefreshRates.back()->getFps().getValue();
152         // use ratio^2 to get a lower score the more we get further from peak
153         return ratio * ratio;
154     }
155 
156     const auto displayPeriod = refreshRate.getVsyncPeriod();
157     const auto layerPeriod = layer.desiredRefreshRate.getPeriodNsecs();
158     if (layer.vote == LayerVoteType::ExplicitDefault) {
159         // Find the actual rate the layer will render, assuming
160         // that layerPeriod is the minimal time to render a frame
161         auto actualLayerPeriod = displayPeriod;
162         int multiplier = 1;
163         while (layerPeriod > actualLayerPeriod + MARGIN_FOR_PERIOD_CALCULATION) {
164             multiplier++;
165             actualLayerPeriod = displayPeriod * multiplier;
166         }
167         return std::min(1.0f,
168                         static_cast<float>(layerPeriod) / static_cast<float>(actualLayerPeriod));
169     }
170 
171     if (layer.vote == LayerVoteType::ExplicitExactOrMultiple ||
172         layer.vote == LayerVoteType::Heuristic) {
173         // Calculate how many display vsyncs we need to present a single frame for this
174         // layer
175         const auto [displayFramesQuotient, displayFramesRemainder] =
176                 getDisplayFrames(layerPeriod, displayPeriod);
177         static constexpr size_t MAX_FRAMES_TO_FIT = 10; // Stop calculating when score < 0.1
178         if (displayFramesRemainder == 0) {
179             // Layer desired refresh rate matches the display rate.
180             return 1.0f * seamlessness;
181         }
182 
183         if (displayFramesQuotient == 0) {
184             // Layer desired refresh rate is higher than the display rate.
185             return (static_cast<float>(layerPeriod) / static_cast<float>(displayPeriod)) *
186                     (1.0f / (MAX_FRAMES_TO_FIT + 1));
187         }
188 
189         // Layer desired refresh rate is lower than the display rate. Check how well it fits
190         // the cadence.
191         auto diff = std::abs(displayFramesRemainder - (displayPeriod - displayFramesRemainder));
192         int iter = 2;
193         while (diff > MARGIN_FOR_PERIOD_CALCULATION && iter < MAX_FRAMES_TO_FIT) {
194             diff = diff - (displayPeriod - diff);
195             iter++;
196         }
197 
198         return (1.0f / iter) * seamlessness;
199     }
200 
201     if (layer.vote == LayerVoteType::ExplicitExact) {
202         const int divider = getFrameRateDivider(refreshRate.getFps(), layer.desiredRefreshRate);
203         if (mSupportsFrameRateOverride) {
204             // Since we support frame rate override, allow refresh rates which are
205             // multiples of the layer's request, as those apps would be throttled
206             // down to run at the desired refresh rate.
207             return divider > 0;
208         }
209 
210         return divider == 1;
211     }
212 
213     return 0;
214 }
215 
216 struct RefreshRateScore {
217     const RefreshRate* refreshRate;
218     float score;
219 };
220 
getBestRefreshRate(const std::vector<LayerRequirement> & layers,const GlobalSignals & globalSignals,GlobalSignals * outSignalsConsidered) const221 RefreshRate RefreshRateConfigs::getBestRefreshRate(const std::vector<LayerRequirement>& layers,
222                                                    const GlobalSignals& globalSignals,
223                                                    GlobalSignals* outSignalsConsidered) const {
224     std::lock_guard lock(mLock);
225 
226     if (auto cached = getCachedBestRefreshRate(layers, globalSignals, outSignalsConsidered)) {
227         return *cached;
228     }
229 
230     GlobalSignals signalsConsidered;
231     RefreshRate result = getBestRefreshRateLocked(layers, globalSignals, &signalsConsidered);
232     lastBestRefreshRateInvocation.emplace(
233             GetBestRefreshRateInvocation{.layerRequirements = layers,
234                                          .globalSignals = globalSignals,
235                                          .outSignalsConsidered = signalsConsidered,
236                                          .resultingBestRefreshRate = result});
237     if (outSignalsConsidered) {
238         *outSignalsConsidered = signalsConsidered;
239     }
240     return result;
241 }
242 
getCachedBestRefreshRate(const std::vector<LayerRequirement> & layers,const GlobalSignals & globalSignals,GlobalSignals * outSignalsConsidered) const243 std::optional<RefreshRate> RefreshRateConfigs::getCachedBestRefreshRate(
244         const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
245         GlobalSignals* outSignalsConsidered) const {
246     const bool sameAsLastCall = lastBestRefreshRateInvocation &&
247             lastBestRefreshRateInvocation->layerRequirements == layers &&
248             lastBestRefreshRateInvocation->globalSignals == globalSignals;
249 
250     if (sameAsLastCall) {
251         if (outSignalsConsidered) {
252             *outSignalsConsidered = lastBestRefreshRateInvocation->outSignalsConsidered;
253         }
254         return lastBestRefreshRateInvocation->resultingBestRefreshRate;
255     }
256 
257     return {};
258 }
259 
getBestRefreshRateLocked(const std::vector<LayerRequirement> & layers,const GlobalSignals & globalSignals,GlobalSignals * outSignalsConsidered) const260 RefreshRate RefreshRateConfigs::getBestRefreshRateLocked(
261         const std::vector<LayerRequirement>& layers, const GlobalSignals& globalSignals,
262         GlobalSignals* outSignalsConsidered) const {
263     ATRACE_CALL();
264     ALOGV("getBestRefreshRate %zu layers", layers.size());
265 
266     if (outSignalsConsidered) *outSignalsConsidered = {};
267     const auto setTouchConsidered = [&] {
268         if (outSignalsConsidered) {
269             outSignalsConsidered->touch = true;
270         }
271     };
272 
273     const auto setIdleConsidered = [&] {
274         if (outSignalsConsidered) {
275             outSignalsConsidered->idle = true;
276         }
277     };
278 
279     int noVoteLayers = 0;
280     int minVoteLayers = 0;
281     int maxVoteLayers = 0;
282     int explicitDefaultVoteLayers = 0;
283     int explicitExactOrMultipleVoteLayers = 0;
284     int explicitExact = 0;
285     float maxExplicitWeight = 0;
286     int seamedFocusedLayers = 0;
287     for (const auto& layer : layers) {
288         switch (layer.vote) {
289             case LayerVoteType::NoVote:
290                 noVoteLayers++;
291                 break;
292             case LayerVoteType::Min:
293                 minVoteLayers++;
294                 break;
295             case LayerVoteType::Max:
296                 maxVoteLayers++;
297                 break;
298             case LayerVoteType::ExplicitDefault:
299                 explicitDefaultVoteLayers++;
300                 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
301                 break;
302             case LayerVoteType::ExplicitExactOrMultiple:
303                 explicitExactOrMultipleVoteLayers++;
304                 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
305                 break;
306             case LayerVoteType::ExplicitExact:
307                 explicitExact++;
308                 maxExplicitWeight = std::max(maxExplicitWeight, layer.weight);
309                 break;
310             case LayerVoteType::Heuristic:
311                 break;
312         }
313 
314         if (layer.seamlessness == Seamlessness::SeamedAndSeamless && layer.focused) {
315             seamedFocusedLayers++;
316         }
317     }
318 
319     const bool hasExplicitVoteLayers = explicitDefaultVoteLayers > 0 ||
320             explicitExactOrMultipleVoteLayers > 0 || explicitExact > 0;
321 
322     // Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
323     // selected a refresh rate to see if we should apply touch boost.
324     if (globalSignals.touch && !hasExplicitVoteLayers) {
325         ALOGV("TouchBoost - choose %s", getMaxRefreshRateByPolicyLocked().getName().c_str());
326         setTouchConsidered();
327         return getMaxRefreshRateByPolicyLocked();
328     }
329 
330     // If the primary range consists of a single refresh rate then we can only
331     // move out the of range if layers explicitly request a different refresh
332     // rate.
333     const Policy* policy = getCurrentPolicyLocked();
334     const bool primaryRangeIsSingleRate =
335             policy->primaryRange.min.equalsWithMargin(policy->primaryRange.max);
336 
337     if (!globalSignals.touch && globalSignals.idle &&
338         !(primaryRangeIsSingleRate && hasExplicitVoteLayers)) {
339         ALOGV("Idle - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
340         setIdleConsidered();
341         return getMinRefreshRateByPolicyLocked();
342     }
343 
344     if (layers.empty() || noVoteLayers == layers.size()) {
345         return getMaxRefreshRateByPolicyLocked();
346     }
347 
348     // Only if all layers want Min we should return Min
349     if (noVoteLayers + minVoteLayers == layers.size()) {
350         ALOGV("all layers Min - choose %s", getMinRefreshRateByPolicyLocked().getName().c_str());
351         return getMinRefreshRateByPolicyLocked();
352     }
353 
354     // Find the best refresh rate based on score
355     std::vector<RefreshRateScore> scores;
356     scores.reserve(mAppRequestRefreshRates.size());
357 
358     for (const auto refreshRate : mAppRequestRefreshRates) {
359         scores.emplace_back(RefreshRateScore{refreshRate, 0.0f});
360     }
361 
362     const auto& defaultMode = mRefreshRates.at(policy->defaultMode);
363 
364     for (const auto& layer : layers) {
365         ALOGV("Calculating score for %s (%s, weight %.2f, desired %.2f) ", layer.name.c_str(),
366               layerVoteTypeString(layer.vote).c_str(), layer.weight,
367               layer.desiredRefreshRate.getValue());
368         if (layer.vote == LayerVoteType::NoVote || layer.vote == LayerVoteType::Min) {
369             continue;
370         }
371 
372         auto weight = layer.weight;
373 
374         for (auto i = 0u; i < scores.size(); i++) {
375             const bool isSeamlessSwitch =
376                     scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup();
377 
378             if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
379                 ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
380                       formatLayerInfo(layer, weight).c_str(),
381                       scores[i].refreshRate->toString().c_str(),
382                       mCurrentRefreshRate->toString().c_str());
383                 continue;
384             }
385 
386             if (layer.seamlessness == Seamlessness::SeamedAndSeamless && !isSeamlessSwitch &&
387                 !layer.focused) {
388                 ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
389                       " Current mode = %s",
390                       formatLayerInfo(layer, weight).c_str(),
391                       scores[i].refreshRate->toString().c_str(),
392                       mCurrentRefreshRate->toString().c_str());
393                 continue;
394             }
395 
396             // Layers with default seamlessness vote for the current mode group if
397             // there are layers with seamlessness=SeamedAndSeamless and for the default
398             // mode group otherwise. In second case, if the current mode group is different
399             // from the default, this means a layer with seamlessness=SeamedAndSeamless has just
400             // disappeared.
401             const bool isInPolicyForDefault = seamedFocusedLayers > 0
402                     ? scores[i].refreshRate->getModeGroup() == mCurrentRefreshRate->getModeGroup()
403                     : scores[i].refreshRate->getModeGroup() == defaultMode->getModeGroup();
404 
405             if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
406                 ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
407                       scores[i].refreshRate->toString().c_str(),
408                       mCurrentRefreshRate->toString().c_str());
409                 continue;
410             }
411 
412             bool inPrimaryRange = scores[i].refreshRate->inPolicy(policy->primaryRange.min,
413                                                                   policy->primaryRange.max);
414             if ((primaryRangeIsSingleRate || !inPrimaryRange) &&
415                 !(layer.focused &&
416                   (layer.vote == LayerVoteType::ExplicitDefault ||
417                    layer.vote == LayerVoteType::ExplicitExact))) {
418                 // Only focused layers with ExplicitDefault frame rate settings are allowed to score
419                 // refresh rates outside the primary range.
420                 continue;
421             }
422 
423             const auto layerScore =
424                     calculateLayerScoreLocked(layer, *scores[i].refreshRate, isSeamlessSwitch);
425             ALOGV("%s gives %s score of %.2f", formatLayerInfo(layer, weight).c_str(),
426                   scores[i].refreshRate->getName().c_str(), layerScore);
427             scores[i].score += weight * layerScore;
428         }
429     }
430 
431     // Now that we scored all the refresh rates we need to pick the one that got the highest score.
432     // In case of a tie we will pick the higher refresh rate if any of the layers wanted Max,
433     // or the lower otherwise.
434     const RefreshRate* bestRefreshRate = maxVoteLayers > 0
435             ? getBestRefreshRate(scores.rbegin(), scores.rend())
436             : getBestRefreshRate(scores.begin(), scores.end());
437 
438     if (primaryRangeIsSingleRate) {
439         // If we never scored any layers, then choose the rate from the primary
440         // range instead of picking a random score from the app range.
441         if (std::all_of(scores.begin(), scores.end(),
442                         [](RefreshRateScore score) { return score.score == 0; })) {
443             ALOGV("layers not scored - choose %s",
444                   getMaxRefreshRateByPolicyLocked().getName().c_str());
445             return getMaxRefreshRateByPolicyLocked();
446         } else {
447             return *bestRefreshRate;
448         }
449     }
450 
451     // Consider the touch event if there are no ExplicitDefault layers. ExplicitDefault are mostly
452     // interactive (as opposed to ExplicitExactOrMultiple) and therefore if those posted an explicit
453     // vote we should not change it if we get a touch event. Only apply touch boost if it will
454     // actually increase the refresh rate over the normal selection.
455     const RefreshRate& touchRefreshRate = getMaxRefreshRateByPolicyLocked();
456 
457     const bool touchBoostForExplicitExact = [&] {
458         if (mSupportsFrameRateOverride) {
459             // Enable touch boost if there are other layers besides exact
460             return explicitExact + noVoteLayers != layers.size();
461         } else {
462             // Enable touch boost if there are no exact layers
463             return explicitExact == 0;
464         }
465     }();
466     if (globalSignals.touch && explicitDefaultVoteLayers == 0 && touchBoostForExplicitExact &&
467         bestRefreshRate->getFps().lessThanWithMargin(touchRefreshRate.getFps())) {
468         setTouchConsidered();
469         ALOGV("TouchBoost - choose %s", touchRefreshRate.getName().c_str());
470         return touchRefreshRate;
471     }
472 
473     return *bestRefreshRate;
474 }
475 
476 std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>>
groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement> & layers)477 groupLayersByUid(const std::vector<RefreshRateConfigs::LayerRequirement>& layers) {
478     std::unordered_map<uid_t, std::vector<const RefreshRateConfigs::LayerRequirement*>> layersByUid;
479     for (const auto& layer : layers) {
480         auto iter = layersByUid.emplace(layer.ownerUid,
481                                         std::vector<const RefreshRateConfigs::LayerRequirement*>());
482         auto& layersWithSameUid = iter.first->second;
483         layersWithSameUid.push_back(&layer);
484     }
485 
486     // Remove uids that can't have a frame rate override
487     for (auto iter = layersByUid.begin(); iter != layersByUid.end();) {
488         const auto& layersWithSameUid = iter->second;
489         bool skipUid = false;
490         for (const auto& layer : layersWithSameUid) {
491             if (layer->vote == RefreshRateConfigs::LayerVoteType::Max ||
492                 layer->vote == RefreshRateConfigs::LayerVoteType::Heuristic) {
493                 skipUid = true;
494                 break;
495             }
496         }
497         if (skipUid) {
498             iter = layersByUid.erase(iter);
499         } else {
500             ++iter;
501         }
502     }
503 
504     return layersByUid;
505 }
506 
initializeScoresForAllRefreshRates(const AllRefreshRatesMapType & refreshRates)507 std::vector<RefreshRateScore> initializeScoresForAllRefreshRates(
508         const AllRefreshRatesMapType& refreshRates) {
509     std::vector<RefreshRateScore> scores;
510     scores.reserve(refreshRates.size());
511     for (const auto& [ignored, refreshRate] : refreshRates) {
512         scores.emplace_back(RefreshRateScore{refreshRate.get(), 0.0f});
513     }
514     std::sort(scores.begin(), scores.end(),
515               [](const auto& a, const auto& b) { return *a.refreshRate < *b.refreshRate; });
516     return scores;
517 }
518 
getFrameRateOverrides(const std::vector<LayerRequirement> & layers,Fps displayFrameRate,bool touch) const519 RefreshRateConfigs::UidToFrameRateOverride RefreshRateConfigs::getFrameRateOverrides(
520         const std::vector<LayerRequirement>& layers, Fps displayFrameRate, bool touch) const {
521     ATRACE_CALL();
522     if (!mSupportsFrameRateOverride) return {};
523 
524     ALOGV("getFrameRateOverrides %zu layers", layers.size());
525     std::lock_guard lock(mLock);
526     std::vector<RefreshRateScore> scores = initializeScoresForAllRefreshRates(mRefreshRates);
527     std::unordered_map<uid_t, std::vector<const LayerRequirement*>> layersByUid =
528             groupLayersByUid(layers);
529     UidToFrameRateOverride frameRateOverrides;
530     for (const auto& [uid, layersWithSameUid] : layersByUid) {
531         // Layers with ExplicitExactOrMultiple expect touch boost
532         const bool hasExplicitExactOrMultiple =
533                 std::any_of(layersWithSameUid.cbegin(), layersWithSameUid.cend(),
534                             [](const auto& layer) {
535                                 return layer->vote == LayerVoteType::ExplicitExactOrMultiple;
536                             });
537 
538         if (touch && hasExplicitExactOrMultiple) {
539             continue;
540         }
541 
542         for (auto& score : scores) {
543             score.score = 0;
544         }
545 
546         for (const auto& layer : layersWithSameUid) {
547             if (layer->vote == LayerVoteType::NoVote || layer->vote == LayerVoteType::Min) {
548                 continue;
549             }
550 
551             LOG_ALWAYS_FATAL_IF(layer->vote != LayerVoteType::ExplicitDefault &&
552                                 layer->vote != LayerVoteType::ExplicitExactOrMultiple &&
553                                 layer->vote != LayerVoteType::ExplicitExact);
554             for (RefreshRateScore& score : scores) {
555                 const auto layerScore = calculateLayerScoreLocked(*layer, *score.refreshRate,
556                                                                   /*isSeamlessSwitch*/ true);
557                 score.score += layer->weight * layerScore;
558             }
559         }
560 
561         // We just care about the refresh rates which are a divider of the
562         // display refresh rate
563         auto iter =
564                 std::remove_if(scores.begin(), scores.end(), [&](const RefreshRateScore& score) {
565                     return getFrameRateDivider(displayFrameRate, score.refreshRate->getFps()) == 0;
566                 });
567         scores.erase(iter, scores.end());
568 
569         // If we never scored any layers, we don't have a preferred frame rate
570         if (std::all_of(scores.begin(), scores.end(),
571                         [](const RefreshRateScore& score) { return score.score == 0; })) {
572             continue;
573         }
574 
575         // Now that we scored all the refresh rates we need to pick the one that got the highest
576         // score.
577         const RefreshRate* bestRefreshRate = getBestRefreshRate(scores.begin(), scores.end());
578         frameRateOverrides.emplace(uid, bestRefreshRate->getFps());
579     }
580 
581     return frameRateOverrides;
582 }
583 
584 template <typename Iter>
getBestRefreshRate(Iter begin,Iter end) const585 const RefreshRate* RefreshRateConfigs::getBestRefreshRate(Iter begin, Iter end) const {
586     constexpr auto EPSILON = 0.001f;
587     const RefreshRate* bestRefreshRate = begin->refreshRate;
588     float max = begin->score;
589     for (auto i = begin; i != end; ++i) {
590         const auto [refreshRate, score] = *i;
591         ALOGV("%s scores %.2f", refreshRate->getName().c_str(), score);
592 
593         ATRACE_INT(refreshRate->getName().c_str(), round<int>(score * 100));
594 
595         if (score > max * (1 + EPSILON)) {
596             max = score;
597             bestRefreshRate = refreshRate;
598         }
599     }
600 
601     return bestRefreshRate;
602 }
603 
onKernelTimerChanged(std::optional<DisplayModeId> desiredActiveConfigId,bool timerExpired) const604 std::optional<Fps> RefreshRateConfigs::onKernelTimerChanged(
605         std::optional<DisplayModeId> desiredActiveConfigId, bool timerExpired) const {
606     std::lock_guard lock(mLock);
607 
608     const auto& current = desiredActiveConfigId ? *mRefreshRates.at(*desiredActiveConfigId)
609                                                 : *mCurrentRefreshRate;
610     const auto& min = *mMinSupportedRefreshRate;
611 
612     if (current != min) {
613         const auto& refreshRate = timerExpired ? min : current;
614         return refreshRate.getFps();
615     }
616 
617     return {};
618 }
619 
getMinRefreshRateByPolicyLocked() const620 const RefreshRate& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
621     for (auto refreshRate : mPrimaryRefreshRates) {
622         if (mCurrentRefreshRate->getModeGroup() == refreshRate->getModeGroup()) {
623             return *refreshRate;
624         }
625     }
626     ALOGE("Can't find min refresh rate by policy with the same mode group"
627           " as the current mode %s",
628           mCurrentRefreshRate->toString().c_str());
629     // Defaulting to the lowest refresh rate
630     return *mPrimaryRefreshRates.front();
631 }
632 
getMaxRefreshRateByPolicy() const633 RefreshRate RefreshRateConfigs::getMaxRefreshRateByPolicy() const {
634     std::lock_guard lock(mLock);
635     return getMaxRefreshRateByPolicyLocked();
636 }
637 
getMaxRefreshRateByPolicyLocked() const638 const RefreshRate& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
639     for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); it++) {
640         const auto& refreshRate = (**it);
641         if (mCurrentRefreshRate->getModeGroup() == refreshRate.getModeGroup()) {
642             return refreshRate;
643         }
644     }
645     ALOGE("Can't find max refresh rate by policy with the same mode group"
646           " as the current mode %s",
647           mCurrentRefreshRate->toString().c_str());
648     // Defaulting to the highest refresh rate
649     return *mPrimaryRefreshRates.back();
650 }
651 
getCurrentRefreshRate() const652 RefreshRate RefreshRateConfigs::getCurrentRefreshRate() const {
653     std::lock_guard lock(mLock);
654     return *mCurrentRefreshRate;
655 }
656 
getCurrentRefreshRateByPolicy() const657 RefreshRate RefreshRateConfigs::getCurrentRefreshRateByPolicy() const {
658     std::lock_guard lock(mLock);
659     return getCurrentRefreshRateByPolicyLocked();
660 }
661 
getCurrentRefreshRateByPolicyLocked() const662 const RefreshRate& RefreshRateConfigs::getCurrentRefreshRateByPolicyLocked() const {
663     if (std::find(mAppRequestRefreshRates.begin(), mAppRequestRefreshRates.end(),
664                   mCurrentRefreshRate) != mAppRequestRefreshRates.end()) {
665         return *mCurrentRefreshRate;
666     }
667     return *mRefreshRates.at(getCurrentPolicyLocked()->defaultMode);
668 }
669 
setCurrentModeId(DisplayModeId modeId)670 void RefreshRateConfigs::setCurrentModeId(DisplayModeId modeId) {
671     std::lock_guard lock(mLock);
672 
673     // Invalidate the cached invocation to getBestRefreshRate. This forces
674     // the refresh rate to be recomputed on the next call to getBestRefreshRate.
675     lastBestRefreshRateInvocation.reset();
676 
677     mCurrentRefreshRate = mRefreshRates.at(modeId).get();
678 }
679 
RefreshRateConfigs(const DisplayModes & modes,DisplayModeId currentModeId,Config config)680 RefreshRateConfigs::RefreshRateConfigs(const DisplayModes& modes, DisplayModeId currentModeId,
681                                        Config config)
682       : mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
683     initializeIdleTimer();
684     updateDisplayModes(modes, currentModeId);
685 }
686 
initializeIdleTimer()687 void RefreshRateConfigs::initializeIdleTimer() {
688     if (mConfig.idleTimerTimeoutMs > 0) {
689         const auto getCallback = [this]() -> std::optional<IdleTimerCallbacks::Callbacks> {
690             std::scoped_lock lock(mIdleTimerCallbacksMutex);
691             if (!mIdleTimerCallbacks.has_value()) return {};
692             return mConfig.supportKernelIdleTimer ? mIdleTimerCallbacks->kernel
693                                                   : mIdleTimerCallbacks->platform;
694         };
695 
696         mIdleTimer.emplace(
697                 "IdleTimer", std::chrono::milliseconds(mConfig.idleTimerTimeoutMs),
698                 [getCallback] {
699                     if (const auto callback = getCallback()) callback->onReset();
700                 },
701                 [getCallback] {
702                     if (const auto callback = getCallback()) callback->onExpired();
703                 });
704     }
705 }
706 
updateDisplayModes(const DisplayModes & modes,DisplayModeId currentModeId)707 void RefreshRateConfigs::updateDisplayModes(const DisplayModes& modes,
708                                             DisplayModeId currentModeId) {
709     std::lock_guard lock(mLock);
710 
711     // The current mode should be supported
712     LOG_ALWAYS_FATAL_IF(std::none_of(modes.begin(), modes.end(), [&](DisplayModePtr mode) {
713         return mode->getId() == currentModeId;
714     }));
715 
716     // Invalidate the cached invocation to getBestRefreshRate. This forces
717     // the refresh rate to be recomputed on the next call to getBestRefreshRate.
718     lastBestRefreshRateInvocation.reset();
719 
720     mRefreshRates.clear();
721     for (const auto& mode : modes) {
722         const auto modeId = mode->getId();
723         mRefreshRates.emplace(modeId,
724                               std::make_unique<RefreshRate>(mode, RefreshRate::ConstructorTag(0)));
725         if (modeId == currentModeId) {
726             mCurrentRefreshRate = mRefreshRates.at(modeId).get();
727         }
728     }
729 
730     std::vector<const RefreshRate*> sortedModes;
731     getSortedRefreshRateListLocked([](const RefreshRate&) { return true; }, &sortedModes);
732     // Reset the policy because the old one may no longer be valid.
733     mDisplayManagerPolicy = {};
734     mDisplayManagerPolicy.defaultMode = currentModeId;
735     mMinSupportedRefreshRate = sortedModes.front();
736     mMaxSupportedRefreshRate = sortedModes.back();
737 
738     mSupportsFrameRateOverride = false;
739     if (mConfig.enableFrameRateOverride) {
740         for (const auto& mode1 : sortedModes) {
741             for (const auto& mode2 : sortedModes) {
742                 if (getFrameRateDivider(mode1->getFps(), mode2->getFps()) >= 2) {
743                     mSupportsFrameRateOverride = true;
744                     break;
745                 }
746             }
747         }
748     }
749 
750     constructAvailableRefreshRates();
751 }
752 
isPolicyValidLocked(const Policy & policy) const753 bool RefreshRateConfigs::isPolicyValidLocked(const Policy& policy) const {
754     // defaultMode must be a valid mode, and within the given refresh rate range.
755     auto iter = mRefreshRates.find(policy.defaultMode);
756     if (iter == mRefreshRates.end()) {
757         ALOGE("Default mode is not found.");
758         return false;
759     }
760     const RefreshRate& refreshRate = *iter->second;
761     if (!refreshRate.inPolicy(policy.primaryRange.min, policy.primaryRange.max)) {
762         ALOGE("Default mode is not in the primary range.");
763         return false;
764     }
765     return policy.appRequestRange.min.lessThanOrEqualWithMargin(policy.primaryRange.min) &&
766             policy.appRequestRange.max.greaterThanOrEqualWithMargin(policy.primaryRange.max);
767 }
768 
setDisplayManagerPolicy(const Policy & policy)769 status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
770     std::lock_guard lock(mLock);
771     if (!isPolicyValidLocked(policy)) {
772         ALOGE("Invalid refresh rate policy: %s", policy.toString().c_str());
773         return BAD_VALUE;
774     }
775     lastBestRefreshRateInvocation.reset();
776     Policy previousPolicy = *getCurrentPolicyLocked();
777     mDisplayManagerPolicy = policy;
778     if (*getCurrentPolicyLocked() == previousPolicy) {
779         return CURRENT_POLICY_UNCHANGED;
780     }
781     constructAvailableRefreshRates();
782     return NO_ERROR;
783 }
784 
setOverridePolicy(const std::optional<Policy> & policy)785 status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
786     std::lock_guard lock(mLock);
787     if (policy && !isPolicyValidLocked(*policy)) {
788         return BAD_VALUE;
789     }
790     lastBestRefreshRateInvocation.reset();
791     Policy previousPolicy = *getCurrentPolicyLocked();
792     mOverridePolicy = policy;
793     if (*getCurrentPolicyLocked() == previousPolicy) {
794         return CURRENT_POLICY_UNCHANGED;
795     }
796     constructAvailableRefreshRates();
797     return NO_ERROR;
798 }
799 
getCurrentPolicyLocked() const800 const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
801     return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
802 }
803 
getCurrentPolicy() const804 RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
805     std::lock_guard lock(mLock);
806     return *getCurrentPolicyLocked();
807 }
808 
getDisplayManagerPolicy() const809 RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
810     std::lock_guard lock(mLock);
811     return mDisplayManagerPolicy;
812 }
813 
isModeAllowed(DisplayModeId modeId) const814 bool RefreshRateConfigs::isModeAllowed(DisplayModeId modeId) const {
815     std::lock_guard lock(mLock);
816     for (const RefreshRate* refreshRate : mAppRequestRefreshRates) {
817         if (refreshRate->getModeId() == modeId) {
818             return true;
819         }
820     }
821     return false;
822 }
823 
getSortedRefreshRateListLocked(const std::function<bool (const RefreshRate &)> & shouldAddRefreshRate,std::vector<const RefreshRate * > * outRefreshRates)824 void RefreshRateConfigs::getSortedRefreshRateListLocked(
825         const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
826         std::vector<const RefreshRate*>* outRefreshRates) {
827     outRefreshRates->clear();
828     outRefreshRates->reserve(mRefreshRates.size());
829     for (const auto& [type, refreshRate] : mRefreshRates) {
830         if (shouldAddRefreshRate(*refreshRate)) {
831             ALOGV("getSortedRefreshRateListLocked: mode %d added to list policy",
832                   refreshRate->getModeId().value());
833             outRefreshRates->push_back(refreshRate.get());
834         }
835     }
836 
837     std::sort(outRefreshRates->begin(), outRefreshRates->end(),
838               [](const auto refreshRate1, const auto refreshRate2) {
839                   if (refreshRate1->mode->getVsyncPeriod() !=
840                       refreshRate2->mode->getVsyncPeriod()) {
841                       return refreshRate1->mode->getVsyncPeriod() >
842                               refreshRate2->mode->getVsyncPeriod();
843                   } else {
844                       return refreshRate1->mode->getGroup() > refreshRate2->mode->getGroup();
845                   }
846               });
847 }
848 
constructAvailableRefreshRates()849 void RefreshRateConfigs::constructAvailableRefreshRates() {
850     // Filter modes based on current policy and sort based on vsync period
851     const Policy* policy = getCurrentPolicyLocked();
852     const auto& defaultMode = mRefreshRates.at(policy->defaultMode)->mode;
853     ALOGV("constructAvailableRefreshRates: %s ", policy->toString().c_str());
854 
855     auto filterRefreshRates =
856             [&](Fps min, Fps max, const char* listName,
857                 std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock) {
858                 getSortedRefreshRateListLocked(
859                         [&](const RefreshRate& refreshRate) REQUIRES(mLock) {
860                             const auto& mode = refreshRate.mode;
861 
862                             return mode->getHeight() == defaultMode->getHeight() &&
863                                     mode->getWidth() == defaultMode->getWidth() &&
864                                     mode->getDpiX() == defaultMode->getDpiX() &&
865                                     mode->getDpiY() == defaultMode->getDpiY() &&
866                                     (policy->allowGroupSwitching ||
867                                      mode->getGroup() == defaultMode->getGroup()) &&
868                                     refreshRate.inPolicy(min, max);
869                         },
870                         outRefreshRates);
871 
872                 LOG_ALWAYS_FATAL_IF(outRefreshRates->empty(),
873                                     "No matching modes for %s range: min=%s max=%s", listName,
874                                     to_string(min).c_str(), to_string(max).c_str());
875                 auto stringifyRefreshRates = [&]() -> std::string {
876                     std::string str;
877                     for (auto refreshRate : *outRefreshRates) {
878                         base::StringAppendF(&str, "%s ", refreshRate->getName().c_str());
879                     }
880                     return str;
881                 };
882                 ALOGV("%s refresh rates: %s", listName, stringifyRefreshRates().c_str());
883             };
884 
885     filterRefreshRates(policy->primaryRange.min, policy->primaryRange.max, "primary",
886                        &mPrimaryRefreshRates);
887     filterRefreshRates(policy->appRequestRange.min, policy->appRequestRange.max, "app request",
888                        &mAppRequestRefreshRates);
889 }
890 
findClosestKnownFrameRate(Fps frameRate) const891 Fps RefreshRateConfigs::findClosestKnownFrameRate(Fps frameRate) const {
892     if (frameRate.lessThanOrEqualWithMargin(*mKnownFrameRates.begin())) {
893         return *mKnownFrameRates.begin();
894     }
895 
896     if (frameRate.greaterThanOrEqualWithMargin(*std::prev(mKnownFrameRates.end()))) {
897         return *std::prev(mKnownFrameRates.end());
898     }
899 
900     auto lowerBound = std::lower_bound(mKnownFrameRates.begin(), mKnownFrameRates.end(), frameRate,
901                                        Fps::comparesLess);
902 
903     const auto distance1 = std::abs((frameRate.getValue() - lowerBound->getValue()));
904     const auto distance2 = std::abs((frameRate.getValue() - std::prev(lowerBound)->getValue()));
905     return distance1 < distance2 ? *lowerBound : *std::prev(lowerBound);
906 }
907 
getIdleTimerAction() const908 RefreshRateConfigs::KernelIdleTimerAction RefreshRateConfigs::getIdleTimerAction() const {
909     std::lock_guard lock(mLock);
910     const auto& deviceMin = *mMinSupportedRefreshRate;
911     const auto& minByPolicy = getMinRefreshRateByPolicyLocked();
912     const auto& maxByPolicy = getMaxRefreshRateByPolicyLocked();
913     const auto& currentPolicy = getCurrentPolicyLocked();
914 
915     // Kernel idle timer will set the refresh rate to the device min. If DisplayManager says that
916     // the min allowed refresh rate is higher than the device min, we do not want to enable the
917     // timer.
918     if (deviceMin < minByPolicy) {
919         return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
920     }
921     if (minByPolicy == maxByPolicy) {
922         // when min primary range in display manager policy is below device min turn on the timer.
923         if (currentPolicy->primaryRange.min.lessThanWithMargin(deviceMin.getFps())) {
924             return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
925         }
926         return RefreshRateConfigs::KernelIdleTimerAction::TurnOff;
927     }
928     // Turn on the timer in all other cases.
929     return RefreshRateConfigs::KernelIdleTimerAction::TurnOn;
930 }
931 
getFrameRateDivider(Fps displayFrameRate,Fps layerFrameRate)932 int RefreshRateConfigs::getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate) {
933     // This calculation needs to be in sync with the java code
934     // in DisplayManagerService.getDisplayInfoForFrameRateOverride
935 
936     // The threshold must be smaller than 0.001 in order to differentiate
937     // between the fractional pairs (e.g. 59.94 and 60).
938     constexpr float kThreshold = 0.0009f;
939     const auto numPeriods = displayFrameRate.getValue() / layerFrameRate.getValue();
940     const auto numPeriodsRounded = std::round(numPeriods);
941     if (std::abs(numPeriods - numPeriodsRounded) > kThreshold) {
942         return 0;
943     }
944 
945     return static_cast<int>(numPeriodsRounded);
946 }
947 
dump(std::string & result) const948 void RefreshRateConfigs::dump(std::string& result) const {
949     std::lock_guard lock(mLock);
950     base::StringAppendF(&result, "DesiredDisplayModeSpecs (DisplayManager): %s\n\n",
951                         mDisplayManagerPolicy.toString().c_str());
952     scheduler::RefreshRateConfigs::Policy currentPolicy = *getCurrentPolicyLocked();
953     if (mOverridePolicy && currentPolicy != mDisplayManagerPolicy) {
954         base::StringAppendF(&result, "DesiredDisplayModeSpecs (Override): %s\n\n",
955                             currentPolicy.toString().c_str());
956     }
957 
958     auto mode = mCurrentRefreshRate->mode;
959     base::StringAppendF(&result, "Current mode: %s\n", mCurrentRefreshRate->toString().c_str());
960 
961     result.append("Refresh rates:\n");
962     for (const auto& [id, refreshRate] : mRefreshRates) {
963         mode = refreshRate->mode;
964         base::StringAppendF(&result, "\t%s\n", refreshRate->toString().c_str());
965     }
966 
967     base::StringAppendF(&result, "Supports Frame Rate Override: %s\n",
968                         mSupportsFrameRateOverride ? "yes" : "no");
969     base::StringAppendF(&result, "Idle timer: (%s) %s\n",
970                         mConfig.supportKernelIdleTimer ? "kernel" : "platform",
971                         mIdleTimer ? mIdleTimer->dump().c_str() : "off");
972     result.append("\n");
973 }
974 
975 } // namespace android::scheduler
976 
977 // TODO(b/129481165): remove the #pragma below and fix conversion issues
978 #pragma clang diagnostic pop // ignored "-Wextra"
979