blob: 314526a99dcf563c8df335bdb2090d7f79362f4e [file] [log] [blame]
Ady Abraham8a82ba62020-01-17 12:43:17 -08001/*
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
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wextra"
20
Ady Abraham8a82ba62020-01-17 12:43:17 -080021// #define LOG_NDEBUG 0
Ady Abraham0ccd79b2020-06-10 10:11:17 -070022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
Ady Abraham8a82ba62020-01-17 12:43:17 -080023
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010024#include "LayerInfo.h"
Ady Abraham8a82ba62020-01-17 12:43:17 -080025
26#include <algorithm>
27#include <utility>
28
Ady Abraham0ccd79b2020-06-10 10:11:17 -070029#include <cutils/compiler.h>
30#include <cutils/trace.h>
31
Ady Abraham8a82ba62020-01-17 12:43:17 -080032#undef LOG_TAG
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010033#define LOG_TAG "LayerInfo"
Ady Abraham8a82ba62020-01-17 12:43:17 -080034
35namespace android::scheduler {
36
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010037bool LayerInfo::sTraceEnabled = false;
Ady Abrahamb1b9d412020-06-01 19:53:52 -070038
Ady Abrahambdda8f02021-04-01 16:06:11 -070039LayerInfo::LayerInfo(const std::string& name, uid_t ownerUid,
40 LayerHistory::LayerVoteType defaultVote)
Ady Abrahama6b676e2020-05-27 14:29:09 -070041 : mName(name),
Ady Abrahambdda8f02021-04-01 16:06:11 -070042 mOwnerUid(ownerUid),
Ady Abraham8a82ba62020-01-17 12:43:17 -080043 mDefaultVote(defaultVote),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070044 mLayerVote({defaultVote, Fps()}),
Ady Abraham0ccd79b2020-06-10 10:11:17 -070045 mRefreshRateHistory(name) {}
Ady Abraham8a82ba62020-01-17 12:43:17 -080046
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010047void LayerInfo::setLastPresentTime(nsecs_t lastPresentTime, nsecs_t now, LayerUpdateType updateType,
Ady Abrahambdda8f02021-04-01 16:06:11 -070048 bool pendingModeChange, LayerProps props) {
Ady Abraham8a82ba62020-01-17 12:43:17 -080049 lastPresentTime = std::max(lastPresentTime, static_cast<nsecs_t>(0));
50
51 mLastUpdatedTime = std::max(lastPresentTime, now);
Ady Abrahambdda8f02021-04-01 16:06:11 -070052 mLayerProps = props;
Ady Abraham5def7332020-05-29 16:13:47 -070053 switch (updateType) {
54 case LayerUpdateType::AnimationTX:
55 mLastAnimationTime = std::max(lastPresentTime, now);
56 break;
57 case LayerUpdateType::SetFrameRate:
58 case LayerUpdateType::Buffer:
Marin Shalamanov2045d5b2020-12-28 18:11:41 +010059 FrameTimeData frameTime = {.presentTime = lastPresentTime,
Ady Abraham5def7332020-05-29 16:13:47 -070060 .queueTime = mLastUpdatedTime,
Marin Shalamanova7fe3042021-01-29 21:02:08 +010061 .pendingModeChange = pendingModeChange};
Ady Abraham5def7332020-05-29 16:13:47 -070062 mFrameTimes.push_back(frameTime);
63 if (mFrameTimes.size() > HISTORY_SIZE) {
64 mFrameTimes.pop_front();
65 }
66 break;
Ady Abraham8a82ba62020-01-17 12:43:17 -080067 }
68}
69
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010070bool LayerInfo::isFrameTimeValid(const FrameTimeData& frameTime) const {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000071 return frameTime.queueTime >= std::chrono::duration_cast<std::chrono::nanoseconds>(
72 mFrameTimeValidSince.time_since_epoch())
73 .count();
74}
Ady Abraham1adbb722020-05-15 11:51:48 -070075
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010076bool LayerInfo::isFrequent(nsecs_t now) const {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000077 // If we know nothing about this layer we consider it as frequent as it might be the start
78 // of an animation.
Marin Shalamanov2045d5b2020-12-28 18:11:41 +010079 if (mFrameTimes.size() < kFrequentLayerWindowSize) {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000080 return true;
81 }
82
83 // Find the first active frame
Ady Abraham983e5682020-05-28 16:49:18 -070084 auto it = mFrameTimes.begin();
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000085 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());
Marin Shalamanov2045d5b2020-12-28 18:11:41 +010092 if (numFrames < kFrequentLayerWindowSize) {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000093 return false;
94 }
95
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070096 using fps_approx_ops::operator>=;
97
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000098 // Layer is considered frequent if the average frame rate is higher than the threshold
99 const auto totalTime = mFrameTimes.back().queueTime - it->queueTime;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700100 return Fps::fromPeriodNsecs(totalTime / (numFrames - 1)) >= kMinFpsForFrequentLayer;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800101}
102
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100103bool LayerInfo::isAnimating(nsecs_t now) const {
Ady Abraham5def7332020-05-29 16:13:47 -0700104 return mLastAnimationTime >= getActiveLayerThreshold(now);
105}
106
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100107bool LayerInfo::hasEnoughDataForHeuristic() const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700108 // The layer had to publish at least HISTORY_SIZE or HISTORY_DURATION of updates
Ady Abrahama61edcb2020-01-30 18:32:03 -0800109 if (mFrameTimes.size() < 2) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700110 ALOGV("fewer than 2 frames recorded: %zu", mFrameTimes.size());
Ady Abrahama61edcb2020-01-30 18:32:03 -0800111 return false;
112 }
113
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000114 if (!isFrameTimeValid(mFrameTimes.front())) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700115 ALOGV("stale frames still captured");
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000116 return false;
117 }
118
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700119 const auto totalDuration = mFrameTimes.back().queueTime - mFrameTimes.front().queueTime;
120 if (mFrameTimes.size() < HISTORY_SIZE && totalDuration < HISTORY_DURATION.count()) {
121 ALOGV("not enough frames captured: %zu | %.2f seconds", mFrameTimes.size(),
122 totalDuration / 1e9f);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800123 return false;
124 }
125
126 return true;
127}
128
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100129std::optional<nsecs_t> LayerInfo::calculateAverageFrameTime() const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100130 // Ignore frames captured during a mode change
131 const bool isDuringModeChange =
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100132 std::any_of(mFrameTimes.begin(), mFrameTimes.end(),
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100133 [](const auto& frame) { return frame.pendingModeChange; });
134 if (isDuringModeChange) {
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100135 return std::nullopt;
136 }
Ady Abraham32efd542020-05-19 17:49:26 -0700137
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100138 const bool isMissingPresentTime =
139 std::any_of(mFrameTimes.begin(), mFrameTimes.end(),
140 [](auto frame) { return frame.presentTime == 0; });
141 if (isMissingPresentTime && !mLastRefreshRate.reported.isValid()) {
142 // If there are no presentation timestamps and we haven't calculated
143 // one in the past then we can't calculate the refresh rate
144 return std::nullopt;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800145 }
Ady Abrahamc9664832020-05-12 14:16:56 -0700146
Ady Abrahamc9664832020-05-12 14:16:56 -0700147 // Calculate the average frame time based on presentation timestamps. If those
148 // doesn't exist, we look at the time the buffer was queued only. We can do that only if
149 // we calculated a refresh rate based on presentation timestamps in the past. The reason
150 // we look at the queue time is to handle cases where hwui attaches presentation timestamps
151 // when implementing render ahead for specific refresh rates. When hwui no longer provides
152 // presentation timestamps we look at the queue time to see if the current refresh rate still
153 // matches the content.
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700154
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100155 auto getFrameTime = isMissingPresentTime ? [](FrameTimeData data) { return data.queueTime; }
156 : [](FrameTimeData data) { return data.presentTime; };
157
158 nsecs_t totalDeltas = 0;
159 int numDeltas = 0;
160 auto prevFrame = mFrameTimes.begin();
161 for (auto it = mFrameTimes.begin() + 1; it != mFrameTimes.end(); ++it) {
162 const auto currDelta = getFrameTime(*it) - getFrameTime(*prevFrame);
163 if (currDelta < kMinPeriodBetweenFrames) {
164 // Skip this frame, but count the delta into the next frame
165 continue;
166 }
167
168 prevFrame = it;
169
170 if (currDelta > kMaxPeriodBetweenFrames) {
171 // Skip this frame and the current delta.
172 continue;
173 }
174
175 totalDeltas += currDelta;
176 numDeltas++;
177 }
178
179 if (numDeltas == 0) {
180 return std::nullopt;
181 }
182
183 const auto averageFrameTime = static_cast<double>(totalDeltas) / static_cast<double>(numDeltas);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700184 return static_cast<nsecs_t>(averageFrameTime);
Ady Abraham32efd542020-05-19 17:49:26 -0700185}
Ady Abraham8a82ba62020-01-17 12:43:17 -0800186
Ady Abraham3efa3942021-06-24 19:01:25 -0700187std::optional<Fps> LayerInfo::calculateRefreshRateIfPossible(
188 const RefreshRateConfigs& refreshRateConfigs, nsecs_t now) {
Ady Abraham32efd542020-05-19 17:49:26 -0700189 static constexpr float MARGIN = 1.0f; // 1Hz
Ady Abraham32efd542020-05-19 17:49:26 -0700190 if (!hasEnoughDataForHeuristic()) {
191 ALOGV("Not enough data");
192 return std::nullopt;
193 }
194
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700195 if (const auto averageFrameTime = calculateAverageFrameTime()) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100196 const auto refreshRate = Fps::fromPeriodNsecs(*averageFrameTime);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700197 const bool refreshRateConsistent = mRefreshRateHistory.add(refreshRate, now);
198 if (refreshRateConsistent) {
Ady Abraham3efa3942021-06-24 19:01:25 -0700199 const auto knownRefreshRate = refreshRateConfigs.findClosestKnownFrameRate(refreshRate);
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700200 using fps_approx_ops::operator!=;
201
202 // To avoid oscillation, use the last calculated refresh rate if it is close enough.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100203 if (std::abs(mLastRefreshRate.calculated.getValue() - refreshRate.getValue()) >
204 MARGIN &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700205 mLastRefreshRate.reported != knownRefreshRate) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700206 mLastRefreshRate.calculated = refreshRate;
207 mLastRefreshRate.reported = knownRefreshRate;
208 }
209
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100210 ALOGV("%s %s rounded to nearest known frame rate %s", mName.c_str(),
211 to_string(refreshRate).c_str(), to_string(mLastRefreshRate.reported).c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700212 } else {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100213 ALOGV("%s Not stable (%s) returning last known frame rate %s", mName.c_str(),
214 to_string(refreshRate).c_str(), to_string(mLastRefreshRate.reported).c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700215 }
Ady Abraham32efd542020-05-19 17:49:26 -0700216 }
217
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100218 return mLastRefreshRate.reported.isValid() ? std::make_optional(mLastRefreshRate.reported)
219 : std::nullopt;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800220}
221
Ady Abraham3efa3942021-06-24 19:01:25 -0700222LayerInfo::LayerVote LayerInfo::getRefreshRateVote(const RefreshRateConfigs& refreshRateConfigs,
223 nsecs_t now) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800224 if (mLayerVote.type != LayerHistory::LayerVoteType::Heuristic) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700225 ALOGV("%s voted %d ", mName.c_str(), static_cast<int>(mLayerVote.type));
Marin Shalamanov46084422020-10-13 12:33:42 +0200226 return mLayerVote;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800227 }
228
Ady Abraham5def7332020-05-29 16:13:47 -0700229 if (isAnimating(now)) {
230 ALOGV("%s is animating", mName.c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700231 mLastRefreshRate.animatingOrInfrequent = true;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700232 return {LayerHistory::LayerVoteType::Max, Fps()};
Ady Abraham5def7332020-05-29 16:13:47 -0700233 }
234
Ady Abraham8a82ba62020-01-17 12:43:17 -0800235 if (!isFrequent(now)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700236 ALOGV("%s is infrequent", mName.c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700237 mLastRefreshRate.animatingOrInfrequent = true;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700238 // Infrequent layers vote for minimal refresh rate for
Marin Shalamanov29e25402021-04-07 21:09:58 +0200239 // battery saving purposes and also to prevent b/135718869.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700240 return {LayerHistory::LayerVoteType::Min, Fps()};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800241 }
242
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700243 // If the layer was previously tagged as animating or infrequent, we clear
244 // the history as it is likely the layer just changed its behavior
245 // and we should not look at stale data
246 if (mLastRefreshRate.animatingOrInfrequent) {
247 clearHistory(now);
248 }
249
Ady Abraham3efa3942021-06-24 19:01:25 -0700250 auto refreshRate = calculateRefreshRateIfPossible(refreshRateConfigs, now);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800251 if (refreshRate.has_value()) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100252 ALOGV("%s calculated refresh rate: %s", mName.c_str(), to_string(*refreshRate).c_str());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800253 return {LayerHistory::LayerVoteType::Heuristic, refreshRate.value()};
254 }
255
Ady Abrahama6b676e2020-05-27 14:29:09 -0700256 ALOGV("%s Max (can't resolve refresh rate)", mName.c_str());
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700257 return {LayerHistory::LayerVoteType::Max, Fps()};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800258}
259
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100260const char* LayerInfo::getTraceTag(android::scheduler::LayerHistory::LayerVoteType type) const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700261 if (mTraceTags.count(type) == 0) {
262 const auto tag = "LFPS " + mName + " " + RefreshRateConfigs::layerVoteTypeString(type);
263 mTraceTags.emplace(type, tag);
264 }
265
266 return mTraceTags.at(type).c_str();
267}
268
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100269LayerInfo::RefreshRateHistory::HeuristicTraceTagData
270LayerInfo::RefreshRateHistory::makeHeuristicTraceTagData() const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700271 const std::string prefix = "LFPS ";
272 const std::string suffix = "Heuristic ";
273 return {.min = prefix + mName + suffix + "min",
274 .max = prefix + mName + suffix + "max",
275 .consistent = prefix + mName + suffix + "consistent",
276 .average = prefix + mName + suffix + "average"};
277}
278
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100279void LayerInfo::RefreshRateHistory::clear() {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700280 mRefreshRates.clear();
281}
282
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100283bool LayerInfo::RefreshRateHistory::add(Fps refreshRate, nsecs_t now) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700284 mRefreshRates.push_back({refreshRate, now});
285 while (mRefreshRates.size() >= HISTORY_SIZE ||
286 now - mRefreshRates.front().timestamp > HISTORY_DURATION.count()) {
287 mRefreshRates.pop_front();
288 }
289
290 if (CC_UNLIKELY(sTraceEnabled)) {
291 if (!mHeuristicTraceTagData.has_value()) {
292 mHeuristicTraceTagData = makeHeuristicTraceTagData();
293 }
294
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100295 ATRACE_INT(mHeuristicTraceTagData->average.c_str(), refreshRate.getIntValue());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700296 }
297
298 return isConsistent();
299}
300
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100301bool LayerInfo::RefreshRateHistory::isConsistent() const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700302 if (mRefreshRates.empty()) return true;
303
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700304 const auto [min, max] =
305 std::minmax_element(mRefreshRates.begin(), mRefreshRates.end(),
306 [](const auto& lhs, const auto& rhs) {
307 return isStrictlyLess(lhs.refreshRate, rhs.refreshRate);
308 });
309
310 const bool consistent =
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100311 max->refreshRate.getValue() - min->refreshRate.getValue() < MARGIN_CONSISTENT_FPS;
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700312
313 if (CC_UNLIKELY(sTraceEnabled)) {
314 if (!mHeuristicTraceTagData.has_value()) {
315 mHeuristicTraceTagData = makeHeuristicTraceTagData();
316 }
317
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100318 ATRACE_INT(mHeuristicTraceTagData->max.c_str(), max->refreshRate.getIntValue());
319 ATRACE_INT(mHeuristicTraceTagData->min.c_str(), min->refreshRate.getIntValue());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700320 ATRACE_INT(mHeuristicTraceTagData->consistent.c_str(), consistent);
321 }
322
323 return consistent;
324}
325
Ady Abraham8a82ba62020-01-17 12:43:17 -0800326} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100327
328// TODO(b/129481165): remove the #pragma below and fix conversion issues
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700329#pragma clang diagnostic pop // ignored "-Wextra"