• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2020 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 <chrono>
20 #include <deque>
21 #include <optional>
22 #include <string>
23 #include <unordered_map>
24 
25 #include <ui/Transform.h>
26 #include <utils/Timers.h>
27 
28 #include <scheduler/Seamlessness.h>
29 
30 #include "LayerHistory.h"
31 #include "RefreshRateConfigs.h"
32 
33 namespace android {
34 
35 class Layer;
36 
37 namespace scheduler {
38 
39 using namespace std::chrono_literals;
40 
41 // Maximum period between presents for a layer to be considered active.
42 constexpr std::chrono::nanoseconds MAX_ACTIVE_LAYER_PERIOD_NS = 1200ms;
43 
44 // Earliest present time for a layer to be considered active.
getActiveLayerThreshold(nsecs_t now)45 constexpr nsecs_t getActiveLayerThreshold(nsecs_t now) {
46     return now - MAX_ACTIVE_LAYER_PERIOD_NS.count();
47 }
48 
49 // Stores history of present times and refresh rates for a layer.
50 class LayerInfo {
51     using LayerUpdateType = LayerHistory::LayerUpdateType;
52 
53     // Layer is considered frequent if the earliest value in the window of most recent present times
54     // is within a threshold. If a layer is infrequent, its average refresh rate is disregarded in
55     // favor of a low refresh rate.
56     static constexpr size_t kFrequentLayerWindowSize = 3;
57     static constexpr Fps kMinFpsForFrequentLayer = 10_Hz;
58     static constexpr auto kMaxPeriodForFrequentLayerNs =
59             std::chrono::nanoseconds(kMinFpsForFrequentLayer.getPeriodNsecs()) + 1ms;
60 
61     friend class LayerHistoryTest;
62     friend class LayerInfoTest;
63 
64 public:
65     // Holds information about the layer vote
66     struct LayerVote {
67         LayerHistory::LayerVoteType type = LayerHistory::LayerVoteType::Heuristic;
68         Fps fps;
69         Seamlessness seamlessness = Seamlessness::Default;
70     };
71 
72     // FrameRateCompatibility specifies how we should interpret the frame rate associated with
73     // the layer.
74     enum class FrameRateCompatibility {
75         Default, // Layer didn't specify any specific handling strategy
76 
77         Exact, // Layer needs the exact frame rate.
78 
79         ExactOrMultiple, // Layer needs the exact frame rate (or a multiple of it) to present the
80                          // content properly. Any other value will result in a pull down.
81 
82         NoVote, // Layer doesn't have any requirements for the refresh rate and
83                 // should not be considered when the display refresh rate is determined.
84 
85         ftl_last = NoVote
86     };
87 
88     // Encapsulates the frame rate and compatibility of the layer. This information will be used
89     // when the display refresh rate is determined.
90     struct FrameRate {
91         using Seamlessness = scheduler::Seamlessness;
92 
93         Fps rate;
94         FrameRateCompatibility type = FrameRateCompatibility::Default;
95         Seamlessness seamlessness = Seamlessness::Default;
96 
97         FrameRate() = default;
98 
99         FrameRate(Fps rate, FrameRateCompatibility type,
100                   Seamlessness seamlessness = Seamlessness::OnlySeamless)
rateFrameRate101               : rate(rate), type(type), seamlessness(getSeamlessness(rate, seamlessness)) {}
102 
103         bool operator==(const FrameRate& other) const {
104             return isApproxEqual(rate, other.rate) && type == other.type &&
105                     seamlessness == other.seamlessness;
106         }
107 
108         bool operator!=(const FrameRate& other) const { return !(*this == other); }
109 
110         // Convert an ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_* value to a
111         // Layer::FrameRateCompatibility. Logs fatal if the compatibility value is invalid.
112         static FrameRateCompatibility convertCompatibility(int8_t compatibility);
113         static scheduler::Seamlessness convertChangeFrameRateStrategy(int8_t strategy);
114 
115     private:
getSeamlessnessFrameRate116         static Seamlessness getSeamlessness(Fps rate, Seamlessness seamlessness) {
117             if (!rate.isValid()) {
118                 // Refresh rate of 0 is a special value which should reset the vote to
119                 // its default value.
120                 return Seamlessness::Default;
121             }
122             return seamlessness;
123         }
124     };
125 
setTraceEnabled(bool enabled)126     static void setTraceEnabled(bool enabled) { sTraceEnabled = enabled; }
127 
128     LayerInfo(const std::string& name, uid_t ownerUid, LayerHistory::LayerVoteType defaultVote);
129 
130     LayerInfo(const LayerInfo&) = delete;
131     LayerInfo& operator=(const LayerInfo&) = delete;
132 
133     struct LayerProps {
134         bool visible = false;
135         FloatRect bounds;
136         ui::Transform transform;
137         FrameRate setFrameRateVote;
138         int32_t frameRateSelectionPriority = -1;
139     };
140 
141     // Records the last requested present time. It also stores information about when
142     // the layer was last updated. If the present time is farther in the future than the
143     // updated time, the updated time is the present time.
144     void setLastPresentTime(nsecs_t lastPresentTime, nsecs_t now, LayerUpdateType updateType,
145                             bool pendingModeChange, LayerProps props);
146 
147     // Sets an explicit layer vote. This usually comes directly from the application via
148     // ANativeWindow_setFrameRate API
setLayerVote(LayerVote vote)149     void setLayerVote(LayerVote vote) { mLayerVote = vote; }
150 
151     // Sets the default layer vote. This will be the layer vote after calling to resetLayerVote().
152     // This is used for layers that called to setLayerVote() and then removed the vote, so that the
153     // layer can go back to whatever vote it had before the app voted for it.
setDefaultLayerVote(LayerHistory::LayerVoteType type)154     void setDefaultLayerVote(LayerHistory::LayerVoteType type) { mDefaultVote = type; }
155 
156     // Resets the layer vote to its default.
resetLayerVote()157     void resetLayerVote() { mLayerVote = {mDefaultVote, Fps(), Seamlessness::Default}; }
158 
getName()159     std::string getName() const { return mName; }
160 
getOwnerUid()161     uid_t getOwnerUid() const { return mOwnerUid; }
162 
163     LayerVote getRefreshRateVote(const RefreshRateConfigs&, nsecs_t now);
164 
165     // Return the last updated time. If the present time is farther in the future than the
166     // updated time, the updated time is the present time.
getLastUpdatedTime()167     nsecs_t getLastUpdatedTime() const { return mLastUpdatedTime; }
168 
getSetFrameRateVote()169     FrameRate getSetFrameRateVote() const { return mLayerProps.setFrameRateVote; }
isVisible()170     bool isVisible() const { return mLayerProps.visible; }
getFrameRateSelectionPriority()171     int32_t getFrameRateSelectionPriority() const { return mLayerProps.frameRateSelectionPriority; }
172 
getBounds()173     FloatRect getBounds() const { return mLayerProps.bounds; }
174 
getTransform()175     ui::Transform getTransform() const { return mLayerProps.transform; }
176 
177     // Returns a C string for tracing a vote
178     const char* getTraceTag(LayerHistory::LayerVoteType type) const;
179 
180     // Return the framerate of this layer.
181     Fps getFps(nsecs_t now) const;
182 
onLayerInactive(nsecs_t now)183     void onLayerInactive(nsecs_t now) {
184         // Mark mFrameTimeValidSince to now to ignore all previous frame times.
185         // We are not deleting the old frame to keep track of whether we should treat the first
186         // buffer as Max as we don't know anything about this layer or Min as this layer is
187         // posting infrequent updates.
188         const auto timePoint = std::chrono::nanoseconds(now);
189         mFrameTimeValidSince = std::chrono::time_point<std::chrono::steady_clock>(timePoint);
190         mLastRefreshRate = {};
191         mRefreshRateHistory.clear();
192     }
193 
clearHistory(nsecs_t now)194     void clearHistory(nsecs_t now) {
195         onLayerInactive(now);
196         mFrameTimes.clear();
197     }
198 
199 private:
200     // Used to store the layer timestamps
201     struct FrameTimeData {
202         nsecs_t presentTime; // desiredPresentTime, if provided
203         nsecs_t queueTime;  // buffer queue time
204         bool pendingModeChange;
205     };
206 
207     // Holds information about the calculated and reported refresh rate
208     struct RefreshRateHeuristicData {
209         // Rate calculated on the layer
210         Fps calculated;
211         // Last reported rate for LayerInfo::getRefreshRate()
212         Fps reported;
213         // Whether the last reported rate for LayerInfo::getRefreshRate()
214         // was due to animation or infrequent updates
215         bool animatingOrInfrequent = false;
216     };
217 
218     // Class to store past calculated refresh rate and determine whether
219     // the refresh rate calculated is consistent with past values
220     class RefreshRateHistory {
221     public:
222         static constexpr auto HISTORY_SIZE = 90;
223         static constexpr std::chrono::nanoseconds HISTORY_DURATION = 2s;
224 
RefreshRateHistory(const std::string & name)225         RefreshRateHistory(const std::string& name) : mName(name) {}
226 
227         // Clears History
228         void clear();
229 
230         // Adds a new refresh rate and returns true if it is consistent
231         bool add(Fps refreshRate, nsecs_t now);
232 
233     private:
234         friend class LayerHistoryTest;
235 
236         // Holds the refresh rate when it was calculated
237         struct RefreshRateData {
238             Fps refreshRate;
239             nsecs_t timestamp = 0;
240         };
241 
242         // Holds tracing strings
243         struct HeuristicTraceTagData {
244             std::string min;
245             std::string max;
246             std::string consistent;
247             std::string average;
248         };
249 
250         bool isConsistent() const;
251         HeuristicTraceTagData makeHeuristicTraceTagData() const;
252 
253         const std::string mName;
254         mutable std::optional<HeuristicTraceTagData> mHeuristicTraceTagData;
255         std::deque<RefreshRateData> mRefreshRates;
256         static constexpr float MARGIN_CONSISTENT_FPS = 1.0;
257     };
258 
259     bool isFrequent(nsecs_t now) const;
260     bool isAnimating(nsecs_t now) const;
261     bool hasEnoughDataForHeuristic() const;
262     std::optional<Fps> calculateRefreshRateIfPossible(const RefreshRateConfigs&, nsecs_t now);
263     std::optional<nsecs_t> calculateAverageFrameTime() const;
264     bool isFrameTimeValid(const FrameTimeData&) const;
265 
266     const std::string mName;
267     const uid_t mOwnerUid;
268 
269     // Used for sanitizing the heuristic data. If two frames are less than
270     // this period apart from each other they'll be considered as duplicates.
271     static constexpr nsecs_t kMinPeriodBetweenFrames = (240_Hz).getPeriodNsecs();
272     // Used for sanitizing the heuristic data. If two frames are more than
273     // this period apart from each other, the interval between them won't be
274     // taken into account when calculating average frame rate.
275     static constexpr nsecs_t kMaxPeriodBetweenFrames = kMinFpsForFrequentLayer.getPeriodNsecs();
276     LayerHistory::LayerVoteType mDefaultVote;
277 
278     LayerVote mLayerVote;
279 
280     nsecs_t mLastUpdatedTime = 0;
281 
282     nsecs_t mLastAnimationTime = 0;
283 
284     RefreshRateHeuristicData mLastRefreshRate;
285 
286     std::deque<FrameTimeData> mFrameTimes;
287     std::chrono::time_point<std::chrono::steady_clock> mFrameTimeValidSince =
288             std::chrono::steady_clock::now();
289     static constexpr size_t HISTORY_SIZE = RefreshRateHistory::HISTORY_SIZE;
290     static constexpr std::chrono::nanoseconds HISTORY_DURATION = 1s;
291 
292     LayerProps mLayerProps;
293 
294     RefreshRateHistory mRefreshRateHistory;
295 
296     mutable std::unordered_map<LayerHistory::LayerVoteType, std::string> mTraceTags;
297 
298     // Shared for all LayerInfo instances
299     static bool sTraceEnabled;
300 };
301 
302 } // namespace scheduler
303 } // namespace android
304