blob: 2dd3c62a4ed05fe247341f0d7dac93a53ae05144 [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));
Rachel Leece6e0042023-06-27 11:22:54 -0700330 votes.push_back(mLayerVote);
331 }
332
333 return votes;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800334 }
335
Ady Abraham5def7332020-05-29 16:13:47 -0700336 if (isAnimating(now)) {
Ady Abraham73c3df52023-01-12 18:09:31 -0800337 ATRACE_FORMAT_INSTANT("animating");
Ady Abraham5def7332020-05-29 16:13:47 -0700338 ALOGV("%s is animating", mName.c_str());
Ady Abraham86ac5c52023-01-11 15:24:03 -0800339 mLastRefreshRate.animating = true;
Rachel Leece6e0042023-06-27 11:22:54 -0700340 votes.push_back({LayerHistory::LayerVoteType::Max, Fps()});
341 return votes;
Ady Abraham5def7332020-05-29 16:13:47 -0700342 }
343
Alec Mouri89f5d4e2023-10-20 17:12:49 +0000344 // Vote for max refresh rate whenever we're front-buffered.
345 if (FlagManager::getInstance().vrr_config() && isFrontBuffered()) {
346 ATRACE_FORMAT_INSTANT("front buffered");
347 ALOGV("%s is front-buffered", mName.c_str());
348 votes.push_back({LayerHistory::LayerVoteType::Max, Fps()});
349 return votes;
350 }
351
ramindani63db24e2023-04-03 10:56:05 -0700352 const LayerInfo::Frequent frequent = isFrequent(now);
353 mIsFrequencyConclusive = frequent.isConclusive;
354 if (!frequent.isFrequent) {
Ady Abraham73c3df52023-01-12 18:09:31 -0800355 ATRACE_FORMAT_INSTANT("infrequent");
Ady Abrahama6b676e2020-05-27 14:29:09 -0700356 ALOGV("%s is infrequent", mName.c_str());
Ady Abraham86ac5c52023-01-11 15:24:03 -0800357 mLastRefreshRate.infrequent = true;
Arthur Hung8144e022023-09-08 10:26:23 +0000358 mLastSmallDirtyCount = 0;
ramindani63db24e2023-04-03 10:56:05 -0700359 // Infrequent layers vote for minimal refresh rate for
Marin Shalamanov29e25402021-04-07 21:09:58 +0200360 // battery saving purposes and also to prevent b/135718869.
Rachel Leece6e0042023-06-27 11:22:54 -0700361 votes.push_back({LayerHistory::LayerVoteType::Min, Fps()});
362 return votes;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800363 }
364
ramindani63db24e2023-04-03 10:56:05 -0700365 if (frequent.clearHistory) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700366 clearHistory(now);
367 }
368
Arthur Hung8144e022023-09-08 10:26:23 +0000369 // Return no vote if the recent frames are small dirty.
Arthur Hungc70bee22023-06-02 01:35:52 +0000370 if (frequent.isSmallDirty && !mLastRefreshRate.reported.isValid()) {
371 ATRACE_FORMAT_INSTANT("NoVote (small dirty)");
372 ALOGV("%s is small dirty", mName.c_str());
373 votes.push_back({LayerHistory::LayerVoteType::NoVote, Fps()});
374 return votes;
375 }
376
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400377 auto refreshRate = calculateRefreshRateIfPossible(selector, now);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800378 if (refreshRate.has_value()) {
Rachel Leec0e40bc2023-09-12 13:41:15 -0700379 ATRACE_FORMAT_INSTANT("calculated (%s)", to_string(*refreshRate).c_str());
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100380 ALOGV("%s calculated refresh rate: %s", mName.c_str(), to_string(*refreshRate).c_str());
Rachel Leece6e0042023-06-27 11:22:54 -0700381 votes.push_back({LayerHistory::LayerVoteType::Heuristic, refreshRate.value()});
382 return votes;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800383 }
384
Rachel Leec0e40bc2023-09-12 13:41:15 -0700385 ATRACE_FORMAT_INSTANT("Max (can't resolve refresh rate)");
Ady Abrahama6b676e2020-05-27 14:29:09 -0700386 ALOGV("%s Max (can't resolve refresh rate)", mName.c_str());
Rachel Leece6e0042023-06-27 11:22:54 -0700387 votes.push_back({LayerHistory::LayerVoteType::Max, Fps()});
388 return votes;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800389}
390
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700391const char* LayerInfo::getTraceTag(LayerHistory::LayerVoteType type) const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700392 if (mTraceTags.count(type) == 0) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700393 auto tag = "LFPS " + mName + " " + ftl::enum_string(type);
394 mTraceTags.emplace(type, std::move(tag));
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700395 }
396
397 return mTraceTags.at(type).c_str();
398}
399
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000400LayerInfo::FrameRate LayerInfo::getSetFrameRateVote() const {
401 return mLayerProps->setFrameRateVote;
402}
403
404bool LayerInfo::isVisible() const {
405 return mLayerProps->visible;
406}
407
408int32_t LayerInfo::getFrameRateSelectionPriority() const {
409 return mLayerProps->frameRateSelectionPriority;
410}
411
Alec Mouri89f5d4e2023-10-20 17:12:49 +0000412bool LayerInfo::isFrontBuffered() const {
413 return mLayerProps->isFrontBuffered;
414}
415
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000416FloatRect LayerInfo::getBounds() const {
417 return mLayerProps->bounds;
418}
419
420ui::Transform LayerInfo::getTransform() const {
421 return mLayerProps->transform;
422}
423
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100424LayerInfo::RefreshRateHistory::HeuristicTraceTagData
425LayerInfo::RefreshRateHistory::makeHeuristicTraceTagData() const {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700426 const std::string prefix = "LFPS ";
427 const std::string suffix = "Heuristic ";
428 return {.min = prefix + mName + suffix + "min",
429 .max = prefix + mName + suffix + "max",
430 .consistent = prefix + mName + suffix + "consistent",
431 .average = prefix + mName + suffix + "average"};
432}
433
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100434void LayerInfo::RefreshRateHistory::clear() {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700435 mRefreshRates.clear();
436}
437
Jerry Chang04eb8e02023-11-15 08:06:07 +0000438Fps LayerInfo::RefreshRateHistory::add(Fps refreshRate, nsecs_t now,
439 const RefreshRateSelector& selector) {
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700440 mRefreshRates.push_back({refreshRate, now});
441 while (mRefreshRates.size() >= HISTORY_SIZE ||
442 now - mRefreshRates.front().timestamp > HISTORY_DURATION.count()) {
443 mRefreshRates.pop_front();
444 }
445
446 if (CC_UNLIKELY(sTraceEnabled)) {
447 if (!mHeuristicTraceTagData.has_value()) {
448 mHeuristicTraceTagData = makeHeuristicTraceTagData();
449 }
450
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100451 ATRACE_INT(mHeuristicTraceTagData->average.c_str(), refreshRate.getIntValue());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700452 }
453
Jerry Chang04eb8e02023-11-15 08:06:07 +0000454 return selectRefreshRate(selector);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700455}
456
Jerry Chang04eb8e02023-11-15 08:06:07 +0000457Fps LayerInfo::RefreshRateHistory::selectRefreshRate(const RefreshRateSelector& selector) const {
458 if (mRefreshRates.empty()) return Fps();
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700459
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700460 const auto [min, max] =
461 std::minmax_element(mRefreshRates.begin(), mRefreshRates.end(),
462 [](const auto& lhs, const auto& rhs) {
463 return isStrictlyLess(lhs.refreshRate, rhs.refreshRate);
464 });
465
Jerry Chang04eb8e02023-11-15 08:06:07 +0000466 const auto maxClosestRate = selector.findClosestKnownFrameRate(max->refreshRate);
467 const bool consistent = [&](Fps maxFps, Fps minFps) {
468 if (FlagManager::getInstance().use_known_refresh_rate_for_fps_consistency()) {
469 if (maxFps.getValue() - minFps.getValue() <
470 MARGIN_CONSISTENT_FPS_FOR_CLOSEST_REFRESH_RATE) {
471 const auto minClosestRate = selector.findClosestKnownFrameRate(minFps);
472 using fps_approx_ops::operator==;
473 return maxClosestRate == minClosestRate;
474 }
475 return false;
476 }
477 return maxFps.getValue() - minFps.getValue() < MARGIN_CONSISTENT_FPS;
478 }(max->refreshRate, min->refreshRate);
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700479
480 if (CC_UNLIKELY(sTraceEnabled)) {
481 if (!mHeuristicTraceTagData.has_value()) {
482 mHeuristicTraceTagData = makeHeuristicTraceTagData();
483 }
484
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100485 ATRACE_INT(mHeuristicTraceTagData->max.c_str(), max->refreshRate.getIntValue());
486 ATRACE_INT(mHeuristicTraceTagData->min.c_str(), min->refreshRate.getIntValue());
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700487 ATRACE_INT(mHeuristicTraceTagData->consistent.c_str(), consistent);
488 }
489
Jerry Chang04eb8e02023-11-15 08:06:07 +0000490 return consistent ? maxClosestRate : Fps();
Ady Abraham0ccd79b2020-06-10 10:11:17 -0700491}
492
Vishnu Nair3fbe3262023-09-29 17:07:00 -0700493FrameRateCompatibility LayerInfo::FrameRate::convertCompatibility(int8_t compatibility) {
Rachel Leece6e0042023-06-27 11:22:54 -0700494 switch (compatibility) {
495 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
496 return FrameRateCompatibility::Default;
497 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
498 return FrameRateCompatibility::ExactOrMultiple;
499 case ANATIVEWINDOW_FRAME_RATE_EXACT:
500 return FrameRateCompatibility::Exact;
501 case ANATIVEWINDOW_FRAME_RATE_MIN:
502 return FrameRateCompatibility::Min;
Rachel Leee5514a72023-10-25 16:20:29 -0700503 case ANATIVEWINDOW_FRAME_RATE_GTE:
504 return FrameRateCompatibility::Gte;
Rachel Leece6e0042023-06-27 11:22:54 -0700505 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
506 return FrameRateCompatibility::NoVote;
507 default:
508 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
509 return FrameRateCompatibility::Default;
510 }
511}
512
513Seamlessness LayerInfo::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
514 switch (strategy) {
515 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
516 return Seamlessness::OnlySeamless;
517 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
518 return Seamlessness::SeamedAndSeamless;
519 default:
520 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
521 return Seamlessness::Default;
522 }
523}
524
525FrameRateCategory LayerInfo::FrameRate::convertCategory(int8_t category) {
526 switch (category) {
527 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_DEFAULT:
528 return FrameRateCategory::Default;
529 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_NO_PREFERENCE:
530 return FrameRateCategory::NoPreference;
531 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_LOW:
532 return FrameRateCategory::Low;
533 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_NORMAL:
534 return FrameRateCategory::Normal;
535 case ANATIVEWINDOW_FRAME_RATE_CATEGORY_HIGH:
536 return FrameRateCategory::High;
537 default:
538 LOG_ALWAYS_FATAL("Invalid frame rate category value %d", category);
539 return FrameRateCategory::Default;
540 }
541}
542
Rachel Lee58cc90d2023-09-05 18:50:20 -0700543LayerInfo::FrameRateSelectionStrategy LayerInfo::convertFrameRateSelectionStrategy(
544 int8_t strategy) {
545 switch (strategy) {
Rachel Lee70f7b692023-11-22 11:24:02 -0800546 case ANATIVEWINDOW_FRAME_RATE_SELECTION_STRATEGY_PROPAGATE:
547 return FrameRateSelectionStrategy::Propagate;
Rachel Lee58cc90d2023-09-05 18:50:20 -0700548 case ANATIVEWINDOW_FRAME_RATE_SELECTION_STRATEGY_OVERRIDE_CHILDREN:
549 return FrameRateSelectionStrategy::OverrideChildren;
Rachel Lee70f7b692023-11-22 11:24:02 -0800550 case ANATIVEWINDOW_FRAME_RATE_SELECTION_STRATEGY_SELF:
551 return FrameRateSelectionStrategy::Self;
Rachel Lee58cc90d2023-09-05 18:50:20 -0700552 default:
553 LOG_ALWAYS_FATAL("Invalid frame rate selection strategy value %d", strategy);
554 return FrameRateSelectionStrategy::Self;
555 }
556}
557
Rachel Leece6e0042023-06-27 11:22:54 -0700558bool LayerInfo::FrameRate::isNoVote() const {
Rachel Leed0694bc2023-09-12 14:57:58 -0700559 return vote.type == FrameRateCompatibility::NoVote;
Rachel Leece6e0042023-06-27 11:22:54 -0700560}
561
562bool LayerInfo::FrameRate::isValid() const {
563 return isNoVote() || vote.rate.isValid() || category != FrameRateCategory::Default;
564}
565
566std::ostream& operator<<(std::ostream& stream, const LayerInfo::FrameRate& rate) {
567 return stream << "{rate=" << rate.vote.rate << " type=" << ftl::enum_string(rate.vote.type)
568 << " seamlessness=" << ftl::enum_string(rate.vote.seamlessness) << '}';
569}
570
Ady Abraham8a82ba62020-01-17 12:43:17 -0800571} // namespace android::scheduler
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100572
573// TODO(b/129481165): remove the #pragma below and fix conversion issues
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700574#pragma clang diagnostic pop // ignored "-Wextra"