blob: 1bc4ac2f116ea9b5e1f71a71bb48d1594acc6982 [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
Rachel Leece6e0042023-06-27 11:22:54 -070029#include <android/native_window.h>
Ady Abraham0ccd79b2020-06-10 10:11:17 -070030#include <cutils/compiler.h>
31#include <cutils/trace.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070032#include <ftl/enum.h>
Ady Abraham73c3df52023-01-12 18:09:31 -080033#include <gui/TraceUtils.h>
Rachel Leece6e0042023-06-27 11:22:54 -070034#include <system/window.h>
Ady Abraham0ccd79b2020-06-10 10:11:17 -070035
Ady Abraham8a82ba62020-01-17 12:43:17 -080036#undef LOG_TAG
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010037#define LOG_TAG "LayerInfo"
Ady Abraham8a82ba62020-01-17 12:43:17 -080038
39namespace android::scheduler {
40
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010041bool LayerInfo::sTraceEnabled = false;
Ady Abrahamb1b9d412020-06-01 19:53:52 -070042
Ady Abrahambdda8f02021-04-01 16:06:11 -070043LayerInfo::LayerInfo(const std::string& name, uid_t ownerUid,
44 LayerHistory::LayerVoteType defaultVote)
Ady Abrahama6b676e2020-05-27 14:29:09 -070045 : mName(name),
Ady Abrahambdda8f02021-04-01 16:06:11 -070046 mOwnerUid(ownerUid),
Ady Abraham8a82ba62020-01-17 12:43:17 -080047 mDefaultVote(defaultVote),
Dominik Laskowski6eab42d2021-09-13 14:34:13 -070048 mLayerVote({defaultVote, Fps()}),
Vishnu Nairef68d6d2023-02-28 06:18:27 +000049 mLayerProps(std::make_unique<LayerProps>()),
50 mRefreshRateHistory(name) {
51 ;
52}
Ady Abraham8a82ba62020-01-17 12:43:17 -080053
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010054void LayerInfo::setLastPresentTime(nsecs_t lastPresentTime, nsecs_t now, LayerUpdateType updateType,
Vishnu Nairef68d6d2023-02-28 06:18:27 +000055 bool pendingModeChange, const LayerProps& props) {
Ady Abraham8a82ba62020-01-17 12:43:17 -080056 lastPresentTime = std::max(lastPresentTime, static_cast<nsecs_t>(0));
57
58 mLastUpdatedTime = std::max(lastPresentTime, now);
Vishnu Nairef68d6d2023-02-28 06:18:27 +000059 *mLayerProps = props;
Ady Abraham5def7332020-05-29 16:13:47 -070060 switch (updateType) {
61 case LayerUpdateType::AnimationTX:
62 mLastAnimationTime = std::max(lastPresentTime, now);
63 break;
64 case LayerUpdateType::SetFrameRate:
Ady Abrahamae93c352023-12-20 23:38:55 +000065 if (FlagManager::getInstance().vrr_config()) {
66 break;
67 }
68 FALLTHROUGH_INTENDED;
Ady Abraham5def7332020-05-29 16:13:47 -070069 case LayerUpdateType::Buffer:
Marin Shalamanov2045d5b2020-12-28 18:11:41 +010070 FrameTimeData frameTime = {.presentTime = lastPresentTime,
Ady Abraham5def7332020-05-29 16:13:47 -070071 .queueTime = mLastUpdatedTime,
Arthur Hungc70bee22023-06-02 01:35:52 +000072 .pendingModeChange = pendingModeChange,
73 .isSmallDirty = props.isSmallDirty};
Ady Abraham5def7332020-05-29 16:13:47 -070074 mFrameTimes.push_back(frameTime);
75 if (mFrameTimes.size() > HISTORY_SIZE) {
76 mFrameTimes.pop_front();
77 }
78 break;
Ady Abraham8a82ba62020-01-17 12:43:17 -080079 }
80}
81
Vishnu Nair41376b62023-11-08 05:08:58 -080082void LayerInfo::setProperties(const android::scheduler::LayerProps& properties) {
83 *mLayerProps = properties;
84}
85
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010086bool LayerInfo::isFrameTimeValid(const FrameTimeData& frameTime) const {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000087 return frameTime.queueTime >= std::chrono::duration_cast<std::chrono::nanoseconds>(
88 mFrameTimeValidSince.time_since_epoch())
89 .count();
90}
Ady Abraham1adbb722020-05-15 11:51:48 -070091
ramindani63db24e2023-04-03 10:56:05 -070092LayerInfo::Frequent LayerInfo::isFrequent(nsecs_t now) const {
Ady Abraham86ac5c52023-01-11 15:24:03 -080093 // If we know nothing about this layer (e.g. after touch event),
94 // we consider it as frequent as it might be the start of an animation.
Marin Shalamanov2045d5b2020-12-28 18:11:41 +010095 if (mFrameTimes.size() < kFrequentLayerWindowSize) {
ramindani63db24e2023-04-03 10:56:05 -070096 return {/* isFrequent */ true, /* clearHistory */ false, /* isConclusive */ true};
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000097 }
Ady Abraham86ac5c52023-01-11 15:24:03 -080098
99 // Non-active layers are also infrequent
100 if (mLastUpdatedTime < getActiveLayerThreshold(now)) {
ramindani63db24e2023-04-03 10:56:05 -0700101 return {/* isFrequent */ false, /* clearHistory */ false, /* isConclusive */ true};
Ady Abraham86ac5c52023-01-11 15:24:03 -0800102 }
103
104 // We check whether we can classify this layer as frequent or infrequent:
105 // - frequent: a layer posted kFrequentLayerWindowSize within
106 // kMaxPeriodForFrequentLayerNs of each other.
107 // - infrequent: a layer posted kFrequentLayerWindowSize with longer
108 // gaps than kFrequentLayerWindowSize.
109 // If we can't determine the layer classification yet, we return the last
110 // classification.
111 bool isFrequent = true;
112 bool isInfrequent = true;
Arthur Hungc70bee22023-06-02 01:35:52 +0000113 int32_t smallDirtyCount = 0;
Ady Abraham86ac5c52023-01-11 15:24:03 -0800114 const auto n = mFrameTimes.size() - 1;
115 for (size_t i = 0; i < kFrequentLayerWindowSize - 1; i++) {
116 if (mFrameTimes[n - i].queueTime - mFrameTimes[n - i - 1].queueTime <
117 kMaxPeriodForFrequentLayerNs.count()) {
118 isInfrequent = false;
Arthur Hungc70bee22023-06-02 01:35:52 +0000119 if (mFrameTimes[n - i].presentTime == 0 && mFrameTimes[n - i].isSmallDirty) {
120 smallDirtyCount++;
121 }
Ady Abraham86ac5c52023-01-11 15:24:03 -0800122 } else {
123 isFrequent = false;
124 }
125 }
126
Arthur Hung8144e022023-09-08 10:26:23 +0000127 // Vote the small dirty when a layer contains at least HISTORY_SIZE of small dirty updates.
128 bool isSmallDirty = false;
129 if (smallDirtyCount >= kNumSmallDirtyThreshold) {
130 if (mLastSmallDirtyCount >= HISTORY_SIZE) {
131 isSmallDirty = true;
132 } else {
133 mLastSmallDirtyCount++;
134 }
135 } else {
136 mLastSmallDirtyCount = 0;
137 }
138
Ady Abraham86ac5c52023-01-11 15:24:03 -0800139 if (isFrequent || isInfrequent) {
ramindani63db24e2023-04-03 10:56:05 -0700140 // If the layer was previously inconclusive, we clear
141 // the history as indeterminate layers changed to frequent,
142 // and we should not look at the stale data.
Arthur Hungc70bee22023-06-02 01:35:52 +0000143 return {isFrequent, isFrequent && !mIsFrequencyConclusive, /* isConclusive */ true,
Arthur Hung8144e022023-09-08 10:26:23 +0000144 isSmallDirty};
Ady Abraham86ac5c52023-01-11 15:24:03 -0800145 }
146
147 // If we can't determine whether the layer is frequent or not, we return
ramindani63db24e2023-04-03 10:56:05 -0700148 // the last known classification and mark the layer frequency as inconclusive.
149 isFrequent = !mLastRefreshRate.infrequent;
150
151 // If the layer was previously tagged as animating, we clear
152 // the history as it is likely the layer just changed its behavior,
153 // and we should not look at stale data.
154 return {isFrequent, isFrequent && mLastRefreshRate.animating, /* isConclusive */ false};
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400155}
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000156
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400157Fps LayerInfo::getFps(nsecs_t now) const {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000158 // Find the first active frame
Ady Abraham983e5682020-05-28 16:49:18 -0700159 auto it = mFrameTimes.begin();
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000160 for (; it != mFrameTimes.end(); ++it) {
161 if (it->queueTime >= getActiveLayerThreshold(now)) {
162 break;
163 }
164 }
165
166 const auto numFrames = std::distance(it, mFrameTimes.end());
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100167 if (numFrames < kFrequentLayerWindowSize) {
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400168 return Fps();
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000169 }
170
171 // Layer is considered frequent if the average frame rate is higher than the threshold
172 const auto totalTime = mFrameTimes.back().queueTime - it->queueTime;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400173 return Fps::fromPeriodNsecs(totalTime / (numFrames - 1));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800174}
175
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100176bool LayerInfo::isAnimating(nsecs_t now) const {
Ady Abraham5def7332020-05-29 16:13:47 -0700177 return mLastAnimationTime >= getActiveLayerThreshold(now);
178}
179
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100180bool LayerInfo::hasEnoughDataForHeuristic() const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700181 // The layer had to publish at least HISTORY_SIZE or HISTORY_DURATION of updates
Ady Abrahama61edcb2020-01-30 18:32:03 -0800182 if (mFrameTimes.size() < 2) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700183 ALOGV("fewer than 2 frames recorded: %zu", mFrameTimes.size());
Ady Abrahama61edcb2020-01-30 18:32:03 -0800184 return false;
185 }
186
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000187 if (!isFrameTimeValid(mFrameTimes.front())) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700188 ALOGV("stale frames still captured");
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000189 return false;
190 }
191
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700192 const auto totalDuration = mFrameTimes.back().queueTime - mFrameTimes.front().queueTime;
193 if (mFrameTimes.size() < HISTORY_SIZE && totalDuration < HISTORY_DURATION.count()) {
194 ALOGV("not enough frames captured: %zu | %.2f seconds", mFrameTimes.size(),
195 totalDuration / 1e9f);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800196 return false;
197 }
198
199 return true;
200}
201
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100202std::optional<nsecs_t> LayerInfo::calculateAverageFrameTime() const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100203 // Ignore frames captured during a mode change
204 const bool isDuringModeChange =
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100205 std::any_of(mFrameTimes.begin(), mFrameTimes.end(),
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100206 [](const auto& frame) { return frame.pendingModeChange; });
207 if (isDuringModeChange) {
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100208 return std::nullopt;
209 }
Ady Abraham32efd542020-05-19 17:49:26 -0700210
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100211 const bool isMissingPresentTime =
212 std::any_of(mFrameTimes.begin(), mFrameTimes.end(),
213 [](auto frame) { return frame.presentTime == 0; });
214 if (isMissingPresentTime && !mLastRefreshRate.reported.isValid()) {
215 // If there are no presentation timestamps and we haven't calculated
216 // one in the past then we can't calculate the refresh rate
217 return std::nullopt;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800218 }
Ady Abrahamc9664832020-05-12 14:16:56 -0700219
Ady Abrahamc9664832020-05-12 14:16:56 -0700220 // Calculate the average frame time based on presentation timestamps. If those
221 // doesn't exist, we look at the time the buffer was queued only. We can do that only if
222 // we calculated a refresh rate based on presentation timestamps in the past. The reason
223 // we look at the queue time is to handle cases where hwui attaches presentation timestamps
224 // when implementing render ahead for specific refresh rates. When hwui no longer provides
225 // presentation timestamps we look at the queue time to see if the current refresh rate still
226 // matches the content.
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700227
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100228 auto getFrameTime = isMissingPresentTime ? [](FrameTimeData data) { return data.queueTime; }
229 : [](FrameTimeData data) { return data.presentTime; };
230
231 nsecs_t totalDeltas = 0;
232 int numDeltas = 0;
Arthur Hungc70bee22023-06-02 01:35:52 +0000233 int32_t smallDirtyCount = 0;
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100234 auto prevFrame = mFrameTimes.begin();
235 for (auto it = mFrameTimes.begin() + 1; it != mFrameTimes.end(); ++it) {
236 const auto currDelta = getFrameTime(*it) - getFrameTime(*prevFrame);
237 if (currDelta < kMinPeriodBetweenFrames) {
238 // Skip this frame, but count the delta into the next frame
239 continue;
240 }
241
Arthur Hungc70bee22023-06-02 01:35:52 +0000242 // If this is a small area update, we don't want to consider it for calculating the average
243 // frame time. Instead, we let the bigger frame updates to drive the calculation.
244 if (it->isSmallDirty && currDelta < kMinPeriodBetweenSmallDirtyFrames) {
245 smallDirtyCount++;
246 continue;
247 }
248
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100249 prevFrame = it;
250
251 if (currDelta > kMaxPeriodBetweenFrames) {
252 // Skip this frame and the current delta.
253 continue;
254 }
255
256 totalDeltas += currDelta;
257 numDeltas++;
258 }
259
Arthur Hungc70bee22023-06-02 01:35:52 +0000260 if (smallDirtyCount > 0) {
261 ATRACE_FORMAT_INSTANT("small dirty = %" PRIu32, smallDirtyCount);
262 }
263
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100264 if (numDeltas == 0) {
265 return std::nullopt;
266 }
267
268 const auto averageFrameTime = static_cast<double>(totalDeltas) / static_cast<double>(numDeltas);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700269 return static_cast<nsecs_t>(averageFrameTime);
Ady Abraham32efd542020-05-19 17:49:26 -0700270}
Ady Abraham8a82ba62020-01-17 12:43:17 -0800271
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400272std::optional<Fps> LayerInfo::calculateRefreshRateIfPossible(const RefreshRateSelector& selector,
273 nsecs_t now) {
Ady Abraham73c3df52023-01-12 18:09:31 -0800274 ATRACE_CALL();
Ady Abraham32efd542020-05-19 17:49:26 -0700275 static constexpr float MARGIN = 1.0f; // 1Hz
Ady Abraham32efd542020-05-19 17:49:26 -0700276 if (!hasEnoughDataForHeuristic()) {
277 ALOGV("Not enough data");
278 return std::nullopt;
279 }
280
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700281 if (const auto averageFrameTime = calculateAverageFrameTime()) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100282 const auto refreshRate = Fps::fromPeriodNsecs(*averageFrameTime);
Jerry Chang04eb8e02023-11-15 08:06:07 +0000283 const auto closestKnownRefreshRate = mRefreshRateHistory.add(refreshRate, now, selector);
284 if (closestKnownRefreshRate.isValid()) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700285 using fps_approx_ops::operator!=;
286
287 // To avoid oscillation, use the last calculated refresh rate if it is close enough.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100288 if (std::abs(mLastRefreshRate.calculated.getValue() - refreshRate.getValue()) >
289 MARGIN &&
Jerry Chang04eb8e02023-11-15 08:06:07 +0000290 mLastRefreshRate.reported != closestKnownRefreshRate) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700291 mLastRefreshRate.calculated = refreshRate;
Jerry Chang04eb8e02023-11-15 08:06:07 +0000292 mLastRefreshRate.reported = closestKnownRefreshRate;
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700293 }
294
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100295 ALOGV("%s %s rounded to nearest known frame rate %s", mName.c_str(),
296 to_string(refreshRate).c_str(), to_string(mLastRefreshRate.reported).c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700297 } else {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100298 ALOGV("%s Not stable (%s) returning last known frame rate %s", mName.c_str(),
299 to_string(refreshRate).c_str(), to_string(mLastRefreshRate.reported).c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700300 }
Ady Abraham32efd542020-05-19 17:49:26 -0700301 }
302
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100303 return mLastRefreshRate.reported.isValid() ? std::make_optional(mLastRefreshRate.reported)
304 : std::nullopt;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800305}
306
Rachel Leece6e0042023-06-27 11:22:54 -0700307LayerInfo::RefreshRateVotes LayerInfo::getRefreshRateVote(const RefreshRateSelector& selector,
308 nsecs_t now) {
Ady Abraham73c3df52023-01-12 18:09:31 -0800309 ATRACE_CALL();
Rachel Leece6e0042023-06-27 11:22:54 -0700310 LayerInfo::RefreshRateVotes votes;
311
Ady Abraham8a82ba62020-01-17 12:43:17 -0800312 if (mLayerVote.type != LayerHistory::LayerVoteType::Heuristic) {
Rachel Leece6e0042023-06-27 11:22:54 -0700313 if (mLayerVote.category != FrameRateCategory::Default) {
Rachel Lee414f4082023-10-23 14:48:44 -0700314 const auto voteType = mLayerVote.type == LayerHistory::LayerVoteType::NoVote
315 ? LayerHistory::LayerVoteType::NoVote
316 : LayerHistory::LayerVoteType::ExplicitCategory;
317 ATRACE_FORMAT_INSTANT("Vote %s (category=%s)", ftl::enum_string(voteType).c_str(),
Rachel Leec0e40bc2023-09-12 13:41:15 -0700318 ftl::enum_string(mLayerVote.category).c_str());
Rachel Lee414f4082023-10-23 14:48:44 -0700319 ALOGV("%s voted %s with category: %s", mName.c_str(),
320 ftl::enum_string(voteType).c_str(),
321 ftl::enum_string(mLayerVote.category).c_str());
322 votes.push_back({voteType, Fps(), Seamlessness::Default, mLayerVote.category,
Rachel Lee67afbea2023-09-28 15:35:07 -0700323 mLayerVote.categorySmoothSwitchOnly});
Rachel Leece6e0042023-06-27 11:22:54 -0700324 }
325
326 if (mLayerVote.fps.isValid() ||
327 mLayerVote.type != LayerHistory::LayerVoteType::ExplicitDefault) {
Rachel Leec0e40bc2023-09-12 13:41:15 -0700328 ATRACE_FORMAT_INSTANT("Vote %s", ftl::enum_string(mLayerVote.type).c_str());
Rachel Lee414f4082023-10-23 14:48:44 -0700329 ALOGV("%s voted %d", mName.c_str(), static_cast<int>(mLayerVote.type));
Ady Abraham0dd4bd42024-02-06 18:36:49 -0800330 votes.push_back({mLayerVote.type, mLayerVote.fps, mLayerVote.seamlessness,
331 FrameRateCategory::Default, mLayerVote.categorySmoothSwitchOnly});
Rachel Leece6e0042023-06-27 11:22:54 -0700332 }
333
334 return votes;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800335 }
336
Ady Abraham5def7332020-05-29 16:13:47 -0700337 if (isAnimating(now)) {
Ady Abraham73c3df52023-01-12 18:09:31 -0800338 ATRACE_FORMAT_INSTANT("animating");
Ady Abraham5def7332020-05-29 16:13:47 -0700339 ALOGV("%s is animating", mName.c_str());
Ady Abraham86ac5c52023-01-11 15:24:03 -0800340 mLastRefreshRate.animating = true;
Rachel Leece6e0042023-06-27 11:22:54 -0700341 votes.push_back({LayerHistory::LayerVoteType::Max, Fps()});
342 return votes;
Ady Abraham5def7332020-05-29 16:13:47 -0700343 }
344
Alec Mouri89f5d4e2023-10-20 17:12:49 +0000345 // Vote for max refresh rate whenever we're front-buffered.
346 if (FlagManager::getInstance().vrr_config() && isFrontBuffered()) {
347 ATRACE_FORMAT_INSTANT("front buffered");
348 ALOGV("%s is front-buffered", mName.c_str());
349 votes.push_back({LayerHistory::LayerVoteType::Max, Fps()});
350 return votes;
351 }
352
ramindani63db24e2023-04-03 10:56:05 -0700353 const LayerInfo::Frequent frequent = isFrequent(now);
354 mIsFrequencyConclusive = frequent.isConclusive;
355 if (!frequent.isFrequent) {
Ady Abraham73c3df52023-01-12 18:09:31 -0800356 ATRACE_FORMAT_INSTANT("infrequent");
Ady Abrahama6b676e2020-05-27 14:29:09 -0700357 ALOGV("%s is infrequent", mName.c_str());
Ady Abraham86ac5c52023-01-11 15:24:03 -0800358 mLastRefreshRate.infrequent = true;
Arthur Hung8144e022023-09-08 10:26:23 +0000359 mLastSmallDirtyCount = 0;
ramindani63db24e2023-04-03 10:56:05 -0700360 // Infrequent layers vote for minimal refresh rate for
Marin Shalamanov29e25402021-04-07 21:09:58 +0200361 // battery saving purposes and also to prevent b/135718869.
Rachel Leece6e0042023-06-27 11:22:54 -0700362 votes.push_back({LayerHistory::LayerVoteType::Min, Fps()});
363 return votes;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800364 }
365
ramindani63db24e2023-04-03 10:56:05 -0700366 if (frequent.clearHistory) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700367 clearHistory(now);
368 }
369
Arthur Hung8144e022023-09-08 10:26:23 +0000370 // Return no vote if the recent frames are small dirty.
Arthur Hungc70bee22023-06-02 01:35:52 +0000371 if (frequent.isSmallDirty && !mLastRefreshRate.reported.isValid()) {
372 ATRACE_FORMAT_INSTANT("NoVote (small dirty)");
373 ALOGV("%s is small dirty", mName.c_str());
374 votes.push_back({LayerHistory::LayerVoteType::NoVote, Fps()});
375 return votes;
376 }
377
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400378 auto refreshRate = calculateRefreshRateIfPossible(selector, now);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800379 if (refreshRate.has_value()) {
Rachel Leec0e40bc2023-09-12 13:41:15 -0700380 ATRACE_FORMAT_INSTANT("calculated (%s)", to_string(*refreshRate).c_str());
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100381 ALOGV("%s calculated refresh rate: %s", mName.c_str(), to_string(*refreshRate).c_str());
Rachel Leece6e0042023-06-27 11:22:54 -0700382 votes.push_back({LayerHistory::LayerVoteType::Heuristic, refreshRate.value()});
383 return votes;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800384 }
385
Rachel Leec0e40bc2023-09-12 13:41:15 -0700386 ATRACE_FORMAT_INSTANT("Max (can't resolve refresh rate)");
Ady Abrahama6b676e2020-05-27 14:29:09 -0700387 ALOGV("%s Max (can't resolve refresh rate)", mName.c_str());
Rachel Leece6e0042023-06-27 11:22:54 -0700388 votes.push_back({LayerHistory::LayerVoteType::Max, Fps()});
389 return votes;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800390}
391
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700392const char* LayerInfo::getTraceTag(LayerHistory::LayerVoteType type) const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700393 if (mTraceTags.count(type) == 0) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700394 auto tag = "LFPS " + mName + " " + ftl::enum_string(type);
395 mTraceTags.emplace(type, std::move(tag));
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700396 }
397
398 return mTraceTags.at(type).c_str();
399}
400
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000401LayerInfo::FrameRate LayerInfo::getSetFrameRateVote() const {
402 return mLayerProps->setFrameRateVote;
403}
404
405bool LayerInfo::isVisible() const {
406 return mLayerProps->visible;
407}
408
409int32_t LayerInfo::getFrameRateSelectionPriority() const {
410 return mLayerProps->frameRateSelectionPriority;
411}
412
Alec Mouri89f5d4e2023-10-20 17:12:49 +0000413bool LayerInfo::isFrontBuffered() const {
414 return mLayerProps->isFrontBuffered;
415}
416
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000417FloatRect LayerInfo::getBounds() const {
418 return mLayerProps->bounds;
419}
420
421ui::Transform LayerInfo::getTransform() const {
422 return mLayerProps->transform;
423}
424
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100425LayerInfo::RefreshRateHistory::HeuristicTraceTagData
426LayerInfo::RefreshRateHistory::makeHeuristicTraceTagData() const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700427 const std::string prefix = "LFPS ";
428 const std::string suffix = "Heuristic ";
429 return {.min = prefix + mName + suffix + "min",
430 .max = prefix + mName + suffix + "max",
431 .consistent = prefix + mName + suffix + "consistent",
432 .average = prefix + mName + suffix + "average"};
433}
434
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100435void LayerInfo::RefreshRateHistory::clear() {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700436 mRefreshRates.clear();
437}
438
Jerry Chang04eb8e02023-11-15 08:06:07 +0000439Fps LayerInfo::RefreshRateHistory::add(Fps refreshRate, nsecs_t now,
440 const RefreshRateSelector& selector) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700441 mRefreshRates.push_back({refreshRate, now});
442 while (mRefreshRates.size() >= HISTORY_SIZE ||
443 now - mRefreshRates.front().timestamp > HISTORY_DURATION.count()) {
444 mRefreshRates.pop_front();
445 }
446
447 if (CC_UNLIKELY(sTraceEnabled)) {
448 if (!mHeuristicTraceTagData.has_value()) {
449 mHeuristicTraceTagData = makeHeuristicTraceTagData();
450 }
451
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100452 ATRACE_INT(mHeuristicTraceTagData->average.c_str(), refreshRate.getIntValue());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700453 }
454
Jerry Chang04eb8e02023-11-15 08:06:07 +0000455 return selectRefreshRate(selector);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700456}
457
Jerry Chang04eb8e02023-11-15 08:06:07 +0000458Fps LayerInfo::RefreshRateHistory::selectRefreshRate(const RefreshRateSelector& selector) const {
459 if (mRefreshRates.empty()) return Fps();
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700460
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700461 const auto [min, max] =
462 std::minmax_element(mRefreshRates.begin(), mRefreshRates.end(),
463 [](const auto& lhs, const auto& rhs) {
464 return isStrictlyLess(lhs.refreshRate, rhs.refreshRate);
465 });
466
Jerry Chang04eb8e02023-11-15 08:06:07 +0000467 const auto maxClosestRate = selector.findClosestKnownFrameRate(max->refreshRate);
468 const bool consistent = [&](Fps maxFps, Fps minFps) {
469 if (FlagManager::getInstance().use_known_refresh_rate_for_fps_consistency()) {
470 if (maxFps.getValue() - minFps.getValue() <
471 MARGIN_CONSISTENT_FPS_FOR_CLOSEST_REFRESH_RATE) {
472 const auto minClosestRate = selector.findClosestKnownFrameRate(minFps);
473 using fps_approx_ops::operator==;
474 return maxClosestRate == minClosestRate;
475 }
476 return false;
477 }
478 return maxFps.getValue() - minFps.getValue() < MARGIN_CONSISTENT_FPS;
479 }(max->refreshRate, min->refreshRate);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700480
481 if (CC_UNLIKELY(sTraceEnabled)) {
482 if (!mHeuristicTraceTagData.has_value()) {
483 mHeuristicTraceTagData = makeHeuristicTraceTagData();
484 }
485
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100486 ATRACE_INT(mHeuristicTraceTagData->max.c_str(), max->refreshRate.getIntValue());
487 ATRACE_INT(mHeuristicTraceTagData->min.c_str(), min->refreshRate.getIntValue());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700488 ATRACE_INT(mHeuristicTraceTagData->consistent.c_str(), consistent);
489 }
490
Jerry Chang04eb8e02023-11-15 08:06:07 +0000491 return consistent ? maxClosestRate : Fps();
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700492}
493
Vishnu Nair3fbe3262023-09-29 17:07:00 -0700494FrameRateCompatibility LayerInfo::FrameRate::convertCompatibility(int8_t compatibility) {
Rachel Leece6e0042023-06-27 11:22:54 -0700495 switch (compatibility) {
496 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
497 return FrameRateCompatibility::Default;
498 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
499 return FrameRateCompatibility::ExactOrMultiple;
500 case ANATIVEWINDOW_FRAME_RATE_EXACT:
501 return FrameRateCompatibility::Exact;
502 case ANATIVEWINDOW_FRAME_RATE_MIN:
503 return FrameRateCompatibility::Min;
Rachel Leee5514a72023-10-25 16:20:29 -0700504 case ANATIVEWINDOW_FRAME_RATE_GTE:
505 return FrameRateCompatibility::Gte;
Rachel Leece6e0042023-06-27 11:22:54 -0700506 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
507 return FrameRateCompatibility::NoVote;
508 default:
509 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
510 return FrameRateCompatibility::Default;
511 }
512}
513
514Seamlessness LayerInfo::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
515 switch (strategy) {
516 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
517 return Seamlessness::OnlySeamless;
518 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
519 return Seamlessness::SeamedAndSeamless;
520 default:
521 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
522 return Seamlessness::Default;
523 }
524}
525
526FrameRateCategory LayerInfo::FrameRate::convertCategory(int8_t category) {
527 switch (category) {
528 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_DEFAULT:
529 return FrameRateCategory::Default;
530 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_NO_PREFERENCE:
531 return FrameRateCategory::NoPreference;
532 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_LOW:
533 return FrameRateCategory::Low;
534 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_NORMAL:
535 return FrameRateCategory::Normal;
Rachel Lee9580ff12023-12-26 17:33:41 -0800536 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_HIGH_HINT:
537 return FrameRateCategory::HighHint;
Rachel Leece6e0042023-06-27 11:22:54 -0700538 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_HIGH:
539 return FrameRateCategory::High;
540 default:
541 LOG_ALWAYS_FATAL("Invalid frame rate category value %d", category);
542 return FrameRateCategory::Default;
543 }
544}
545
Rachel Lee58cc90d2023-09-05 18:50:20 -0700546LayerInfo::FrameRateSelectionStrategy LayerInfo::convertFrameRateSelectionStrategy(
547 int8_t strategy) {
548 switch (strategy) {
Rachel Lee70f7b692023-11-22 11:24:02 -0800549 case ANATIVEWINDOW_FRAME_RATE_SELECTION_STRATEGY_PROPAGATE:
550 return FrameRateSelectionStrategy::Propagate;
Rachel Lee58cc90d2023-09-05 18:50:20 -0700551 case ANATIVEWINDOW_FRAME_RATE_SELECTION_STRATEGY_OVERRIDE_CHILDREN:
552 return FrameRateSelectionStrategy::OverrideChildren;
Rachel Lee70f7b692023-11-22 11:24:02 -0800553 case ANATIVEWINDOW_FRAME_RATE_SELECTION_STRATEGY_SELF:
554 return FrameRateSelectionStrategy::Self;
Rachel Lee58cc90d2023-09-05 18:50:20 -0700555 default:
556 LOG_ALWAYS_FATAL("Invalid frame rate selection strategy value %d", strategy);
557 return FrameRateSelectionStrategy::Self;
558 }
559}
560
Rachel Leece6e0042023-06-27 11:22:54 -0700561bool LayerInfo::FrameRate::isNoVote() const {
Rachel Leed0694bc2023-09-12 14:57:58 -0700562 return vote.type == FrameRateCompatibility::NoVote;
Rachel Leece6e0042023-06-27 11:22:54 -0700563}
564
565bool LayerInfo::FrameRate::isValid() const {
566 return isNoVote() || vote.rate.isValid() || category != FrameRateCategory::Default;
567}
568
Rachel Lee45681982024-03-14 18:40:15 -0700569bool LayerInfo::FrameRate::isVoteValidForMrr(bool isVrrDevice) const {
570 if (isVrrDevice || FlagManager::getInstance().frame_rate_category_mrr()) {
571 return true;
572 }
573
574 if (category == FrameRateCategory::Default && vote.type != FrameRateCompatibility::Gte) {
575 return true;
576 }
577
578 return false;
579}
580
Rachel Leece6e0042023-06-27 11:22:54 -0700581std::ostream& operator<<(std::ostream& stream, const LayerInfo::FrameRate& rate) {
582 return stream << "{rate=" << rate.vote.rate << " type=" << ftl::enum_string(rate.vote.type)
583 << " seamlessness=" << ftl::enum_string(rate.vote.seamlessness) << '}';
584}
585
Ady Abraham8a82ba62020-01-17 12:43:17 -0800586} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100587
588// TODO(b/129481165): remove the #pragma below and fix conversion issues
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700589#pragma clang diagnostic pop // ignored "-Wextra"