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 // TODO(b/129481165): remove the #pragma below and fix conversion issues
18 #pragma clang diagnostic push
19 #pragma clang diagnostic ignored "-Wextra"
20 
21 // #define LOG_NDEBUG 0
22 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
23 
24 #include "LayerInfo.h"
25 
26 #include <algorithm>
27 #include <utility>
28 
29 #include <cutils/compiler.h>
30 #include <cutils/trace.h>
31 
32 #undef LOG_TAG
33 #define LOG_TAG "LayerInfo"
34 
35 namespace android::scheduler {
36 
37 bool LayerInfo::sTraceEnabled = false;
38 
LayerInfo(const std::string & name,uid_t ownerUid,LayerHistory::LayerVoteType defaultVote)39 LayerInfo::LayerInfo(const std::string& name, uid_t ownerUid,
40                      LayerHistory::LayerVoteType defaultVote)
41       : mName(name),
42         mOwnerUid(ownerUid),
43         mDefaultVote(defaultVote),
44         mLayerVote({defaultVote, Fps(0.0f)}),
45         mRefreshRateHistory(name) {}
46 
setLastPresentTime(nsecs_t lastPresentTime,nsecs_t now,LayerUpdateType updateType,bool pendingModeChange,LayerProps props)47 void LayerInfo::setLastPresentTime(nsecs_t lastPresentTime, nsecs_t now, LayerUpdateType updateType,
48                                    bool pendingModeChange, LayerProps props) {
49     lastPresentTime = std::max(lastPresentTime, static_cast<nsecs_t>(0));
50 
51     mLastUpdatedTime = std::max(lastPresentTime, now);
52     mLayerProps = props;
53     switch (updateType) {
54         case LayerUpdateType::AnimationTX:
55             mLastAnimationTime = std::max(lastPresentTime, now);
56             break;
57         case LayerUpdateType::SetFrameRate:
58         case LayerUpdateType::Buffer:
59             FrameTimeData frameTime = {.presentTime = lastPresentTime,
60                                        .queueTime = mLastUpdatedTime,
61                                        .pendingModeChange = pendingModeChange};
62             mFrameTimes.push_back(frameTime);
63             if (mFrameTimes.size() > HISTORY_SIZE) {
64                 mFrameTimes.pop_front();
65             }
66             break;
67     }
68 }
69 
isFrameTimeValid(const FrameTimeData & frameTime) const70 bool LayerInfo::isFrameTimeValid(const FrameTimeData& frameTime) const {
71     return frameTime.queueTime >= std::chrono::duration_cast<std::chrono::nanoseconds>(
72                                           mFrameTimeValidSince.time_since_epoch())
73                                           .count();
74 }
75 
isFrequent(nsecs_t now) const76 bool LayerInfo::isFrequent(nsecs_t now) const {
77     // If we know nothing about this layer we consider it as frequent as it might be the start
78     // of an animation.
79     if (mFrameTimes.size() < kFrequentLayerWindowSize) {
80         return true;
81     }
82 
83     // Find the first active frame
84     auto it = mFrameTimes.begin();
85     for (; it != mFrameTimes.end(); ++it) {
86         if (it->queueTime >= getActiveLayerThreshold(now)) {
87             break;
88         }
89     }
90 
91     const auto numFrames = std::distance(it, mFrameTimes.end());
92     if (numFrames < kFrequentLayerWindowSize) {
93         return false;
94     }
95 
96     // Layer is considered frequent if the average frame rate is higher than the threshold
97     const auto totalTime = mFrameTimes.back().queueTime - it->queueTime;
98     return Fps::fromPeriodNsecs(totalTime / (numFrames - 1))
99             .greaterThanOrEqualWithMargin(kMinFpsForFrequentLayer);
100 }
101 
isAnimating(nsecs_t now) const102 bool LayerInfo::isAnimating(nsecs_t now) const {
103     return mLastAnimationTime >= getActiveLayerThreshold(now);
104 }
105 
hasEnoughDataForHeuristic() const106 bool LayerInfo::hasEnoughDataForHeuristic() const {
107     // The layer had to publish at least HISTORY_SIZE or HISTORY_DURATION of updates
108     if (mFrameTimes.size() < 2) {
109         ALOGV("fewer than 2 frames recorded: %zu", mFrameTimes.size());
110         return false;
111     }
112 
113     if (!isFrameTimeValid(mFrameTimes.front())) {
114         ALOGV("stale frames still captured");
115         return false;
116     }
117 
118     const auto totalDuration = mFrameTimes.back().queueTime - mFrameTimes.front().queueTime;
119     if (mFrameTimes.size() < HISTORY_SIZE && totalDuration < HISTORY_DURATION.count()) {
120         ALOGV("not enough frames captured: %zu | %.2f seconds", mFrameTimes.size(),
121               totalDuration / 1e9f);
122         return false;
123     }
124 
125     return true;
126 }
127 
calculateAverageFrameTime() const128 std::optional<nsecs_t> LayerInfo::calculateAverageFrameTime() const {
129     // Ignore frames captured during a mode change
130     const bool isDuringModeChange =
131             std::any_of(mFrameTimes.begin(), mFrameTimes.end(),
132                         [](const auto& frame) { return frame.pendingModeChange; });
133     if (isDuringModeChange) {
134         return std::nullopt;
135     }
136 
137     const bool isMissingPresentTime =
138             std::any_of(mFrameTimes.begin(), mFrameTimes.end(),
139                         [](auto frame) { return frame.presentTime == 0; });
140     if (isMissingPresentTime && !mLastRefreshRate.reported.isValid()) {
141         // If there are no presentation timestamps and we haven't calculated
142         // one in the past then we can't calculate the refresh rate
143         return std::nullopt;
144     }
145 
146     // Calculate the average frame time based on presentation timestamps. If those
147     // doesn't exist, we look at the time the buffer was queued only. We can do that only if
148     // we calculated a refresh rate based on presentation timestamps in the past. The reason
149     // we look at the queue time is to handle cases where hwui attaches presentation timestamps
150     // when implementing render ahead for specific refresh rates. When hwui no longer provides
151     // presentation timestamps we look at the queue time to see if the current refresh rate still
152     // matches the content.
153 
154     auto getFrameTime = isMissingPresentTime ? [](FrameTimeData data) { return data.queueTime; }
155                                              : [](FrameTimeData data) { return data.presentTime; };
156 
157     nsecs_t totalDeltas = 0;
158     int numDeltas = 0;
159     auto prevFrame = mFrameTimes.begin();
160     for (auto it = mFrameTimes.begin() + 1; it != mFrameTimes.end(); ++it) {
161         const auto currDelta = getFrameTime(*it) - getFrameTime(*prevFrame);
162         if (currDelta < kMinPeriodBetweenFrames) {
163             // Skip this frame, but count the delta into the next frame
164             continue;
165         }
166 
167         prevFrame = it;
168 
169         if (currDelta > kMaxPeriodBetweenFrames) {
170             // Skip this frame and the current delta.
171             continue;
172         }
173 
174         totalDeltas += currDelta;
175         numDeltas++;
176     }
177 
178     if (numDeltas == 0) {
179         return std::nullopt;
180     }
181 
182     const auto averageFrameTime = static_cast<double>(totalDeltas) / static_cast<double>(numDeltas);
183     return static_cast<nsecs_t>(averageFrameTime);
184 }
185 
calculateRefreshRateIfPossible(const RefreshRateConfigs & refreshRateConfigs,nsecs_t now)186 std::optional<Fps> LayerInfo::calculateRefreshRateIfPossible(
187         const RefreshRateConfigs& refreshRateConfigs, nsecs_t now) {
188     static constexpr float MARGIN = 1.0f; // 1Hz
189     if (!hasEnoughDataForHeuristic()) {
190         ALOGV("Not enough data");
191         return std::nullopt;
192     }
193 
194     const auto averageFrameTime = calculateAverageFrameTime();
195     if (averageFrameTime.has_value()) {
196         const auto refreshRate = Fps::fromPeriodNsecs(*averageFrameTime);
197         const bool refreshRateConsistent = mRefreshRateHistory.add(refreshRate, now);
198         if (refreshRateConsistent) {
199             const auto knownRefreshRate = refreshRateConfigs.findClosestKnownFrameRate(refreshRate);
200             // To avoid oscillation, use the last calculated refresh rate if it is
201             // close enough
202             if (std::abs(mLastRefreshRate.calculated.getValue() - refreshRate.getValue()) >
203                         MARGIN &&
204                 !mLastRefreshRate.reported.equalsWithMargin(knownRefreshRate)) {
205                 mLastRefreshRate.calculated = refreshRate;
206                 mLastRefreshRate.reported = knownRefreshRate;
207             }
208 
209             ALOGV("%s %s rounded to nearest known frame rate %s", mName.c_str(),
210                   to_string(refreshRate).c_str(), to_string(mLastRefreshRate.reported).c_str());
211         } else {
212             ALOGV("%s Not stable (%s) returning last known frame rate %s", mName.c_str(),
213                   to_string(refreshRate).c_str(), to_string(mLastRefreshRate.reported).c_str());
214         }
215     }
216 
217     return mLastRefreshRate.reported.isValid() ? std::make_optional(mLastRefreshRate.reported)
218                                                : std::nullopt;
219 }
220 
getRefreshRateVote(const RefreshRateConfigs & refreshRateConfigs,nsecs_t now)221 LayerInfo::LayerVote LayerInfo::getRefreshRateVote(const RefreshRateConfigs& refreshRateConfigs,
222                                                    nsecs_t now) {
223     if (mLayerVote.type != LayerHistory::LayerVoteType::Heuristic) {
224         ALOGV("%s voted %d ", mName.c_str(), static_cast<int>(mLayerVote.type));
225         return mLayerVote;
226     }
227 
228     if (isAnimating(now)) {
229         ALOGV("%s is animating", mName.c_str());
230         mLastRefreshRate.animatingOrInfrequent = true;
231         return {LayerHistory::LayerVoteType::Max, Fps(0.0f)};
232     }
233 
234     if (!isFrequent(now)) {
235         ALOGV("%s is infrequent", mName.c_str());
236         mLastRefreshRate.animatingOrInfrequent = true;
237         // Infrequent layers vote for mininal refresh rate for
238         // battery saving purposes and also to prevent b/135718869.
239         return {LayerHistory::LayerVoteType::Min, Fps(0.0f)};
240     }
241 
242     // If the layer was previously tagged as animating or infrequent, we clear
243     // the history as it is likely the layer just changed its behavior
244     // and we should not look at stale data
245     if (mLastRefreshRate.animatingOrInfrequent) {
246         clearHistory(now);
247     }
248 
249     auto refreshRate = calculateRefreshRateIfPossible(refreshRateConfigs, now);
250     if (refreshRate.has_value()) {
251         ALOGV("%s calculated refresh rate: %s", mName.c_str(), to_string(*refreshRate).c_str());
252         return {LayerHistory::LayerVoteType::Heuristic, refreshRate.value()};
253     }
254 
255     ALOGV("%s Max (can't resolve refresh rate)", mName.c_str());
256     return {LayerHistory::LayerVoteType::Max, Fps(0.0f)};
257 }
258 
getTraceTag(android::scheduler::LayerHistory::LayerVoteType type) const259 const char* LayerInfo::getTraceTag(android::scheduler::LayerHistory::LayerVoteType type) const {
260     if (mTraceTags.count(type) == 0) {
261         const auto tag = "LFPS " + mName + " " + RefreshRateConfigs::layerVoteTypeString(type);
262         mTraceTags.emplace(type, tag);
263     }
264 
265     return mTraceTags.at(type).c_str();
266 }
267 
268 LayerInfo::RefreshRateHistory::HeuristicTraceTagData
makeHeuristicTraceTagData() const269 LayerInfo::RefreshRateHistory::makeHeuristicTraceTagData() const {
270     const std::string prefix = "LFPS ";
271     const std::string suffix = "Heuristic ";
272     return {.min = prefix + mName + suffix + "min",
273             .max = prefix + mName + suffix + "max",
274             .consistent = prefix + mName + suffix + "consistent",
275             .average = prefix + mName + suffix + "average"};
276 }
277 
clear()278 void LayerInfo::RefreshRateHistory::clear() {
279     mRefreshRates.clear();
280 }
281 
add(Fps refreshRate,nsecs_t now)282 bool LayerInfo::RefreshRateHistory::add(Fps refreshRate, nsecs_t now) {
283     mRefreshRates.push_back({refreshRate, now});
284     while (mRefreshRates.size() >= HISTORY_SIZE ||
285            now - mRefreshRates.front().timestamp > HISTORY_DURATION.count()) {
286         mRefreshRates.pop_front();
287     }
288 
289     if (CC_UNLIKELY(sTraceEnabled)) {
290         if (!mHeuristicTraceTagData.has_value()) {
291             mHeuristicTraceTagData = makeHeuristicTraceTagData();
292         }
293 
294         ATRACE_INT(mHeuristicTraceTagData->average.c_str(), refreshRate.getIntValue());
295     }
296 
297     return isConsistent();
298 }
299 
isConsistent() const300 bool LayerInfo::RefreshRateHistory::isConsistent() const {
301     if (mRefreshRates.empty()) return true;
302 
303     const auto max = std::max_element(mRefreshRates.begin(), mRefreshRates.end());
304     const auto min = std::min_element(mRefreshRates.begin(), mRefreshRates.end());
305     const auto consistent =
306             max->refreshRate.getValue() - min->refreshRate.getValue() < MARGIN_CONSISTENT_FPS;
307 
308     if (CC_UNLIKELY(sTraceEnabled)) {
309         if (!mHeuristicTraceTagData.has_value()) {
310             mHeuristicTraceTagData = makeHeuristicTraceTagData();
311         }
312 
313         ATRACE_INT(mHeuristicTraceTagData->max.c_str(), max->refreshRate.getIntValue());
314         ATRACE_INT(mHeuristicTraceTagData->min.c_str(), min->refreshRate.getIntValue());
315         ATRACE_INT(mHeuristicTraceTagData->consistent.c_str(), consistent);
316     }
317 
318     return consistent;
319 }
320 
321 } // namespace android::scheduler
322 
323 // TODO(b/129481165): remove the #pragma below and fix conversion issues
324 #pragma clang diagnostic pop // ignored "-Wextra"