blob: 6e2b943509753a849b5f90a5a293cf3362b532dc [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>
Vishnu Nairbe0ad902024-06-27 23:38:43 +000030#include <common/trace.h>
Ady Abraham0ccd79b2020-06-10 10:11:17 -070031#include <cutils/compiler.h>
32#include <cutils/trace.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070033#include <ftl/enum.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
Vishnu Nairef68d6d2023-02-28 06:18:27 +000058 *mLayerProps = props;
Ady Abraham5def7332020-05-29 16:13:47 -070059 switch (updateType) {
60 case LayerUpdateType::AnimationTX:
Ady Abrahamf8fdc452024-04-05 16:22:55 +000061 mLastUpdatedTime = std::max(lastPresentTime, now);
Ady Abraham5def7332020-05-29 16:13:47 -070062 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:
Ady Abrahamf8fdc452024-04-05 16:22:55 +000070 mLastUpdatedTime = std::max(lastPresentTime, now);
Marin Shalamanov2045d5b2020-12-28 18:11:41 +010071 FrameTimeData frameTime = {.presentTime = lastPresentTime,
Ady Abraham5def7332020-05-29 16:13:47 -070072 .queueTime = mLastUpdatedTime,
Arthur Hungc70bee22023-06-02 01:35:52 +000073 .pendingModeChange = pendingModeChange,
74 .isSmallDirty = props.isSmallDirty};
Ady Abraham5def7332020-05-29 16:13:47 -070075 mFrameTimes.push_back(frameTime);
76 if (mFrameTimes.size() > HISTORY_SIZE) {
77 mFrameTimes.pop_front();
78 }
79 break;
Ady Abraham8a82ba62020-01-17 12:43:17 -080080 }
81}
82
Vishnu Nair41376b62023-11-08 05:08:58 -080083void LayerInfo::setProperties(const android::scheduler::LayerProps& properties) {
84 *mLayerProps = properties;
85}
86
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +010087bool LayerInfo::isFrameTimeValid(const FrameTimeData& frameTime) const {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000088 return frameTime.queueTime >= std::chrono::duration_cast<std::chrono::nanoseconds>(
89 mFrameTimeValidSince.time_since_epoch())
90 .count();
91}
Ady Abraham1adbb722020-05-15 11:51:48 -070092
ramindani63db24e2023-04-03 10:56:05 -070093LayerInfo::Frequent LayerInfo::isFrequent(nsecs_t now) const {
Ady Abraham86ac5c52023-01-11 15:24:03 -080094 // If we know nothing about this layer (e.g. after touch event),
95 // we consider it as frequent as it might be the start of an animation.
Marin Shalamanov2045d5b2020-12-28 18:11:41 +010096 if (mFrameTimes.size() < kFrequentLayerWindowSize) {
ramindani63db24e2023-04-03 10:56:05 -070097 return {/* isFrequent */ true, /* clearHistory */ false, /* isConclusive */ true};
Ady Abrahamdfb63ba2020-05-27 20:05:05 +000098 }
Ady Abraham86ac5c52023-01-11 15:24:03 -080099
100 // Non-active layers are also infrequent
101 if (mLastUpdatedTime < getActiveLayerThreshold(now)) {
ramindani63db24e2023-04-03 10:56:05 -0700102 return {/* isFrequent */ false, /* clearHistory */ false, /* isConclusive */ true};
Ady Abraham86ac5c52023-01-11 15:24:03 -0800103 }
104
105 // We check whether we can classify this layer as frequent or infrequent:
106 // - frequent: a layer posted kFrequentLayerWindowSize within
107 // kMaxPeriodForFrequentLayerNs of each other.
108 // - infrequent: a layer posted kFrequentLayerWindowSize with longer
109 // gaps than kFrequentLayerWindowSize.
110 // If we can't determine the layer classification yet, we return the last
111 // classification.
112 bool isFrequent = true;
113 bool isInfrequent = true;
Arthur Hungc70bee22023-06-02 01:35:52 +0000114 int32_t smallDirtyCount = 0;
Ady Abraham86ac5c52023-01-11 15:24:03 -0800115 const auto n = mFrameTimes.size() - 1;
116 for (size_t i = 0; i < kFrequentLayerWindowSize - 1; i++) {
117 if (mFrameTimes[n - i].queueTime - mFrameTimes[n - i - 1].queueTime <
118 kMaxPeriodForFrequentLayerNs.count()) {
119 isInfrequent = false;
Arthur Hungc70bee22023-06-02 01:35:52 +0000120 if (mFrameTimes[n - i].presentTime == 0 && mFrameTimes[n - i].isSmallDirty) {
121 smallDirtyCount++;
122 }
Ady Abraham86ac5c52023-01-11 15:24:03 -0800123 } else {
124 isFrequent = false;
125 }
126 }
127
Arthur Hung8144e022023-09-08 10:26:23 +0000128 // Vote the small dirty when a layer contains at least HISTORY_SIZE of small dirty updates.
129 bool isSmallDirty = false;
130 if (smallDirtyCount >= kNumSmallDirtyThreshold) {
131 if (mLastSmallDirtyCount >= HISTORY_SIZE) {
132 isSmallDirty = true;
133 } else {
134 mLastSmallDirtyCount++;
135 }
136 } else {
137 mLastSmallDirtyCount = 0;
138 }
139
Ady Abraham86ac5c52023-01-11 15:24:03 -0800140 if (isFrequent || isInfrequent) {
ramindani63db24e2023-04-03 10:56:05 -0700141 // If the layer was previously inconclusive, we clear
142 // the history as indeterminate layers changed to frequent,
143 // and we should not look at the stale data.
Arthur Hungc70bee22023-06-02 01:35:52 +0000144 return {isFrequent, isFrequent && !mIsFrequencyConclusive, /* isConclusive */ true,
Arthur Hung8144e022023-09-08 10:26:23 +0000145 isSmallDirty};
Ady Abraham86ac5c52023-01-11 15:24:03 -0800146 }
147
148 // If we can't determine whether the layer is frequent or not, we return
ramindani63db24e2023-04-03 10:56:05 -0700149 // the last known classification and mark the layer frequency as inconclusive.
150 isFrequent = !mLastRefreshRate.infrequent;
151
152 // If the layer was previously tagged as animating, we clear
153 // the history as it is likely the layer just changed its behavior,
154 // and we should not look at stale data.
155 return {isFrequent, isFrequent && mLastRefreshRate.animating, /* isConclusive */ false};
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400156}
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000157
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400158Fps LayerInfo::getFps(nsecs_t now) const {
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000159 // Find the first active frame
Ady Abraham983e5682020-05-28 16:49:18 -0700160 auto it = mFrameTimes.begin();
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000161 for (; it != mFrameTimes.end(); ++it) {
162 if (it->queueTime >= getActiveLayerThreshold(now)) {
163 break;
164 }
165 }
166
167 const auto numFrames = std::distance(it, mFrameTimes.end());
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100168 if (numFrames < kFrequentLayerWindowSize) {
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400169 return Fps();
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000170 }
171
172 // Layer is considered frequent if the average frame rate is higher than the threshold
173 const auto totalTime = mFrameTimes.back().queueTime - it->queueTime;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400174 return Fps::fromPeriodNsecs(totalTime / (numFrames - 1));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800175}
176
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100177bool LayerInfo::isAnimating(nsecs_t now) const {
Ady Abraham5def7332020-05-29 16:13:47 -0700178 return mLastAnimationTime >= getActiveLayerThreshold(now);
179}
180
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100181bool LayerInfo::hasEnoughDataForHeuristic() const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700182 // The layer had to publish at least HISTORY_SIZE or HISTORY_DURATION of updates
Ady Abrahama61edcb2020-01-30 18:32:03 -0800183 if (mFrameTimes.size() < 2) {
Rachel Lee70f49092024-05-02 13:53:51 -0700184 ALOGV("%s fewer than 2 frames recorded: %zu", mName.c_str(), mFrameTimes.size());
Ady Abrahama61edcb2020-01-30 18:32:03 -0800185 return false;
186 }
187
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000188 if (!isFrameTimeValid(mFrameTimes.front())) {
Rachel Lee70f49092024-05-02 13:53:51 -0700189 ALOGV("%s stale frames still captured", mName.c_str());
Ady Abrahamdfb63ba2020-05-27 20:05:05 +0000190 return false;
191 }
192
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700193 const auto totalDuration = mFrameTimes.back().queueTime - mFrameTimes.front().queueTime;
194 if (mFrameTimes.size() < HISTORY_SIZE && totalDuration < HISTORY_DURATION.count()) {
Rachel Lee70f49092024-05-02 13:53:51 -0700195 ALOGV("%s not enough frames captured: %zu | %.2f seconds", mName.c_str(),
196 mFrameTimes.size(), totalDuration / 1e9f);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800197 return false;
198 }
199
200 return true;
201}
202
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100203std::optional<nsecs_t> LayerInfo::calculateAverageFrameTime() const {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100204 // Ignore frames captured during a mode change
205 const bool isDuringModeChange =
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100206 std::any_of(mFrameTimes.begin(), mFrameTimes.end(),
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100207 [](const auto& frame) { return frame.pendingModeChange; });
208 if (isDuringModeChange) {
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100209 return std::nullopt;
210 }
Ady Abraham32efd542020-05-19 17:49:26 -0700211
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100212 const bool isMissingPresentTime =
213 std::any_of(mFrameTimes.begin(), mFrameTimes.end(),
214 [](auto frame) { return frame.presentTime == 0; });
215 if (isMissingPresentTime && !mLastRefreshRate.reported.isValid()) {
216 // If there are no presentation timestamps and we haven't calculated
217 // one in the past then we can't calculate the refresh rate
218 return std::nullopt;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800219 }
Ady Abrahamc9664832020-05-12 14:16:56 -0700220
Ady Abrahamc9664832020-05-12 14:16:56 -0700221 // Calculate the average frame time based on presentation timestamps. If those
222 // doesn't exist, we look at the time the buffer was queued only. We can do that only if
223 // we calculated a refresh rate based on presentation timestamps in the past. The reason
224 // we look at the queue time is to handle cases where hwui attaches presentation timestamps
225 // when implementing render ahead for specific refresh rates. When hwui no longer provides
226 // presentation timestamps we look at the queue time to see if the current refresh rate still
227 // matches the content.
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700228
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100229 auto getFrameTime = isMissingPresentTime ? [](FrameTimeData data) { return data.queueTime; }
230 : [](FrameTimeData data) { return data.presentTime; };
231
232 nsecs_t totalDeltas = 0;
233 int numDeltas = 0;
Arthur Hungc70bee22023-06-02 01:35:52 +0000234 int32_t smallDirtyCount = 0;
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100235 auto prevFrame = mFrameTimes.begin();
236 for (auto it = mFrameTimes.begin() + 1; it != mFrameTimes.end(); ++it) {
237 const auto currDelta = getFrameTime(*it) - getFrameTime(*prevFrame);
238 if (currDelta < kMinPeriodBetweenFrames) {
239 // Skip this frame, but count the delta into the next frame
240 continue;
241 }
242
Arthur Hungc70bee22023-06-02 01:35:52 +0000243 // If this is a small area update, we don't want to consider it for calculating the average
244 // frame time. Instead, we let the bigger frame updates to drive the calculation.
245 if (it->isSmallDirty && currDelta < kMinPeriodBetweenSmallDirtyFrames) {
246 smallDirtyCount++;
247 continue;
248 }
249
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100250 prevFrame = it;
251
252 if (currDelta > kMaxPeriodBetweenFrames) {
253 // Skip this frame and the current delta.
254 continue;
255 }
256
257 totalDeltas += currDelta;
258 numDeltas++;
259 }
260
Arthur Hungc70bee22023-06-02 01:35:52 +0000261 if (smallDirtyCount > 0) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000262 SFTRACE_FORMAT_INSTANT("small dirty = %" PRIu32, smallDirtyCount);
Arthur Hungc70bee22023-06-02 01:35:52 +0000263 }
264
Marin Shalamanov2045d5b2020-12-28 18:11:41 +0100265 if (numDeltas == 0) {
266 return std::nullopt;
267 }
268
269 const auto averageFrameTime = static_cast<double>(totalDeltas) / static_cast<double>(numDeltas);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700270 return static_cast<nsecs_t>(averageFrameTime);
Ady Abraham32efd542020-05-19 17:49:26 -0700271}
Ady Abraham8a82ba62020-01-17 12:43:17 -0800272
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400273std::optional<Fps> LayerInfo::calculateRefreshRateIfPossible(const RefreshRateSelector& selector,
274 nsecs_t now) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000275 SFTRACE_CALL();
Ady Abraham32efd542020-05-19 17:49:26 -0700276 static constexpr float MARGIN = 1.0f; // 1Hz
Ady Abraham32efd542020-05-19 17:49:26 -0700277 if (!hasEnoughDataForHeuristic()) {
278 ALOGV("Not enough data");
279 return std::nullopt;
280 }
281
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700282 if (const auto averageFrameTime = calculateAverageFrameTime()) {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100283 const auto refreshRate = Fps::fromPeriodNsecs(*averageFrameTime);
Jerry Chang04eb8e02023-11-15 08:06:07 +0000284 const auto closestKnownRefreshRate = mRefreshRateHistory.add(refreshRate, now, selector);
285 if (closestKnownRefreshRate.isValid()) {
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700286 using fps_approx_ops::operator!=;
287
288 // To avoid oscillation, use the last calculated refresh rate if it is close enough.
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100289 if (std::abs(mLastRefreshRate.calculated.getValue() - refreshRate.getValue()) >
290 MARGIN &&
Jerry Chang04eb8e02023-11-15 08:06:07 +0000291 mLastRefreshRate.reported != closestKnownRefreshRate) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700292 mLastRefreshRate.calculated = refreshRate;
Jerry Chang04eb8e02023-11-15 08:06:07 +0000293 mLastRefreshRate.reported = closestKnownRefreshRate;
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700294 }
295
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100296 ALOGV("%s %s rounded to nearest known frame rate %s", mName.c_str(),
297 to_string(refreshRate).c_str(), to_string(mLastRefreshRate.reported).c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700298 } else {
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100299 ALOGV("%s Not stable (%s) returning last known frame rate %s", mName.c_str(),
300 to_string(refreshRate).c_str(), to_string(mLastRefreshRate.reported).c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700301 }
Ady Abraham32efd542020-05-19 17:49:26 -0700302 }
303
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100304 return mLastRefreshRate.reported.isValid() ? std::make_optional(mLastRefreshRate.reported)
305 : std::nullopt;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800306}
307
Rachel Leece6e0042023-06-27 11:22:54 -0700308LayerInfo::RefreshRateVotes LayerInfo::getRefreshRateVote(const RefreshRateSelector& selector,
309 nsecs_t now) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000310 SFTRACE_CALL();
Rachel Leece6e0042023-06-27 11:22:54 -0700311 LayerInfo::RefreshRateVotes votes;
312
Ady Abraham8a82ba62020-01-17 12:43:17 -0800313 if (mLayerVote.type != LayerHistory::LayerVoteType::Heuristic) {
Rachel Leece6e0042023-06-27 11:22:54 -0700314 if (mLayerVote.category != FrameRateCategory::Default) {
Rachel Lee414f4082023-10-23 14:48:44 -0700315 const auto voteType = mLayerVote.type == LayerHistory::LayerVoteType::NoVote
316 ? LayerHistory::LayerVoteType::NoVote
317 : LayerHistory::LayerVoteType::ExplicitCategory;
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000318 SFTRACE_FORMAT_INSTANT("Vote %s (category=%s)", ftl::enum_string(voteType).c_str(),
319 ftl::enum_string(mLayerVote.category).c_str());
Rachel Lee414f4082023-10-23 14:48:44 -0700320 ALOGV("%s voted %s with category: %s", mName.c_str(),
321 ftl::enum_string(voteType).c_str(),
322 ftl::enum_string(mLayerVote.category).c_str());
323 votes.push_back({voteType, Fps(), Seamlessness::Default, mLayerVote.category,
Rachel Lee67afbea2023-09-28 15:35:07 -0700324 mLayerVote.categorySmoothSwitchOnly});
Rachel Leece6e0042023-06-27 11:22:54 -0700325 }
326
327 if (mLayerVote.fps.isValid() ||
328 mLayerVote.type != LayerHistory::LayerVoteType::ExplicitDefault) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000329 SFTRACE_FORMAT_INSTANT("Vote %s", ftl::enum_string(mLayerVote.type).c_str());
Rachel Lee414f4082023-10-23 14:48:44 -0700330 ALOGV("%s voted %d", mName.c_str(), static_cast<int>(mLayerVote.type));
Ady Abraham0dd4bd42024-02-06 18:36:49 -0800331 votes.push_back({mLayerVote.type, mLayerVote.fps, mLayerVote.seamlessness,
332 FrameRateCategory::Default, mLayerVote.categorySmoothSwitchOnly});
Rachel Leece6e0042023-06-27 11:22:54 -0700333 }
334
335 return votes;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800336 }
337
Ady Abraham5def7332020-05-29 16:13:47 -0700338 if (isAnimating(now)) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000339 SFTRACE_FORMAT_INSTANT("animating");
Ady Abraham5def7332020-05-29 16:13:47 -0700340 ALOGV("%s is animating", mName.c_str());
Ady Abraham86ac5c52023-01-11 15:24:03 -0800341 mLastRefreshRate.animating = true;
Rachel Leece6e0042023-06-27 11:22:54 -0700342 votes.push_back({LayerHistory::LayerVoteType::Max, Fps()});
343 return votes;
Ady Abraham5def7332020-05-29 16:13:47 -0700344 }
345
Alec Mouri89f5d4e2023-10-20 17:12:49 +0000346 // Vote for max refresh rate whenever we're front-buffered.
347 if (FlagManager::getInstance().vrr_config() && isFrontBuffered()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000348 SFTRACE_FORMAT_INSTANT("front buffered");
Alec Mouri89f5d4e2023-10-20 17:12:49 +0000349 ALOGV("%s is front-buffered", mName.c_str());
350 votes.push_back({LayerHistory::LayerVoteType::Max, Fps()});
351 return votes;
352 }
353
ramindani63db24e2023-04-03 10:56:05 -0700354 const LayerInfo::Frequent frequent = isFrequent(now);
355 mIsFrequencyConclusive = frequent.isConclusive;
356 if (!frequent.isFrequent) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000357 SFTRACE_FORMAT_INSTANT("infrequent");
Ady Abrahama6b676e2020-05-27 14:29:09 -0700358 ALOGV("%s is infrequent", mName.c_str());
Ady Abraham86ac5c52023-01-11 15:24:03 -0800359 mLastRefreshRate.infrequent = true;
Arthur Hung8144e022023-09-08 10:26:23 +0000360 mLastSmallDirtyCount = 0;
ramindani63db24e2023-04-03 10:56:05 -0700361 // Infrequent layers vote for minimal refresh rate for
Marin Shalamanov29e25402021-04-07 21:09:58 +0200362 // battery saving purposes and also to prevent b/135718869.
Rachel Leece6e0042023-06-27 11:22:54 -0700363 votes.push_back({LayerHistory::LayerVoteType::Min, Fps()});
364 return votes;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800365 }
366
ramindani63db24e2023-04-03 10:56:05 -0700367 if (frequent.clearHistory) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000368 SFTRACE_FORMAT_INSTANT("frequent.clearHistory");
Rachel Lee70f49092024-05-02 13:53:51 -0700369 ALOGV("%s frequent.clearHistory", mName.c_str());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700370 clearHistory(now);
371 }
372
Arthur Hung8144e022023-09-08 10:26:23 +0000373 // Return no vote if the recent frames are small dirty.
Arthur Hungc70bee22023-06-02 01:35:52 +0000374 if (frequent.isSmallDirty && !mLastRefreshRate.reported.isValid()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000375 SFTRACE_FORMAT_INSTANT("NoVote (small dirty)");
Arthur Hungc70bee22023-06-02 01:35:52 +0000376 ALOGV("%s is small dirty", mName.c_str());
377 votes.push_back({LayerHistory::LayerVoteType::NoVote, Fps()});
378 return votes;
379 }
380
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400381 auto refreshRate = calculateRefreshRateIfPossible(selector, now);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800382 if (refreshRate.has_value()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000383 SFTRACE_FORMAT_INSTANT("calculated (%s)", to_string(*refreshRate).c_str());
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100384 ALOGV("%s calculated refresh rate: %s", mName.c_str(), to_string(*refreshRate).c_str());
Rachel Leece6e0042023-06-27 11:22:54 -0700385 votes.push_back({LayerHistory::LayerVoteType::Heuristic, refreshRate.value()});
386 return votes;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800387 }
388
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000389 SFTRACE_FORMAT_INSTANT("Max (can't resolve refresh rate)");
Ady Abrahama6b676e2020-05-27 14:29:09 -0700390 ALOGV("%s Max (can't resolve refresh rate)", mName.c_str());
Rachel Leece6e0042023-06-27 11:22:54 -0700391 votes.push_back({LayerHistory::LayerVoteType::Max, Fps()});
392 return votes;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800393}
394
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700395const char* LayerInfo::getTraceTag(LayerHistory::LayerVoteType type) const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700396 if (mTraceTags.count(type) == 0) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700397 auto tag = "LFPS " + mName + " " + ftl::enum_string(type);
398 mTraceTags.emplace(type, std::move(tag));
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700399 }
400
401 return mTraceTags.at(type).c_str();
402}
403
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000404LayerInfo::FrameRate LayerInfo::getSetFrameRateVote() const {
405 return mLayerProps->setFrameRateVote;
406}
407
408bool LayerInfo::isVisible() const {
409 return mLayerProps->visible;
410}
411
412int32_t LayerInfo::getFrameRateSelectionPriority() const {
413 return mLayerProps->frameRateSelectionPriority;
414}
415
Alec Mouri89f5d4e2023-10-20 17:12:49 +0000416bool LayerInfo::isFrontBuffered() const {
417 return mLayerProps->isFrontBuffered;
418}
419
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000420FloatRect LayerInfo::getBounds() const {
421 return mLayerProps->bounds;
422}
423
424ui::Transform LayerInfo::getTransform() const {
425 return mLayerProps->transform;
426}
427
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100428LayerInfo::RefreshRateHistory::HeuristicTraceTagData
429LayerInfo::RefreshRateHistory::makeHeuristicTraceTagData() const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700430 const std::string prefix = "LFPS ";
431 const std::string suffix = "Heuristic ";
432 return {.min = prefix + mName + suffix + "min",
433 .max = prefix + mName + suffix + "max",
434 .consistent = prefix + mName + suffix + "consistent",
435 .average = prefix + mName + suffix + "average"};
436}
437
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100438void LayerInfo::RefreshRateHistory::clear() {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700439 mRefreshRates.clear();
440}
441
Jerry Chang04eb8e02023-11-15 08:06:07 +0000442Fps LayerInfo::RefreshRateHistory::add(Fps refreshRate, nsecs_t now,
443 const RefreshRateSelector& selector) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700444 mRefreshRates.push_back({refreshRate, now});
445 while (mRefreshRates.size() >= HISTORY_SIZE ||
446 now - mRefreshRates.front().timestamp > HISTORY_DURATION.count()) {
447 mRefreshRates.pop_front();
448 }
449
450 if (CC_UNLIKELY(sTraceEnabled)) {
451 if (!mHeuristicTraceTagData.has_value()) {
452 mHeuristicTraceTagData = makeHeuristicTraceTagData();
453 }
454
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000455 SFTRACE_INT(mHeuristicTraceTagData->average.c_str(), refreshRate.getIntValue());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700456 }
457
Jerry Chang04eb8e02023-11-15 08:06:07 +0000458 return selectRefreshRate(selector);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700459}
460
Jerry Chang04eb8e02023-11-15 08:06:07 +0000461Fps LayerInfo::RefreshRateHistory::selectRefreshRate(const RefreshRateSelector& selector) const {
462 if (mRefreshRates.empty()) return Fps();
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700463
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700464 const auto [min, max] =
465 std::minmax_element(mRefreshRates.begin(), mRefreshRates.end(),
466 [](const auto& lhs, const auto& rhs) {
467 return isStrictlyLess(lhs.refreshRate, rhs.refreshRate);
468 });
469
Jerry Chang04eb8e02023-11-15 08:06:07 +0000470 const auto maxClosestRate = selector.findClosestKnownFrameRate(max->refreshRate);
471 const bool consistent = [&](Fps maxFps, Fps minFps) {
472 if (FlagManager::getInstance().use_known_refresh_rate_for_fps_consistency()) {
473 if (maxFps.getValue() - minFps.getValue() <
474 MARGIN_CONSISTENT_FPS_FOR_CLOSEST_REFRESH_RATE) {
475 const auto minClosestRate = selector.findClosestKnownFrameRate(minFps);
476 using fps_approx_ops::operator==;
477 return maxClosestRate == minClosestRate;
478 }
479 return false;
480 }
481 return maxFps.getValue() - minFps.getValue() < MARGIN_CONSISTENT_FPS;
482 }(max->refreshRate, min->refreshRate);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700483
484 if (CC_UNLIKELY(sTraceEnabled)) {
485 if (!mHeuristicTraceTagData.has_value()) {
486 mHeuristicTraceTagData = makeHeuristicTraceTagData();
487 }
488
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000489 SFTRACE_INT(mHeuristicTraceTagData->max.c_str(), max->refreshRate.getIntValue());
490 SFTRACE_INT(mHeuristicTraceTagData->min.c_str(), min->refreshRate.getIntValue());
491 SFTRACE_INT(mHeuristicTraceTagData->consistent.c_str(), consistent);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700492 }
493
Jerry Chang04eb8e02023-11-15 08:06:07 +0000494 return consistent ? maxClosestRate : Fps();
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700495}
496
Vishnu Nair3fbe3262023-09-29 17:07:00 -0700497FrameRateCompatibility LayerInfo::FrameRate::convertCompatibility(int8_t compatibility) {
Rachel Leece6e0042023-06-27 11:22:54 -0700498 switch (compatibility) {
499 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
500 return FrameRateCompatibility::Default;
501 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
502 return FrameRateCompatibility::ExactOrMultiple;
503 case ANATIVEWINDOW_FRAME_RATE_EXACT:
504 return FrameRateCompatibility::Exact;
505 case ANATIVEWINDOW_FRAME_RATE_MIN:
506 return FrameRateCompatibility::Min;
Rachel Lee227aef22024-11-26 11:31:08 -0800507 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_GTE:
Rachel Leee5514a72023-10-25 16:20:29 -0700508 return FrameRateCompatibility::Gte;
Rachel Leece6e0042023-06-27 11:22:54 -0700509 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
510 return FrameRateCompatibility::NoVote;
511 default:
512 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
513 return FrameRateCompatibility::Default;
514 }
515}
516
517Seamlessness LayerInfo::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
518 switch (strategy) {
519 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
520 return Seamlessness::OnlySeamless;
521 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
522 return Seamlessness::SeamedAndSeamless;
523 default:
524 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
525 return Seamlessness::Default;
526 }
527}
528
529FrameRateCategory LayerInfo::FrameRate::convertCategory(int8_t category) {
530 switch (category) {
531 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_DEFAULT:
532 return FrameRateCategory::Default;
533 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_NO_PREFERENCE:
534 return FrameRateCategory::NoPreference;
535 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_LOW:
536 return FrameRateCategory::Low;
537 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_NORMAL:
538 return FrameRateCategory::Normal;
Rachel Lee9580ff12023-12-26 17:33:41 -0800539 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_HIGH_HINT:
540 return FrameRateCategory::HighHint;
Rachel Leece6e0042023-06-27 11:22:54 -0700541 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_HIGH:
542 return FrameRateCategory::High;
543 default:
544 LOG_ALWAYS_FATAL("Invalid frame rate category value %d", category);
545 return FrameRateCategory::Default;
546 }
547}
548
Rachel Lee58cc90d2023-09-05 18:50:20 -0700549LayerInfo::FrameRateSelectionStrategy LayerInfo::convertFrameRateSelectionStrategy(
550 int8_t strategy) {
551 switch (strategy) {
Rachel Lee70f7b692023-11-22 11:24:02 -0800552 case ANATIVEWINDOW_FRAME_RATE_SELECTION_STRATEGY_PROPAGATE:
553 return FrameRateSelectionStrategy::Propagate;
Rachel Lee58cc90d2023-09-05 18:50:20 -0700554 case ANATIVEWINDOW_FRAME_RATE_SELECTION_STRATEGY_OVERRIDE_CHILDREN:
555 return FrameRateSelectionStrategy::OverrideChildren;
Rachel Lee70f7b692023-11-22 11:24:02 -0800556 case ANATIVEWINDOW_FRAME_RATE_SELECTION_STRATEGY_SELF:
557 return FrameRateSelectionStrategy::Self;
Rachel Lee58cc90d2023-09-05 18:50:20 -0700558 default:
559 LOG_ALWAYS_FATAL("Invalid frame rate selection strategy value %d", strategy);
560 return FrameRateSelectionStrategy::Self;
561 }
562}
563
Rachel Leece6e0042023-06-27 11:22:54 -0700564bool LayerInfo::FrameRate::isNoVote() const {
Rachel Lee76eb78f2024-11-27 15:44:35 -0800565 // A desired frame rate greater than or equal to 0 is treated as NoVote.
566 bool isNoVoteGte = FlagManager::getInstance().arr_setframerate_gte_enum() &&
567 vote.type == FrameRateCompatibility::Gte && !vote.rate.isValid();
568 return vote.type == FrameRateCompatibility::NoVote || isNoVoteGte;
Rachel Leece6e0042023-06-27 11:22:54 -0700569}
570
Rachel Lee8f2eea42024-04-19 15:15:48 -0700571bool LayerInfo::FrameRate::isValuelessType() const {
572 // For a valueless frame rate compatibility (type), the frame rate should be unspecified (0 Hz).
573 if (!isApproxEqual(vote.rate, 0_Hz)) {
574 return false;
575 }
576 switch (vote.type) {
577 case FrameRateCompatibility::Min:
578 case FrameRateCompatibility::NoVote:
579 return true;
580 case FrameRateCompatibility::Default:
581 case FrameRateCompatibility::ExactOrMultiple:
582 case FrameRateCompatibility::Exact:
Rachel Lee76eb78f2024-11-27 15:44:35 -0800583 return false;
Rachel Lee8f2eea42024-04-19 15:15:48 -0700584 case FrameRateCompatibility::Gte:
Rachel Lee76eb78f2024-11-27 15:44:35 -0800585 if (isNoVote()) {
586 // Special case: GTE 0 is same as NoVote.
587 return true;
588 }
Rachel Lee8f2eea42024-04-19 15:15:48 -0700589 return false;
590 }
591}
592
Rachel Leece6e0042023-06-27 11:22:54 -0700593bool LayerInfo::FrameRate::isValid() const {
Rachel Lee8f2eea42024-04-19 15:15:48 -0700594 return isValuelessType() || vote.rate.isValid() || category != FrameRateCategory::Default;
Rachel Leece6e0042023-06-27 11:22:54 -0700595}
596
Rachel Lee45681982024-03-14 18:40:15 -0700597bool LayerInfo::FrameRate::isVoteValidForMrr(bool isVrrDevice) const {
598 if (isVrrDevice || FlagManager::getInstance().frame_rate_category_mrr()) {
599 return true;
600 }
601
Rachel Lee8f2eea42024-04-19 15:15:48 -0700602 if (category == FrameRateCategory::Default) {
Rachel Lee45681982024-03-14 18:40:15 -0700603 return true;
604 }
605
Rachel Lee109c68e2024-09-05 18:57:31 -0700606 if (category == FrameRateCategory::NoPreference && vote.rate.isValid() &&
Rachel Lee0dd05182024-08-13 16:31:45 -0700607 vote.type == FrameRateCompatibility::ExactOrMultiple) {
608 return true;
609 }
610
Rachel Lee45681982024-03-14 18:40:15 -0700611 return false;
612}
613
Rachel Leece6e0042023-06-27 11:22:54 -0700614std::ostream& operator<<(std::ostream& stream, const LayerInfo::FrameRate& rate) {
615 return stream << "{rate=" << rate.vote.rate << " type=" << ftl::enum_string(rate.vote.type)
616 << " seamlessness=" << ftl::enum_string(rate.vote.seamlessness) << '}';
617}
618
Ady Abraham8a82ba62020-01-17 12:43:17 -0800619} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100620
621// TODO(b/129481165): remove the #pragma below and fix conversion issues
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700622#pragma clang diagnostic pop // ignored "-Wextra"