blob: ae61eeb660f9bc7f1e98b31d302cc58685afecf7 [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>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070031#include <ftl/enum.h>
Ady Abraham0ccd79b2020-06-10 10:11:17 -070032
Ady Abraham8a82ba62020-01-17 12:43:17 -080033#undef LOG_TAG
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010034#define LOG_TAG "LayerInfo"
Ady Abraham8a82ba62020-01-17 12:43:17 -080035
36namespace android::scheduler {
37
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010038bool LayerInfo::sTraceEnabled = false;
Ady Abrahamb1b9d412020-06-01 19:53:52 -070039
Ady Abrahambdda8f02021-04-01 16:06:11 -070040LayerInfo::LayerInfo(const std::string& name, uid_t ownerUid,
41 LayerHistory::LayerVoteType defaultVote)
Ady Abrahama6b676e2020-05-27 14:29:09 -070042 : mName(name),
Ady Abrahambdda8f02021-04-01 16:06:11 -070043 mOwnerUid(ownerUid),
Ady Abraham8a82ba62020-01-17 12:43:17 -080044 mDefaultVote(defaultVote),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070045 mLayerVote({defaultVote, Fps()}),
Ady Abraham0ccd79b2020-06-10 10:11:17 -070046 mRefreshRateHistory(name) {}
Ady Abraham8a82ba62020-01-17 12:43:17 -080047
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010048void LayerInfo::setLastPresentTime(nsecs_t lastPresentTime, nsecs_t now, LayerUpdateType updateType,
Ady Abrahambdda8f02021-04-01 16:06:11 -070049 bool pendingModeChange, LayerProps props) {
Ady Abraham8a82ba62020-01-17 12:43:17 -080050 lastPresentTime = std::max(lastPresentTime, static_cast<nsecs_t>(0));
51
52 mLastUpdatedTime = std::max(lastPresentTime, now);
Ady Abrahambdda8f02021-04-01 16:06:11 -070053 mLayerProps = props;
Ady Abraham5def7332020-05-29 16:13:47 -070054 switch (updateType) {
55 case LayerUpdateType::AnimationTX:
56 mLastAnimationTime = std::max(lastPresentTime, now);
57 break;
58 case LayerUpdateType::SetFrameRate:
59 case LayerUpdateType::Buffer:
Marin Shalamanov2045d5b2020-12-28 18:11:41 +010060 FrameTimeData frameTime = {.presentTime = lastPresentTime,
Ady Abraham5def7332020-05-29 16:13:47 -070061 .queueTime = mLastUpdatedTime,
Marin Shalamanova7fe3042021-01-29 21:02:08 +010062 .pendingModeChange = pendingModeChange};
Ady Abraham5def7332020-05-29 16:13:47 -070063 mFrameTimes.push_back(frameTime);
64 if (mFrameTimes.size() > HISTORY_SIZE) {
65 mFrameTimes.pop_front();
66 }
67 break;
Ady Abraham8a82ba62020-01-17 12:43:17 -080068 }
69}
70
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010071bool LayerInfo::isFrameTimeValid(const FrameTimeData& frameTime) const {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000072 return frameTime.queueTime >= std::chrono::duration_cast<std::chrono::nanoseconds>(
73 mFrameTimeValidSince.time_since_epoch())
74 .count();
75}
Ady Abraham1adbb722020-05-15 11:51:48 -070076
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010077bool LayerInfo::isFrequent(nsecs_t now) const {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000078 // If we know nothing about this layer we consider it as frequent as it might be the start
79 // of an animation.
Marin Shalamanov2045d5b2020-12-28 18:11:41 +010080 if (mFrameTimes.size() < kFrequentLayerWindowSize) {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000081 return true;
82 }
83
84 // Find the first active frame
Ady Abraham983e5682020-05-28 16:49:18 -070085 auto it = mFrameTimes.begin();
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000086 for (; it != mFrameTimes.end(); ++it) {
87 if (it->queueTime >= getActiveLayerThreshold(now)) {
88 break;
89 }
90 }
91
92 const auto numFrames = std::distance(it, mFrameTimes.end());
Marin Shalamanov2045d5b2020-12-28 18:11:41 +010093 if (numFrames < kFrequentLayerWindowSize) {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000094 return false;
95 }
96
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070097 using fps_approx_ops::operator>=;
98
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000099 // Layer is considered frequent if the average frame rate is higher than the threshold
100 const auto totalTime = mFrameTimes.back().queueTime - it->queueTime;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700101 return Fps::fromPeriodNsecs(totalTime / (numFrames - 1)) >= kMinFpsForFrequentLayer;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800102}
103
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100104bool LayerInfo::isAnimating(nsecs_t now) const {
Ady Abraham5def7332020-05-29 16:13:47 -0700105 return mLastAnimationTime >= getActiveLayerThreshold(now);
106}
107
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100108bool LayerInfo::hasEnoughDataForHeuristic() const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700109 // The layer had to publish at least HISTORY_SIZE or HISTORY_DURATION of updates
Ady Abrahama61edcb2020-01-30 18:32:03 -0800110 if (mFrameTimes.size() < 2) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700111 ALOGV("fewer than 2 frames recorded: %zu", mFrameTimes.size());
Ady Abrahama61edcb2020-01-30 18:32:03 -0800112 return false;
113 }
114
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000115 if (!isFrameTimeValid(mFrameTimes.front())) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700116 ALOGV("stale frames still captured");
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000117 return false;
118 }
119
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700120 const auto totalDuration = mFrameTimes.back().queueTime - mFrameTimes.front().queueTime;
121 if (mFrameTimes.size() < HISTORY_SIZE && totalDuration < HISTORY_DURATION.count()) {
122 ALOGV("not enough frames captured: %zu | %.2f seconds", mFrameTimes.size(),
123 totalDuration / 1e9f);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800124 return false;
125 }
126
127 return true;
128}
129
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100130std::optional<nsecs_t> LayerInfo::calculateAverageFrameTime() const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100131 // Ignore frames captured during a mode change
132 const bool isDuringModeChange =
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100133 std::any_of(mFrameTimes.begin(), mFrameTimes.end(),
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100134 [](const auto& frame) { return frame.pendingModeChange; });
135 if (isDuringModeChange) {
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100136 return std::nullopt;
137 }
Ady Abraham32efd542020-05-19 17:49:26 -0700138
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100139 const bool isMissingPresentTime =
140 std::any_of(mFrameTimes.begin(), mFrameTimes.end(),
141 [](auto frame) { return frame.presentTime == 0; });
142 if (isMissingPresentTime && !mLastRefreshRate.reported.isValid()) {
143 // If there are no presentation timestamps and we haven't calculated
144 // one in the past then we can't calculate the refresh rate
145 return std::nullopt;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800146 }
Ady Abrahamc9664832020-05-12 14:16:56 -0700147
Ady Abrahamc9664832020-05-12 14:16:56 -0700148 // Calculate the average frame time based on presentation timestamps. If those
149 // doesn't exist, we look at the time the buffer was queued only. We can do that only if
150 // we calculated a refresh rate based on presentation timestamps in the past. The reason
151 // we look at the queue time is to handle cases where hwui attaches presentation timestamps
152 // when implementing render ahead for specific refresh rates. When hwui no longer provides
153 // presentation timestamps we look at the queue time to see if the current refresh rate still
154 // matches the content.
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700155
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100156 auto getFrameTime = isMissingPresentTime ? [](FrameTimeData data) { return data.queueTime; }
157 : [](FrameTimeData data) { return data.presentTime; };
158
159 nsecs_t totalDeltas = 0;
160 int numDeltas = 0;
161 auto prevFrame = mFrameTimes.begin();
162 for (auto it = mFrameTimes.begin() + 1; it != mFrameTimes.end(); ++it) {
163 const auto currDelta = getFrameTime(*it) - getFrameTime(*prevFrame);
164 if (currDelta < kMinPeriodBetweenFrames) {
165 // Skip this frame, but count the delta into the next frame
166 continue;
167 }
168
169 prevFrame = it;
170
171 if (currDelta > kMaxPeriodBetweenFrames) {
172 // Skip this frame and the current delta.
173 continue;
174 }
175
176 totalDeltas += currDelta;
177 numDeltas++;
178 }
179
180 if (numDeltas == 0) {
181 return std::nullopt;
182 }
183
184 const auto averageFrameTime = static_cast<double>(totalDeltas) / static_cast<double>(numDeltas);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700185 return static_cast<nsecs_t>(averageFrameTime);
Ady Abraham32efd542020-05-19 17:49:26 -0700186}
Ady Abraham8a82ba62020-01-17 12:43:17 -0800187
Ady Abraham3efa3942021-06-24 19:01:25 -0700188std::optional<Fps> LayerInfo::calculateRefreshRateIfPossible(
189 const RefreshRateConfigs& refreshRateConfigs, nsecs_t now) {
Ady Abraham32efd542020-05-19 17:49:26 -0700190 static constexpr float MARGIN = 1.0f; // 1Hz
Ady Abraham32efd542020-05-19 17:49:26 -0700191 if (!hasEnoughDataForHeuristic()) {
192 ALOGV("Not enough data");
193 return std::nullopt;
194 }
195
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700196 if (const auto averageFrameTime = calculateAverageFrameTime()) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100197 const auto refreshRate = Fps::fromPeriodNsecs(*averageFrameTime);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700198 const bool refreshRateConsistent = mRefreshRateHistory.add(refreshRate, now);
199 if (refreshRateConsistent) {
Ady Abraham3efa3942021-06-24 19:01:25 -0700200 const auto knownRefreshRate = refreshRateConfigs.findClosestKnownFrameRate(refreshRate);
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700201 using fps_approx_ops::operator!=;
202
203 // To avoid oscillation, use the last calculated refresh rate if it is close enough.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100204 if (std::abs(mLastRefreshRate.calculated.getValue() - refreshRate.getValue()) >
205 MARGIN &&
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700206 mLastRefreshRate.reported != knownRefreshRate) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700207 mLastRefreshRate.calculated = refreshRate;
208 mLastRefreshRate.reported = knownRefreshRate;
209 }
210
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100211 ALOGV("%s %s rounded to nearest known frame rate %s", mName.c_str(),
212 to_string(refreshRate).c_str(), to_string(mLastRefreshRate.reported).c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700213 } else {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100214 ALOGV("%s Not stable (%s) returning last known frame rate %s", mName.c_str(),
215 to_string(refreshRate).c_str(), to_string(mLastRefreshRate.reported).c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700216 }
Ady Abraham32efd542020-05-19 17:49:26 -0700217 }
218
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100219 return mLastRefreshRate.reported.isValid() ? std::make_optional(mLastRefreshRate.reported)
220 : std::nullopt;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800221}
222
Ady Abraham3efa3942021-06-24 19:01:25 -0700223LayerInfo::LayerVote LayerInfo::getRefreshRateVote(const RefreshRateConfigs& refreshRateConfigs,
224 nsecs_t now) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800225 if (mLayerVote.type != LayerHistory::LayerVoteType::Heuristic) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700226 ALOGV("%s voted %d ", mName.c_str(), static_cast<int>(mLayerVote.type));
Marin Shalamanov46084422020-10-13 12:33:42 +0200227 return mLayerVote;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800228 }
229
Ady Abraham5def7332020-05-29 16:13:47 -0700230 if (isAnimating(now)) {
231 ALOGV("%s is animating", mName.c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700232 mLastRefreshRate.animatingOrInfrequent = true;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700233 return {LayerHistory::LayerVoteType::Max, Fps()};
Ady Abraham5def7332020-05-29 16:13:47 -0700234 }
235
Ady Abraham8a82ba62020-01-17 12:43:17 -0800236 if (!isFrequent(now)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700237 ALOGV("%s is infrequent", mName.c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700238 mLastRefreshRate.animatingOrInfrequent = true;
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700239 // Infrequent layers vote for minimal refresh rate for
Marin Shalamanov29e25402021-04-07 21:09:58 +0200240 // battery saving purposes and also to prevent b/135718869.
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700241 return {LayerHistory::LayerVoteType::Min, Fps()};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800242 }
243
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700244 // If the layer was previously tagged as animating or infrequent, we clear
245 // the history as it is likely the layer just changed its behavior
246 // and we should not look at stale data
247 if (mLastRefreshRate.animatingOrInfrequent) {
248 clearHistory(now);
249 }
250
Ady Abraham3efa3942021-06-24 19:01:25 -0700251 auto refreshRate = calculateRefreshRateIfPossible(refreshRateConfigs, now);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800252 if (refreshRate.has_value()) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100253 ALOGV("%s calculated refresh rate: %s", mName.c_str(), to_string(*refreshRate).c_str());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800254 return {LayerHistory::LayerVoteType::Heuristic, refreshRate.value()};
255 }
256
Ady Abrahama6b676e2020-05-27 14:29:09 -0700257 ALOGV("%s Max (can't resolve refresh rate)", mName.c_str());
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700258 return {LayerHistory::LayerVoteType::Max, Fps()};
Ady Abraham8a82ba62020-01-17 12:43:17 -0800259}
260
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700261const char* LayerInfo::getTraceTag(LayerHistory::LayerVoteType type) const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700262 if (mTraceTags.count(type) == 0) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700263 auto tag = "LFPS " + mName + " " + ftl::enum_string(type);
264 mTraceTags.emplace(type, std::move(tag));
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700265 }
266
267 return mTraceTags.at(type).c_str();
268}
269
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100270LayerInfo::RefreshRateHistory::HeuristicTraceTagData
271LayerInfo::RefreshRateHistory::makeHeuristicTraceTagData() const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700272 const std::string prefix = "LFPS ";
273 const std::string suffix = "Heuristic ";
274 return {.min = prefix + mName + suffix + "min",
275 .max = prefix + mName + suffix + "max",
276 .consistent = prefix + mName + suffix + "consistent",
277 .average = prefix + mName + suffix + "average"};
278}
279
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100280void LayerInfo::RefreshRateHistory::clear() {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700281 mRefreshRates.clear();
282}
283
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100284bool LayerInfo::RefreshRateHistory::add(Fps refreshRate, nsecs_t now) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700285 mRefreshRates.push_back({refreshRate, now});
286 while (mRefreshRates.size() >= HISTORY_SIZE ||
287 now - mRefreshRates.front().timestamp > HISTORY_DURATION.count()) {
288 mRefreshRates.pop_front();
289 }
290
291 if (CC_UNLIKELY(sTraceEnabled)) {
292 if (!mHeuristicTraceTagData.has_value()) {
293 mHeuristicTraceTagData = makeHeuristicTraceTagData();
294 }
295
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100296 ATRACE_INT(mHeuristicTraceTagData->average.c_str(), refreshRate.getIntValue());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700297 }
298
299 return isConsistent();
300}
301
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100302bool LayerInfo::RefreshRateHistory::isConsistent() const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700303 if (mRefreshRates.empty()) return true;
304
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700305 const auto [min, max] =
306 std::minmax_element(mRefreshRates.begin(), mRefreshRates.end(),
307 [](const auto& lhs, const auto& rhs) {
308 return isStrictlyLess(lhs.refreshRate, rhs.refreshRate);
309 });
310
311 const bool consistent =
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100312 max->refreshRate.getValue() - min->refreshRate.getValue() < MARGIN_CONSISTENT_FPS;
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700313
314 if (CC_UNLIKELY(sTraceEnabled)) {
315 if (!mHeuristicTraceTagData.has_value()) {
316 mHeuristicTraceTagData = makeHeuristicTraceTagData();
317 }
318
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100319 ATRACE_INT(mHeuristicTraceTagData->max.c_str(), max->refreshRate.getIntValue());
320 ATRACE_INT(mHeuristicTraceTagData->min.c_str(), min->refreshRate.getIntValue());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700321 ATRACE_INT(mHeuristicTraceTagData->consistent.c_str(), consistent);
322 }
323
324 return consistent;
325}
326
Ady Abraham8a82ba62020-01-17 12:43:17 -0800327} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100328
329// TODO(b/129481165): remove the #pragma below and fix conversion issues
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700330#pragma clang diagnostic pop // ignored "-Wextra"