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 #pragma once
18 
19 #include <android-base/stringprintf.h>
20 #include <gui/DisplayEventReceiver.h>
21 
22 #include <algorithm>
23 #include <numeric>
24 #include <optional>
25 #include <type_traits>
26 
27 #include "DisplayHardware/DisplayMode.h"
28 #include "DisplayHardware/HWComposer.h"
29 #include "Fps.h"
30 #include "Scheduler/OneShotTimer.h"
31 #include "Scheduler/SchedulerUtils.h"
32 #include "Scheduler/Seamlessness.h"
33 #include "Scheduler/StrongTyping.h"
34 
35 namespace android::scheduler {
36 
37 using namespace std::chrono_literals;
38 
39 enum class RefreshRateConfigEvent : unsigned { None = 0b0, Changed = 0b1 };
40 
41 inline RefreshRateConfigEvent operator|(RefreshRateConfigEvent lhs, RefreshRateConfigEvent rhs) {
42     using T = std::underlying_type_t<RefreshRateConfigEvent>;
43     return static_cast<RefreshRateConfigEvent>(static_cast<T>(lhs) | static_cast<T>(rhs));
44 }
45 
46 using FrameRateOverride = DisplayEventReceiver::Event::FrameRateOverride;
47 
48 /**
49  * This class is used to encapsulate configuration for refresh rates. It holds information
50  * about available refresh rates on the device, and the mapping between the numbers and human
51  * readable names.
52  */
53 class RefreshRateConfigs {
54 public:
55     // Margin used when matching refresh rates to the content desired ones.
56     static constexpr nsecs_t MARGIN_FOR_PERIOD_CALCULATION =
57             std::chrono::nanoseconds(800us).count();
58 
59     class RefreshRate {
60     private:
61         // Effectively making the constructor private while allowing
62         // std::make_unique to create the object
63         struct ConstructorTag {
ConstructorTagConstructorTag64             explicit ConstructorTag(int) {}
65         };
66 
67     public:
RefreshRate(DisplayModePtr mode,ConstructorTag)68         RefreshRate(DisplayModePtr mode, ConstructorTag) : mode(mode) {}
69 
getModeId()70         DisplayModeId getModeId() const { return mode->getId(); }
getVsyncPeriod()71         nsecs_t getVsyncPeriod() const { return mode->getVsyncPeriod(); }
getModeGroup()72         int32_t getModeGroup() const { return mode->getGroup(); }
getName()73         std::string getName() const { return to_string(getFps()); }
getFps()74         Fps getFps() const { return mode->getFps(); }
getMode()75         DisplayModePtr getMode() const { return mode; }
76 
77         // Checks whether the fps of this RefreshRate struct is within a given min and max refresh
78         // rate passed in. Margin of error is applied to the boundaries for approximation.
inPolicy(Fps minRefreshRate,Fps maxRefreshRate)79         bool inPolicy(Fps minRefreshRate, Fps maxRefreshRate) const {
80             return minRefreshRate.lessThanOrEqualWithMargin(getFps()) &&
81                     getFps().lessThanOrEqualWithMargin(maxRefreshRate);
82         }
83 
84         bool operator!=(const RefreshRate& other) const { return mode != other.mode; }
85 
86         bool operator<(const RefreshRate& other) const {
87             return getFps().getValue() < other.getFps().getValue();
88         }
89 
90         bool operator==(const RefreshRate& other) const { return !(*this != other); }
91 
92         std::string toString() const;
93         friend std::ostream& operator<<(std::ostream& os, const RefreshRate& refreshRate) {
94             return os << refreshRate.toString();
95         }
96 
97     private:
98         friend RefreshRateConfigs;
99         friend class RefreshRateConfigsTest;
100 
101         DisplayModePtr mode;
102     };
103 
104     using AllRefreshRatesMapType =
105             std::unordered_map<DisplayModeId, std::unique_ptr<const RefreshRate>>;
106 
107     struct FpsRange {
108         Fps min{0.0f};
109         Fps max{std::numeric_limits<float>::max()};
110 
111         bool operator==(const FpsRange& other) const {
112             return min.equalsWithMargin(other.min) && max.equalsWithMargin(other.max);
113         }
114 
115         bool operator!=(const FpsRange& other) const { return !(*this == other); }
116 
toStringFpsRange117         std::string toString() const {
118             return base::StringPrintf("[%s %s]", to_string(min).c_str(), to_string(max).c_str());
119         }
120     };
121 
122     struct Policy {
123     private:
124         static constexpr int kAllowGroupSwitchingDefault = false;
125 
126     public:
127         // The default mode, used to ensure we only initiate display mode switches within the
128         // same mode group as defaultMode's group.
129         DisplayModeId defaultMode;
130         // Whether or not we switch mode groups to get the best frame rate.
131         bool allowGroupSwitching = kAllowGroupSwitchingDefault;
132         // The primary refresh rate range represents display manager's general guidance on the
133         // display modes we'll consider when switching refresh rates. Unless we get an explicit
134         // signal from an app, we should stay within this range.
135         FpsRange primaryRange;
136         // The app request refresh rate range allows us to consider more display modes when
137         // switching refresh rates. Although we should generally stay within the primary range,
138         // specific considerations, such as layer frame rate settings specified via the
139         // setFrameRate() api, may cause us to go outside the primary range. We never go outside the
140         // app request range. The app request range will be greater than or equal to the primary
141         // refresh rate range, never smaller.
142         FpsRange appRequestRange;
143 
144         Policy() = default;
145 
PolicyPolicy146         Policy(DisplayModeId defaultMode, const FpsRange& range)
147               : Policy(defaultMode, kAllowGroupSwitchingDefault, range, range) {}
148 
PolicyPolicy149         Policy(DisplayModeId defaultMode, bool allowGroupSwitching, const FpsRange& range)
150               : Policy(defaultMode, allowGroupSwitching, range, range) {}
151 
PolicyPolicy152         Policy(DisplayModeId defaultMode, const FpsRange& primaryRange,
153                const FpsRange& appRequestRange)
154               : Policy(defaultMode, kAllowGroupSwitchingDefault, primaryRange, appRequestRange) {}
155 
PolicyPolicy156         Policy(DisplayModeId defaultMode, bool allowGroupSwitching, const FpsRange& primaryRange,
157                const FpsRange& appRequestRange)
158               : defaultMode(defaultMode),
159                 allowGroupSwitching(allowGroupSwitching),
160                 primaryRange(primaryRange),
161                 appRequestRange(appRequestRange) {}
162 
163         bool operator==(const Policy& other) const {
164             return defaultMode == other.defaultMode && primaryRange == other.primaryRange &&
165                     appRequestRange == other.appRequestRange &&
166                     allowGroupSwitching == other.allowGroupSwitching;
167         }
168 
169         bool operator!=(const Policy& other) const { return !(*this == other); }
170         std::string toString() const;
171     };
172 
173     // Return code set*Policy() to indicate the current policy is unchanged.
174     static constexpr int CURRENT_POLICY_UNCHANGED = 1;
175 
176     // We maintain the display manager policy and the override policy separately. The override
177     // policy is used by CTS tests to get a consistent device state for testing. While the override
178     // policy is set, it takes precedence over the display manager policy. Once the override policy
179     // is cleared, we revert to using the display manager policy.
180 
181     // Sets the display manager policy to choose refresh rates. The return value will be:
182     //   - A negative value if the policy is invalid or another error occurred.
183     //   - NO_ERROR if the policy was successfully updated, and the current policy is different from
184     //     what it was before the call.
185     //   - CURRENT_POLICY_UNCHANGED if the policy was successfully updated, but the current policy
186     //     is the same as it was before the call.
187     status_t setDisplayManagerPolicy(const Policy& policy) EXCLUDES(mLock);
188     // Sets the override policy. See setDisplayManagerPolicy() for the meaning of the return value.
189     status_t setOverridePolicy(const std::optional<Policy>& policy) EXCLUDES(mLock);
190     // Gets the current policy, which will be the override policy if active, and the display manager
191     // policy otherwise.
192     Policy getCurrentPolicy() const EXCLUDES(mLock);
193     // Gets the display manager policy, regardless of whether an override policy is active.
194     Policy getDisplayManagerPolicy() const EXCLUDES(mLock);
195 
196     // Returns true if mode is allowed by the current policy.
197     bool isModeAllowed(DisplayModeId) const EXCLUDES(mLock);
198 
199     // Describes the different options the layer voted for refresh rate
200     enum class LayerVoteType {
201         NoVote,          // Doesn't care about the refresh rate
202         Min,             // Minimal refresh rate available
203         Max,             // Maximal refresh rate available
204         Heuristic,       // Specific refresh rate that was calculated by platform using a heuristic
205         ExplicitDefault, // Specific refresh rate that was provided by the app with Default
206                          // compatibility
207         ExplicitExactOrMultiple, // Specific refresh rate that was provided by the app with
208                                  // ExactOrMultiple compatibility
209         ExplicitExact,           // Specific refresh rate that was provided by the app with
210                                  // Exact compatibility
211 
212     };
213 
214     // Captures the layer requirements for a refresh rate. This will be used to determine the
215     // display refresh rate.
216     struct LayerRequirement {
217         // Layer's name. Used for debugging purposes.
218         std::string name;
219         // Layer's owner uid
220         uid_t ownerUid = static_cast<uid_t>(-1);
221         // Layer vote type.
222         LayerVoteType vote = LayerVoteType::NoVote;
223         // Layer's desired refresh rate, if applicable.
224         Fps desiredRefreshRate{0.0f};
225         // If a seamless mode switch is required.
226         Seamlessness seamlessness = Seamlessness::Default;
227         // Layer's weight in the range of [0, 1]. The higher the weight the more impact this layer
228         // would have on choosing the refresh rate.
229         float weight = 0.0f;
230         // Whether layer is in focus or not based on WindowManager's state
231         bool focused = false;
232 
233         bool operator==(const LayerRequirement& other) const {
234             return name == other.name && vote == other.vote &&
235                     desiredRefreshRate.equalsWithMargin(other.desiredRefreshRate) &&
236                     seamlessness == other.seamlessness && weight == other.weight &&
237                     focused == other.focused;
238         }
239 
240         bool operator!=(const LayerRequirement& other) const { return !(*this == other); }
241     };
242 
243     // Global state describing signals that affect refresh rate choice.
244     struct GlobalSignals {
245         // Whether the user touched the screen recently. Used to apply touch boost.
246         bool touch = false;
247         // True if the system hasn't seen any buffers posted to layers recently.
248         bool idle = false;
249 
250         bool operator==(const GlobalSignals& other) const {
251             return touch == other.touch && idle == other.idle;
252         }
253     };
254 
255     // Returns the refresh rate that fits best to the given layers.
256     //   layers - The layer requirements to consider.
257     //   globalSignals - global state of touch and idle
258     //   outSignalsConsidered - An output param that tells the caller whether the refresh rate was
259     //                          chosen based on touch boost and/or idle timer.
260     RefreshRate getBestRefreshRate(const std::vector<LayerRequirement>& layers,
261                                    const GlobalSignals& globalSignals,
262                                    GlobalSignals* outSignalsConsidered = nullptr) const
263             EXCLUDES(mLock);
264 
getSupportedRefreshRateRange()265     FpsRange getSupportedRefreshRateRange() const EXCLUDES(mLock) {
266         std::lock_guard lock(mLock);
267         return {mMinSupportedRefreshRate->getFps(), mMaxSupportedRefreshRate->getFps()};
268     }
269 
270     std::optional<Fps> onKernelTimerChanged(std::optional<DisplayModeId> desiredActiveModeId,
271                                             bool timerExpired) const EXCLUDES(mLock);
272 
273     // Returns the highest refresh rate according to the current policy. May change at runtime. Only
274     // uses the primary range, not the app request range.
275     RefreshRate getMaxRefreshRateByPolicy() const EXCLUDES(mLock);
276 
277     // Returns the current refresh rate
278     RefreshRate getCurrentRefreshRate() const EXCLUDES(mLock);
279 
280     // Returns the current refresh rate, if allowed. Otherwise the default that is allowed by
281     // the policy.
282     RefreshRate getCurrentRefreshRateByPolicy() const;
283 
284     // Returns the refresh rate that corresponds to a DisplayModeId. This may change at
285     // runtime.
286     // TODO(b/159590486) An invalid mode id may be given here if the dipslay modes have changed.
getRefreshRateFromModeId(DisplayModeId modeId)287     RefreshRate getRefreshRateFromModeId(DisplayModeId modeId) const EXCLUDES(mLock) {
288         std::lock_guard lock(mLock);
289         return *mRefreshRates.at(modeId);
290     };
291 
292     // Stores the current modeId the device operates at
293     void setCurrentModeId(DisplayModeId) EXCLUDES(mLock);
294 
295     // Returns a string that represents the layer vote type
296     static std::string layerVoteTypeString(LayerVoteType vote);
297 
298     // Returns a known frame rate that is the closest to frameRate
299     Fps findClosestKnownFrameRate(Fps frameRate) const;
300 
301     // Configuration flags.
302     struct Config {
303         bool enableFrameRateOverride = false;
304 
305         // Specifies the upper refresh rate threshold (inclusive) for layer vote types of multiple
306         // or heuristic, such that refresh rates higher than this value will not be voted for. 0 if
307         // no threshold is set.
308         int frameRateMultipleThreshold = 0;
309 
310         // The Idle Timer timeout. 0 timeout means no idle timer.
311         int32_t idleTimerTimeoutMs = 0;
312 
313         // Whether to use idle timer callbacks that support the kernel timer.
314         bool supportKernelIdleTimer = false;
315     };
316 
317     RefreshRateConfigs(const DisplayModes&, DisplayModeId,
318                        Config config = {.enableFrameRateOverride = false,
319                                         .frameRateMultipleThreshold = 0,
320                                         .idleTimerTimeoutMs = 0,
321                                         .supportKernelIdleTimer = false});
322 
323     // Returns whether switching modes (refresh rate or resolution) is possible.
324     // TODO(b/158780872): Consider HAL support, and skip frame rate detection if the modes only
325     // differ in resolution.
canSwitch()326     bool canSwitch() const EXCLUDES(mLock) {
327         std::lock_guard lock(mLock);
328         return mRefreshRates.size() > 1;
329     }
330 
331     // Class to enumerate options around toggling the kernel timer on and off.
332     enum class KernelIdleTimerAction {
333         TurnOff,  // Turn off the idle timer.
334         TurnOn    // Turn on the idle timer.
335     };
336     // Checks whether kernel idle timer should be active depending the policy decisions around
337     // refresh rates.
338     KernelIdleTimerAction getIdleTimerAction() const;
339 
supportsFrameRateOverride()340     bool supportsFrameRateOverride() const { return mSupportsFrameRateOverride; }
341 
342     // Return the display refresh rate divider to match the layer
343     // frame rate, or 0 if the display refresh rate is not a multiple of the
344     // layer refresh rate.
345     static int getFrameRateDivider(Fps displayFrameRate, Fps layerFrameRate);
346 
347     using UidToFrameRateOverride = std::map<uid_t, Fps>;
348     // Returns the frame rate override for each uid.
349     //
350     // @param layers list of visible layers
351     // @param displayFrameRate the display frame rate
352     // @param touch whether touch timer is active (i.e. user touched the screen recently)
353     UidToFrameRateOverride getFrameRateOverrides(const std::vector<LayerRequirement>& layers,
354                                                  Fps displayFrameRate, bool touch) const
355             EXCLUDES(mLock);
356 
supportsKernelIdleTimer()357     bool supportsKernelIdleTimer() const { return mConfig.supportKernelIdleTimer; }
358 
setIdleTimerCallbacks(std::function<void ()> platformTimerReset,std::function<void ()> platformTimerExpired,std::function<void ()> kernelTimerReset,std::function<void ()> kernelTimerExpired)359     void setIdleTimerCallbacks(std::function<void()> platformTimerReset,
360                                std::function<void()> platformTimerExpired,
361                                std::function<void()> kernelTimerReset,
362                                std::function<void()> kernelTimerExpired) {
363         std::scoped_lock lock(mIdleTimerCallbacksMutex);
364         mIdleTimerCallbacks.emplace();
365         mIdleTimerCallbacks->platform.onReset = std::move(platformTimerReset);
366         mIdleTimerCallbacks->platform.onExpired = std::move(platformTimerExpired);
367         mIdleTimerCallbacks->kernel.onReset = std::move(kernelTimerReset);
368         mIdleTimerCallbacks->kernel.onExpired = std::move(kernelTimerExpired);
369     }
370 
startIdleTimer()371     void startIdleTimer() {
372         if (mIdleTimer) {
373             mIdleTimer->start();
374         }
375     }
376 
stopIdleTimer()377     void stopIdleTimer() {
378         if (mIdleTimer) {
379             mIdleTimer->stop();
380         }
381     }
382 
resetIdleTimer(bool kernelOnly)383     void resetIdleTimer(bool kernelOnly) {
384         if (!mIdleTimer) {
385             return;
386         }
387         if (kernelOnly && !mConfig.supportKernelIdleTimer) {
388             return;
389         }
390         mIdleTimer->reset();
391     };
392 
393     void dump(std::string& result) const EXCLUDES(mLock);
394 
395     RefreshRateConfigs(const RefreshRateConfigs&) = delete;
396     void operator=(const RefreshRateConfigs&) = delete;
397 
398 private:
399     friend class RefreshRateConfigsTest;
400 
401     void constructAvailableRefreshRates() REQUIRES(mLock);
402 
403     void getSortedRefreshRateListLocked(
404             const std::function<bool(const RefreshRate&)>& shouldAddRefreshRate,
405             std::vector<const RefreshRate*>* outRefreshRates) REQUIRES(mLock);
406 
407     std::optional<RefreshRate> getCachedBestRefreshRate(const std::vector<LayerRequirement>& layers,
408                                                         const GlobalSignals& globalSignals,
409                                                         GlobalSignals* outSignalsConsidered) const
410             REQUIRES(mLock);
411 
412     RefreshRate getBestRefreshRateLocked(const std::vector<LayerRequirement>& layers,
413                                          const GlobalSignals& globalSignals,
414                                          GlobalSignals* outSignalsConsidered) const REQUIRES(mLock);
415 
416     // Returns the refresh rate with the highest score in the collection specified from begin
417     // to end. If there are more than one with the same highest refresh rate, the first one is
418     // returned.
419     template <typename Iter>
420     const RefreshRate* getBestRefreshRate(Iter begin, Iter end) const;
421 
422     // Returns number of display frames and remainder when dividing the layer refresh period by
423     // display refresh period.
424     std::pair<nsecs_t, nsecs_t> getDisplayFrames(nsecs_t layerPeriod, nsecs_t displayPeriod) const;
425 
426     // Returns the lowest refresh rate according to the current policy. May change at runtime. Only
427     // uses the primary range, not the app request range.
428     const RefreshRate& getMinRefreshRateByPolicyLocked() const REQUIRES(mLock);
429 
430     // Returns the highest refresh rate according to the current policy. May change at runtime. Only
431     // uses the primary range, not the app request range.
432     const RefreshRate& getMaxRefreshRateByPolicyLocked() const REQUIRES(mLock);
433 
434     // Returns the current refresh rate, if allowed. Otherwise the default that is allowed by
435     // the policy.
436     const RefreshRate& getCurrentRefreshRateByPolicyLocked() const REQUIRES(mLock);
437 
438     const Policy* getCurrentPolicyLocked() const REQUIRES(mLock);
439     bool isPolicyValidLocked(const Policy& policy) const REQUIRES(mLock);
440 
441     // Returns whether the layer is allowed to vote for the given refresh rate.
442     bool isVoteAllowed(const LayerRequirement&, const RefreshRate&) const;
443 
444     // calculates a score for a layer. Used to determine the display refresh rate
445     // and the frame rate override for certains applications.
446     float calculateLayerScoreLocked(const LayerRequirement&, const RefreshRate&,
447                                     bool isSeamlessSwitch) const REQUIRES(mLock);
448 
449     void updateDisplayModes(const DisplayModes& mode, DisplayModeId currentModeId) EXCLUDES(mLock);
450 
451     void initializeIdleTimer();
452 
453     // The list of refresh rates, indexed by display modes ID. This may change after this
454     // object is initialized.
455     AllRefreshRatesMapType mRefreshRates GUARDED_BY(mLock);
456 
457     // The list of refresh rates in the primary range of the current policy, ordered by vsyncPeriod
458     // (the first element is the lowest refresh rate).
459     std::vector<const RefreshRate*> mPrimaryRefreshRates GUARDED_BY(mLock);
460 
461     // The list of refresh rates in the app request range of the current policy, ordered by
462     // vsyncPeriod (the first element is the lowest refresh rate).
463     std::vector<const RefreshRate*> mAppRequestRefreshRates GUARDED_BY(mLock);
464 
465     // The current display mode. This will change at runtime. This is set by SurfaceFlinger on
466     // the main thread, and read by the Scheduler (and other objects) on other threads.
467     const RefreshRate* mCurrentRefreshRate GUARDED_BY(mLock);
468 
469     // The policy values will change at runtime. They're set by SurfaceFlinger on the main thread,
470     // and read by the Scheduler (and other objects) on other threads.
471     Policy mDisplayManagerPolicy GUARDED_BY(mLock);
472     std::optional<Policy> mOverridePolicy GUARDED_BY(mLock);
473 
474     // The min and max refresh rates supported by the device.
475     // This may change at runtime.
476     const RefreshRate* mMinSupportedRefreshRate GUARDED_BY(mLock);
477     const RefreshRate* mMaxSupportedRefreshRate GUARDED_BY(mLock);
478 
479     mutable std::mutex mLock;
480 
481     // A sorted list of known frame rates that a Heuristic layer will choose
482     // from based on the closest value.
483     const std::vector<Fps> mKnownFrameRates;
484 
485     const Config mConfig;
486     bool mSupportsFrameRateOverride;
487 
488     struct GetBestRefreshRateInvocation {
489         std::vector<LayerRequirement> layerRequirements;
490         GlobalSignals globalSignals;
491         GlobalSignals outSignalsConsidered;
492         RefreshRate resultingBestRefreshRate;
493     };
494     mutable std::optional<GetBestRefreshRateInvocation> lastBestRefreshRateInvocation
495             GUARDED_BY(mLock);
496 
497     // Timer that records time between requests for next vsync.
498     std::optional<scheduler::OneShotTimer> mIdleTimer;
499 
500     struct IdleTimerCallbacks {
501         struct Callbacks {
502             std::function<void()> onReset;
503             std::function<void()> onExpired;
504         };
505 
506         Callbacks platform;
507         Callbacks kernel;
508     };
509 
510     std::mutex mIdleTimerCallbacksMutex;
511     std::optional<IdleTimerCallbacks> mIdleTimerCallbacks GUARDED_BY(mIdleTimerCallbacksMutex);
512 };
513 
514 } // namespace android::scheduler
515