blob: 94e7e202516c93d6646ae227f0cf159ac1a542cf [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
17// #define LOG_NDEBUG 0
Ady Abraham0ccd79b2020-06-10 10:11:17 -070018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
Ady Abraham8a82ba62020-01-17 12:43:17 -080019
20#include "LayerInfoV2.h"
21
22#include <algorithm>
23#include <utility>
24
Ady Abraham0ccd79b2020-06-10 10:11:17 -070025#include <cutils/compiler.h>
26#include <cutils/trace.h>
27
Ady Abraham8a82ba62020-01-17 12:43:17 -080028#undef LOG_TAG
29#define LOG_TAG "LayerInfoV2"
Ady Abraham8a82ba62020-01-17 12:43:17 -080030
31namespace android::scheduler {
32
Ady Abrahamb1b9d412020-06-01 19:53:52 -070033const RefreshRateConfigs* LayerInfoV2::sRefreshRateConfigs = nullptr;
Ady Abraham0ccd79b2020-06-10 10:11:17 -070034bool LayerInfoV2::sTraceEnabled = false;
Ady Abrahamb1b9d412020-06-01 19:53:52 -070035
Ady Abrahama6b676e2020-05-27 14:29:09 -070036LayerInfoV2::LayerInfoV2(const std::string& name, nsecs_t highRefreshRatePeriod,
37 LayerHistory::LayerVoteType defaultVote)
38 : mName(name),
39 mHighRefreshRatePeriod(highRefreshRatePeriod),
Ady Abraham8a82ba62020-01-17 12:43:17 -080040 mDefaultVote(defaultVote),
Ady Abraham0ccd79b2020-06-10 10:11:17 -070041 mLayerVote({defaultVote, 0.0f}),
42 mRefreshRateHistory(name) {}
Ady Abraham8a82ba62020-01-17 12:43:17 -080043
Ady Abraham32efd542020-05-19 17:49:26 -070044void LayerInfoV2::setLastPresentTime(nsecs_t lastPresentTime, nsecs_t now,
Ady Abraham5def7332020-05-29 16:13:47 -070045 LayerUpdateType updateType, bool pendingConfigChange) {
Ady Abraham8a82ba62020-01-17 12:43:17 -080046 lastPresentTime = std::max(lastPresentTime, static_cast<nsecs_t>(0));
47
48 mLastUpdatedTime = std::max(lastPresentTime, now);
Ady Abraham5def7332020-05-29 16:13:47 -070049 switch (updateType) {
50 case LayerUpdateType::AnimationTX:
51 mLastAnimationTime = std::max(lastPresentTime, now);
52 break;
53 case LayerUpdateType::SetFrameRate:
54 case LayerUpdateType::Buffer:
55 FrameTimeData frameTime = {.presetTime = lastPresentTime,
56 .queueTime = mLastUpdatedTime,
57 .pendingConfigChange = pendingConfigChange};
58 mFrameTimes.push_back(frameTime);
59 if (mFrameTimes.size() > HISTORY_SIZE) {
60 mFrameTimes.pop_front();
61 }
62 break;
Ady Abraham8a82ba62020-01-17 12:43:17 -080063 }
64}
65
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000066bool LayerInfoV2::isFrameTimeValid(const FrameTimeData& frameTime) const {
67 return frameTime.queueTime >= std::chrono::duration_cast<std::chrono::nanoseconds>(
68 mFrameTimeValidSince.time_since_epoch())
69 .count();
70}
Ady Abraham1adbb722020-05-15 11:51:48 -070071
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000072bool LayerInfoV2::isFrequent(nsecs_t now) const {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000073 // If we know nothing about this layer we consider it as frequent as it might be the start
74 // of an animation.
Ady Abraham983e5682020-05-28 16:49:18 -070075 if (mFrameTimes.size() < FREQUENT_LAYER_WINDOW_SIZE) {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000076 return true;
77 }
78
79 // Find the first active frame
Ady Abraham983e5682020-05-28 16:49:18 -070080 auto it = mFrameTimes.begin();
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000081 for (; it != mFrameTimes.end(); ++it) {
82 if (it->queueTime >= getActiveLayerThreshold(now)) {
83 break;
84 }
85 }
86
87 const auto numFrames = std::distance(it, mFrameTimes.end());
88 if (numFrames < FREQUENT_LAYER_WINDOW_SIZE) {
89 return false;
90 }
91
92 // Layer is considered frequent if the average frame rate is higher than the threshold
93 const auto totalTime = mFrameTimes.back().queueTime - it->queueTime;
94 return (1e9f * (numFrames - 1)) / totalTime >= MIN_FPS_FOR_FREQUENT_LAYER;
Ady Abraham8a82ba62020-01-17 12:43:17 -080095}
96
Ady Abraham5def7332020-05-29 16:13:47 -070097bool LayerInfoV2::isAnimating(nsecs_t now) const {
98 return mLastAnimationTime >= getActiveLayerThreshold(now);
99}
100
Ady Abraham8a82ba62020-01-17 12:43:17 -0800101bool LayerInfoV2::hasEnoughDataForHeuristic() const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700102 // The layer had to publish at least HISTORY_SIZE or HISTORY_DURATION of updates
Ady Abrahama61edcb2020-01-30 18:32:03 -0800103 if (mFrameTimes.size() < 2) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700104 ALOGV("fewer than 2 frames recorded: %zu", mFrameTimes.size());
Ady Abrahama61edcb2020-01-30 18:32:03 -0800105 return false;
106 }
107
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000108 if (!isFrameTimeValid(mFrameTimes.front())) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700109 ALOGV("stale frames still captured");
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000110 return false;
111 }
112
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700113 const auto totalDuration = mFrameTimes.back().queueTime - mFrameTimes.front().queueTime;
114 if (mFrameTimes.size() < HISTORY_SIZE && totalDuration < HISTORY_DURATION.count()) {
115 ALOGV("not enough frames captured: %zu | %.2f seconds", mFrameTimes.size(),
116 totalDuration / 1e9f);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800117 return false;
118 }
119
120 return true;
121}
122
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700123std::optional<nsecs_t> LayerInfoV2::calculateAverageFrameTime() const {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800124 nsecs_t totalPresentTimeDeltas = 0;
Ady Abrahamc9664832020-05-12 14:16:56 -0700125 nsecs_t totalQueueTimeDeltas = 0;
Ady Abraham32efd542020-05-19 17:49:26 -0700126 bool missingPresentTime = false;
127 int numFrames = 0;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800128 for (auto it = mFrameTimes.begin(); it != mFrameTimes.end() - 1; ++it) {
Ady Abraham32efd542020-05-19 17:49:26 -0700129 // Ignore frames captured during a config change
130 if (it->pendingConfigChange || (it + 1)->pendingConfigChange) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700131 return std::nullopt;
Ady Abraham32efd542020-05-19 17:49:26 -0700132 }
133
Ady Abrahamc9664832020-05-12 14:16:56 -0700134 totalQueueTimeDeltas +=
135 std::max(((it + 1)->queueTime - it->queueTime), mHighRefreshRatePeriod);
Ady Abraham32efd542020-05-19 17:49:26 -0700136 numFrames++;
Ady Abrahamc9664832020-05-12 14:16:56 -0700137
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700138 if (!missingPresentTime && (it->presetTime == 0 || (it + 1)->presetTime == 0)) {
Ady Abrahamc9664832020-05-12 14:16:56 -0700139 missingPresentTime = true;
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700140 // If there are no presentation timestamps and we haven't calculated
141 // one in the past then we can't calculate the refresh rate
142 if (mLastRefreshRate.reported == 0) {
143 return std::nullopt;
144 }
Ady Abrahamc9664832020-05-12 14:16:56 -0700145 continue;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800146 }
147
148 totalPresentTimeDeltas +=
149 std::max(((it + 1)->presetTime - it->presetTime), mHighRefreshRatePeriod);
150 }
Ady Abrahamc9664832020-05-12 14:16:56 -0700151
Ady Abrahamc9664832020-05-12 14:16:56 -0700152 // Calculate the average frame time based on presentation timestamps. If those
153 // doesn't exist, we look at the time the buffer was queued only. We can do that only if
154 // we calculated a refresh rate based on presentation timestamps in the past. The reason
155 // we look at the queue time is to handle cases where hwui attaches presentation timestamps
156 // when implementing render ahead for specific refresh rates. When hwui no longer provides
157 // presentation timestamps we look at the queue time to see if the current refresh rate still
158 // matches the content.
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700159
Ady Abraham32efd542020-05-19 17:49:26 -0700160 const auto averageFrameTime =
Ady Abrahamc9664832020-05-12 14:16:56 -0700161 static_cast<float>(missingPresentTime ? totalQueueTimeDeltas : totalPresentTimeDeltas) /
Ady Abraham32efd542020-05-19 17:49:26 -0700162 numFrames;
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700163 return static_cast<nsecs_t>(averageFrameTime);
Ady Abraham32efd542020-05-19 17:49:26 -0700164}
Ady Abraham8a82ba62020-01-17 12:43:17 -0800165
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700166std::optional<float> LayerInfoV2::calculateRefreshRateIfPossible(nsecs_t now) {
Ady Abraham32efd542020-05-19 17:49:26 -0700167 static constexpr float MARGIN = 1.0f; // 1Hz
Ady Abraham32efd542020-05-19 17:49:26 -0700168 if (!hasEnoughDataForHeuristic()) {
169 ALOGV("Not enough data");
170 return std::nullopt;
171 }
172
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700173 const auto averageFrameTime = calculateAverageFrameTime();
174 if (averageFrameTime.has_value()) {
175 const auto refreshRate = 1e9f / *averageFrameTime;
176 const bool refreshRateConsistent = mRefreshRateHistory.add(refreshRate, now);
177 if (refreshRateConsistent) {
178 const auto knownRefreshRate =
179 sRefreshRateConfigs->findClosestKnownFrameRate(refreshRate);
Ady Abraham32efd542020-05-19 17:49:26 -0700180
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700181 // To avoid oscillation, use the last calculated refresh rate if it is
182 // close enough
183 if (std::abs(mLastRefreshRate.calculated - refreshRate) > MARGIN &&
184 mLastRefreshRate.reported != knownRefreshRate) {
185 mLastRefreshRate.calculated = refreshRate;
186 mLastRefreshRate.reported = knownRefreshRate;
187 }
188
189 ALOGV("%s %.2fHz rounded to nearest known frame rate %.2fHz", mName.c_str(),
190 refreshRate, mLastRefreshRate.reported);
191 } else {
192 ALOGV("%s Not stable (%.2fHz) returning last known frame rate %.2fHz", mName.c_str(),
193 refreshRate, mLastRefreshRate.reported);
194 }
Ady Abraham32efd542020-05-19 17:49:26 -0700195 }
196
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700197 return mLastRefreshRate.reported == 0 ? std::nullopt
198 : std::make_optional(mLastRefreshRate.reported);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800199}
200
Marin Shalamanov46084422020-10-13 12:33:42 +0200201LayerInfoV2::LayerVote LayerInfoV2::getRefreshRateVote(nsecs_t now) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800202 if (mLayerVote.type != LayerHistory::LayerVoteType::Heuristic) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700203 ALOGV("%s voted %d ", mName.c_str(), static_cast<int>(mLayerVote.type));
Marin Shalamanov46084422020-10-13 12:33:42 +0200204 return mLayerVote;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800205 }
206
Ady Abraham5def7332020-05-29 16:13:47 -0700207 if (isAnimating(now)) {
208 ALOGV("%s is animating", mName.c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700209 mLastRefreshRate.animatingOrInfrequent = true;
Ady Abraham5def7332020-05-29 16:13:47 -0700210 return {LayerHistory::LayerVoteType::Max, 0};
211 }
212
Ady Abraham8a82ba62020-01-17 12:43:17 -0800213 if (!isFrequent(now)) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700214 ALOGV("%s is infrequent", mName.c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700215 mLastRefreshRate.animatingOrInfrequent = true;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800216 return {LayerHistory::LayerVoteType::Min, 0};
217 }
218
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700219 // If the layer was previously tagged as animating or infrequent, we clear
220 // the history as it is likely the layer just changed its behavior
221 // and we should not look at stale data
222 if (mLastRefreshRate.animatingOrInfrequent) {
223 clearHistory(now);
224 }
225
226 auto refreshRate = calculateRefreshRateIfPossible(now);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800227 if (refreshRate.has_value()) {
Ady Abrahama6b676e2020-05-27 14:29:09 -0700228 ALOGV("%s calculated refresh rate: %.2f", mName.c_str(), refreshRate.value());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800229 return {LayerHistory::LayerVoteType::Heuristic, refreshRate.value()};
230 }
231
Ady Abrahama6b676e2020-05-27 14:29:09 -0700232 ALOGV("%s Max (can't resolve refresh rate)", mName.c_str());
Ady Abraham8a82ba62020-01-17 12:43:17 -0800233 return {LayerHistory::LayerVoteType::Max, 0};
234}
235
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700236const char* LayerInfoV2::getTraceTag(android::scheduler::LayerHistory::LayerVoteType type) const {
237 if (mTraceTags.count(type) == 0) {
238 const auto tag = "LFPS " + mName + " " + RefreshRateConfigs::layerVoteTypeString(type);
239 mTraceTags.emplace(type, tag);
240 }
241
242 return mTraceTags.at(type).c_str();
243}
244
245LayerInfoV2::RefreshRateHistory::HeuristicTraceTagData
246LayerInfoV2::RefreshRateHistory::makeHeuristicTraceTagData() const {
247 const std::string prefix = "LFPS ";
248 const std::string suffix = "Heuristic ";
249 return {.min = prefix + mName + suffix + "min",
250 .max = prefix + mName + suffix + "max",
251 .consistent = prefix + mName + suffix + "consistent",
252 .average = prefix + mName + suffix + "average"};
253}
254
255void LayerInfoV2::RefreshRateHistory::clear() {
256 mRefreshRates.clear();
257}
258
259bool LayerInfoV2::RefreshRateHistory::add(float refreshRate, nsecs_t now) {
260 mRefreshRates.push_back({refreshRate, now});
261 while (mRefreshRates.size() >= HISTORY_SIZE ||
262 now - mRefreshRates.front().timestamp > HISTORY_DURATION.count()) {
263 mRefreshRates.pop_front();
264 }
265
266 if (CC_UNLIKELY(sTraceEnabled)) {
267 if (!mHeuristicTraceTagData.has_value()) {
268 mHeuristicTraceTagData = makeHeuristicTraceTagData();
269 }
270
271 ATRACE_INT(mHeuristicTraceTagData->average.c_str(), static_cast<int>(refreshRate));
272 }
273
274 return isConsistent();
275}
276
277bool LayerInfoV2::RefreshRateHistory::isConsistent() const {
278 if (mRefreshRates.empty()) return true;
279
280 const auto max = std::max_element(mRefreshRates.begin(), mRefreshRates.end());
281 const auto min = std::min_element(mRefreshRates.begin(), mRefreshRates.end());
282 const auto consistent = max->refreshRate - min->refreshRate <= MARGIN_FPS;
283
284 if (CC_UNLIKELY(sTraceEnabled)) {
285 if (!mHeuristicTraceTagData.has_value()) {
286 mHeuristicTraceTagData = makeHeuristicTraceTagData();
287 }
288
289 ATRACE_INT(mHeuristicTraceTagData->max.c_str(), static_cast<int>(max->refreshRate));
290 ATRACE_INT(mHeuristicTraceTagData->min.c_str(), static_cast<int>(min->refreshRate));
291 ATRACE_INT(mHeuristicTraceTagData->consistent.c_str(), consistent);
292 }
293
294 return consistent;
295}
296
Ady Abraham8a82ba62020-01-17 12:43:17 -0800297} // namespace android::scheduler