blob: ff360b754c2e4bcbb00e400fe8a4204f19112810 [file] [log] [blame]
Kevin DuBois1678e2c2019-08-22 12:26:24 -07001/*
2 * Copyright 2019 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
Dominik Laskowski62eff352021-12-06 09:59:41 -080021#undef LOG_TAG
22#define LOG_TAG "VSyncPredictor"
23
Kevin DuBois1678e2c2019-08-22 12:26:24 -070024#define ATRACE_TAG ATRACE_TAG_GRAPHICS
Dominik Laskowski62eff352021-12-06 09:59:41 -080025
26#include <algorithm>
27#include <chrono>
28#include <sstream>
29
Kevin DuBois1678e2c2019-08-22 12:26:24 -070030#include <android-base/logging.h>
Ady Abraham5e7371c2020-03-24 14:47:24 -070031#include <android-base/stringprintf.h>
Alec Mouri9b133ca2023-11-14 19:00:01 +000032#include <common/FlagManager.h>
Vishnu Nairbe0ad902024-06-27 23:38:43 +000033#include <common/trace.h>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070034#include <cutils/compiler.h>
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080035#include <cutils/properties.h>
Leon Scroggins III67388622023-02-06 20:36:20 -050036#include <ftl/concat.h>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070037#include <utils/Log.h>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070038
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040039#include "RefreshRateSelector.h"
Dominik Laskowski62eff352021-12-06 09:59:41 -080040#include "VSyncPredictor.h"
Ady Abraham0bb6a472020-10-12 10:22:13 -070041
Kevin DuBois1678e2c2019-08-22 12:26:24 -070042namespace android::scheduler {
Dominik Laskowski62eff352021-12-06 09:59:41 -080043
Ady Abraham5e7371c2020-03-24 14:47:24 -070044using base::StringAppendF;
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080045
Kevin DuBois1678e2c2019-08-22 12:26:24 -070046static auto constexpr kMaxPercent = 100u;
47
Ady Abraham940b7a62024-03-07 10:04:27 -080048namespace {
49int numVsyncsPerFrame(const ftl::NonNull<DisplayModePtr>& displayModePtr) {
50 const auto idealPeakRefreshPeriod = displayModePtr->getPeakFps().getPeriodNsecs();
51 const auto idealRefreshPeriod = displayModePtr->getVsyncRate().getPeriodNsecs();
52 return static_cast<int>(std::round(static_cast<float>(idealPeakRefreshPeriod) /
53 static_cast<float>(idealRefreshPeriod)));
54}
55} // namespace
56
Kevin DuBois1678e2c2019-08-22 12:26:24 -070057VSyncPredictor::~VSyncPredictor() = default;
58
Ady Abraham20024aa2024-03-05 01:32:49 +000059VSyncPredictor::VSyncPredictor(std::unique_ptr<Clock> clock, ftl::NonNull<DisplayModePtr> modePtr,
60 size_t historySize, size_t minimumSamplesForPrediction,
61 uint32_t outlierTolerancePercent)
62 : mClock(std::move(clock)),
63 mId(modePtr->getPhysicalDisplayId()),
Leon Scroggins III67388622023-02-06 20:36:20 -050064 mTraceOn(property_get_bool("debug.sf.vsp_trace", false)),
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080065 kHistorySize(historySize),
Kevin DuBois1678e2c2019-08-22 12:26:24 -070066 kMinimumSamplesForPrediction(minimumSamplesForPrediction),
67 kOutlierTolerancePercent(std::min(outlierTolerancePercent, kMaxPercent)),
Ady Abraham940b7a62024-03-07 10:04:27 -080068 mDisplayModePtr(modePtr),
69 mNumVsyncsForFrame(numVsyncsPerFrame(mDisplayModePtr)) {
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -080070 resetModel();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070071}
72
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080073inline void VSyncPredictor::traceInt64If(const char* name, int64_t value) const {
74 if (CC_UNLIKELY(mTraceOn)) {
Leon Scroggins III67388622023-02-06 20:36:20 -050075 traceInt64(name, value);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080076 }
77}
78
Ady Abrahamd9b9a042023-01-13 11:30:58 -080079inline void VSyncPredictor::traceInt64(const char* name, int64_t value) const {
Vishnu Nairbe0ad902024-06-27 23:38:43 +000080 SFTRACE_INT64(ftl::Concat(ftl::truncated<14>(name), " ", mId.value).c_str(), value);
Ady Abrahamd9b9a042023-01-13 11:30:58 -080081}
82
Ady Abraham9c53ee72020-07-22 21:16:18 -070083inline size_t VSyncPredictor::next(size_t i) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080084 return (i + 1) % mTimestamps.size();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070085}
86
Ady Abrahamc585dba2023-11-15 18:41:35 -080087nsecs_t VSyncPredictor::idealPeriod() const {
88 return mDisplayModePtr->getVsyncRate().getPeriodNsecs();
89}
90
Kevin DuBois1678e2c2019-08-22 12:26:24 -070091bool VSyncPredictor::validate(nsecs_t timestamp) const {
Ady Abraham9ee31132024-08-06 16:44:08 +000092 SFTRACE_CALL();
Ady Abraham92fa2f42020-02-11 15:33:56 -080093 if (mLastTimestampIndex < 0 || mTimestamps.empty()) {
Ady Abraham9ee31132024-08-06 16:44:08 +000094 SFTRACE_INSTANT("timestamp valid (first)");
Kevin DuBois1678e2c2019-08-22 12:26:24 -070095 return true;
96 }
97
Ady Abrahamc585dba2023-11-15 18:41:35 -080098 const auto aValidTimestamp = mTimestamps[mLastTimestampIndex];
99 const auto percent =
100 (timestamp - aValidTimestamp) % idealPeriod() * kMaxPercent / idealPeriod();
Ady Abraham99ca3362021-06-17 12:28:46 -0700101 if (percent >= kOutlierTolerancePercent &&
102 percent <= (kMaxPercent - kOutlierTolerancePercent)) {
Ady Abraham9ee31132024-08-06 16:44:08 +0000103 SFTRACE_FORMAT_INSTANT("timestamp not aligned with model. aValidTimestamp %.2fms ago"
104 ", timestamp %.2fms ago, idealPeriod=%.2 percent=%d",
105 (mClock->now() - aValidTimestamp) / 1e6f,
106 (mClock->now() - timestamp) / 1e6f,
107 idealPeriod() / 1e6f, percent);
Ady Abraham99ca3362021-06-17 12:28:46 -0700108 return false;
109 }
110
111 const auto iter = std::min_element(mTimestamps.begin(), mTimestamps.end(),
112 [timestamp](nsecs_t a, nsecs_t b) {
113 return std::abs(timestamp - a) < std::abs(timestamp - b);
114 });
Ady Abrahamc585dba2023-11-15 18:41:35 -0800115 const auto distancePercent = std::abs(*iter - timestamp) * kMaxPercent / idealPeriod();
Ady Abraham99ca3362021-06-17 12:28:46 -0700116 if (distancePercent < kOutlierTolerancePercent) {
117 // duplicate timestamp
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000118 SFTRACE_FORMAT_INSTANT("duplicate timestamp");
Ady Abraham99ca3362021-06-17 12:28:46 -0700119 return false;
120 }
121 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700122}
123
Kevin DuBois2fd3cea2019-11-14 08:52:45 -0800124nsecs_t VSyncPredictor::currentPeriod() const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700125 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800126 return mRateMap.find(idealPeriod())->second.slope;
Kevin DuBois2fd3cea2019-11-14 08:52:45 -0800127}
128
Ady Abraham3db8a3c2023-11-20 17:53:47 -0800129Period VSyncPredictor::minFramePeriod() const {
130 if (!FlagManager::getInstance().vrr_config()) {
131 return Period::fromNs(currentPeriod());
132 }
133
134 std::lock_guard lock(mMutex);
Ady Abrahame9883032023-11-20 17:54:54 -0800135 return minFramePeriodLocked();
136}
137
138Period VSyncPredictor::minFramePeriodLocked() const {
Ady Abraham3db8a3c2023-11-20 17:53:47 -0800139 const auto slope = mRateMap.find(idealPeriod())->second.slope;
Ady Abraham940b7a62024-03-07 10:04:27 -0800140 return Period::fromNs(slope * mNumVsyncsForFrame);
Ady Abraham3db8a3c2023-11-20 17:53:47 -0800141}
142
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800143bool VSyncPredictor::addVsyncTimestamp(nsecs_t timestamp) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000144 SFTRACE_CALL();
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000145
Ady Abraham9c53ee72020-07-22 21:16:18 -0700146 std::lock_guard lock(mMutex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700147
148 if (!validate(timestamp)) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700149 // VSR could elect to ignore the incongruent timestamp or resetModel(). If ts is ignored,
Ady Abraham43a3e692020-11-13 12:43:39 -0800150 // don't insert this ts into mTimestamps ringbuffer. If we are still
151 // in the learning phase we should just clear all timestamps and start
152 // over.
153 if (mTimestamps.size() < kMinimumSamplesForPrediction) {
Ady Abraham4c56b642021-06-08 15:03:33 -0700154 // Add the timestamp to mTimestamps before clearing it so we could
155 // update mKnownTimestamp based on the new timestamp.
156 mTimestamps.push_back(timestamp);
Ady Abraham9ee31132024-08-06 16:44:08 +0000157
158 // Do not clear timelines as we don't want to break the phase while
159 // we are still learning.
160 clearTimestamps(/* clearTimelines */ false);
Ady Abraham43a3e692020-11-13 12:43:39 -0800161 } else if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700162 mKnownTimestamp =
163 std::max(timestamp, *std::max_element(mTimestamps.begin(), mTimestamps.end()));
164 } else {
165 mKnownTimestamp = timestamp;
166 }
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000167 SFTRACE_FORMAT_INSTANT("timestamp rejected. mKnownTimestamp was %.2fms ago",
168 (mClock->now() - *mKnownTimestamp) / 1e6f);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800169 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700170 }
171
Ady Abraham92fa2f42020-02-11 15:33:56 -0800172 if (mTimestamps.size() != kHistorySize) {
173 mTimestamps.push_back(timestamp);
174 mLastTimestampIndex = next(mLastTimestampIndex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700175 } else {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800176 mLastTimestampIndex = next(mLastTimestampIndex);
177 mTimestamps[mLastTimestampIndex] = timestamp;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700178 }
179
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800180 traceInt64If("VSP-ts", timestamp);
181
Dominik Laskowski62eff352021-12-06 09:59:41 -0800182 const size_t numSamples = mTimestamps.size();
183 if (numSamples < kMinimumSamplesForPrediction) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800184 mRateMap[idealPeriod()] = {idealPeriod(), 0};
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800185 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700186 }
187
188 // This is a 'simple linear regression' calculation of Y over X, with Y being the
189 // vsync timestamps, and X being the ordinal of vsync count.
190 // The calculated slope is the vsync period.
191 // Formula for reference:
192 // Sigma_i: means sum over all timestamps.
193 // mean(variable): statistical mean of variable.
194 // X: snapped ordinal of the timestamp
195 // Y: vsync timestamp
196 //
197 // Sigma_i( (X_i - mean(X)) * (Y_i - mean(Y) )
198 // slope = -------------------------------------------
199 // Sigma_i ( X_i - mean(X) ) ^ 2
200 //
201 // intercept = mean(Y) - slope * mean(X)
202 //
Dominik Laskowski62eff352021-12-06 09:59:41 -0800203 std::vector<nsecs_t> vsyncTS(numSamples);
204 std::vector<nsecs_t> ordinals(numSamples);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700205
Dominik Laskowski62eff352021-12-06 09:59:41 -0800206 // Normalizing to the oldest timestamp cuts down on error in calculating the intercept.
207 const auto oldestTS = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Ady Abrahamc585dba2023-11-15 18:41:35 -0800208 auto it = mRateMap.find(idealPeriod());
Ady Abraham0bb6a472020-10-12 10:22:13 -0700209 auto const currentPeriod = it->second.slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700210
Dominik Laskowski62eff352021-12-06 09:59:41 -0800211 // The mean of the ordinals must be precise for the intercept calculation, so scale them up for
212 // fixed-point arithmetic.
213 constexpr int64_t kScalingFactor = 1000;
214
215 nsecs_t meanTS = 0;
216 nsecs_t meanOrdinal = 0;
217
218 for (size_t i = 0; i < numSamples; i++) {
Dominik Laskowski62eff352021-12-06 09:59:41 -0800219 const auto timestamp = mTimestamps[i] - oldestTS;
220 vsyncTS[i] = timestamp;
221 meanTS += timestamp;
222
Rachel Lee934017e2022-08-10 15:34:14 -0700223 const auto ordinal = currentPeriod == 0
224 ? 0
225 : (vsyncTS[i] + currentPeriod / 2) / currentPeriod * kScalingFactor;
Dominik Laskowski62eff352021-12-06 09:59:41 -0800226 ordinals[i] = ordinal;
227 meanOrdinal += ordinal;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700228 }
229
Dominik Laskowski62eff352021-12-06 09:59:41 -0800230 meanTS /= numSamples;
231 meanOrdinal /= numSamples;
232
233 for (size_t i = 0; i < numSamples; i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700234 vsyncTS[i] -= meanTS;
235 ordinals[i] -= meanOrdinal;
236 }
237
Dominik Laskowski62eff352021-12-06 09:59:41 -0800238 nsecs_t top = 0;
239 nsecs_t bottom = 0;
240 for (size_t i = 0; i < numSamples; i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700241 top += vsyncTS[i] * ordinals[i];
242 bottom += ordinals[i] * ordinals[i];
243 }
244
245 if (CC_UNLIKELY(bottom == 0)) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800246 it->second = {idealPeriod(), 0};
Ady Abraham9ee31132024-08-06 16:44:08 +0000247 clearTimestamps(/* clearTimelines */ true);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800248 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700249 }
250
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700251 nsecs_t const anticipatedPeriod = top * kScalingFactor / bottom;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700252 nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
253
Ady Abrahamc585dba2023-11-15 18:41:35 -0800254 auto const percent = std::abs(anticipatedPeriod - idealPeriod()) * kMaxPercent / idealPeriod();
Ady Abraham92fa2f42020-02-11 15:33:56 -0800255 if (percent >= kOutlierTolerancePercent) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800256 it->second = {idealPeriod(), 0};
Ady Abraham9ee31132024-08-06 16:44:08 +0000257 clearTimestamps(/* clearTimelines */ true);
Ady Abraham92fa2f42020-02-11 15:33:56 -0800258 return false;
259 }
260
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800261 traceInt64If("VSP-period", anticipatedPeriod);
262 traceInt64If("VSP-intercept", intercept);
263
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700264 it->second = {anticipatedPeriod, intercept};
265
Leon Scroggins III67388622023-02-06 20:36:20 -0500266 ALOGV("model update ts %" PRIu64 ": %" PRId64 " slope: %" PRId64 " intercept: %" PRId64,
267 mId.value, timestamp, anticipatedPeriod, intercept);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800268 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700269}
270
Ady Abraham4335afd2023-12-18 19:10:47 -0800271nsecs_t VSyncPredictor::snapToVsync(nsecs_t timePoint) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700272 auto const [slope, intercept] = getVSyncPredictionModelLocked();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700273
Ady Abraham92fa2f42020-02-11 15:33:56 -0800274 if (mTimestamps.empty()) {
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800275 traceInt64("VSP-mode", 1);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700276 auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800277 auto const numPeriodsOut = ((timePoint - knownTimestamp) / idealPeriod()) + 1;
278 return knownTimestamp + numPeriodsOut * idealPeriod();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700279 }
280
Ady Abraham92fa2f42020-02-11 15:33:56 -0800281 auto const oldest = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois127a2d92019-12-04 13:52:52 -0800282
283 // See b/145667109, the ordinal calculation must take into account the intercept.
284 auto const zeroPoint = oldest + intercept;
285 auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700286 auto const prediction = (ordinalRequest * slope) + intercept + oldest;
287
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800288 traceInt64("VSP-mode", 0);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800289 traceInt64If("VSP-timePoint", timePoint);
290 traceInt64If("VSP-prediction", prediction);
291
Kevin DuBois127a2d92019-12-04 13:52:52 -0800292 auto const printer = [&, slope = slope, intercept = intercept] {
293 std::stringstream str;
294 str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
295 << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
296 << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
297 return str.str();
298 };
299
300 ALOGV("%s", printer().c_str());
301 LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
302 printer().c_str());
303
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700304 return prediction;
305}
306
Ady Abraham4335afd2023-12-18 19:10:47 -0800307nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint,
Ady Abraham20024aa2024-03-05 01:32:49 +0000308 std::optional<nsecs_t> lastVsyncOpt) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000309 SFTRACE_CALL();
Ady Abraham9c53ee72020-07-22 21:16:18 -0700310 std::lock_guard lock(mMutex);
Ady Abrahamace3d052022-11-17 16:25:05 -0800311
Ady Abraham20024aa2024-03-05 01:32:49 +0000312 const auto now = TimePoint::fromNs(mClock->now());
313 purgeTimelines(now);
Ady Abrahamf34a8132023-02-13 20:49:48 -0800314
Ady Abrahamee6365b2024-03-06 14:31:45 -0800315 if (lastVsyncOpt && *lastVsyncOpt > timePoint) {
316 timePoint = *lastVsyncOpt;
317 }
318
Ady Abraham77b4fb12024-03-05 17:51:53 -0800319 const auto model = getVSyncPredictionModelLocked();
320 const auto threshold = model.slope / 2;
Ady Abraham940b7a62024-03-07 10:04:27 -0800321 std::optional<Period> minFramePeriodOpt;
322
323 if (mNumVsyncsForFrame > 1) {
324 minFramePeriodOpt = minFramePeriodLocked();
325 }
326
Ady Abraham20024aa2024-03-05 01:32:49 +0000327 std::optional<TimePoint> vsyncOpt;
328 for (auto& timeline : mTimelines) {
Ady Abraham940b7a62024-03-07 10:04:27 -0800329 vsyncOpt = timeline.nextAnticipatedVSyncTimeFrom(model, minFramePeriodOpt,
Ady Abraham20024aa2024-03-05 01:32:49 +0000330 snapToVsync(timePoint), mMissedVsync,
Ady Abraham77b4fb12024-03-05 17:51:53 -0800331 lastVsyncOpt ? snapToVsync(*lastVsyncOpt -
332 threshold)
333 : lastVsyncOpt);
Ady Abraham20024aa2024-03-05 01:32:49 +0000334 if (vsyncOpt) {
335 break;
Ady Abrahame9883032023-11-20 17:54:54 -0800336 }
Ady Abraham20024aa2024-03-05 01:32:49 +0000337 }
338 LOG_ALWAYS_FATAL_IF(!vsyncOpt);
Ady Abrahame9883032023-11-20 17:54:54 -0800339
Ady Abraham20024aa2024-03-05 01:32:49 +0000340 if (*vsyncOpt > mLastCommittedVsync) {
341 mLastCommittedVsync = *vsyncOpt;
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000342 SFTRACE_FORMAT_INSTANT("mLastCommittedVsync in %.2fms",
343 float(mLastCommittedVsync.ns() - mClock->now()) / 1e6f);
Ady Abrahamace3d052022-11-17 16:25:05 -0800344 }
Ady Abrahamf34a8132023-02-13 20:49:48 -0800345
Ady Abraham20024aa2024-03-05 01:32:49 +0000346 return vsyncOpt->ns();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700347}
348
Ady Abraham0bb6a472020-10-12 10:22:13 -0700349/*
Ady Abraham5cc2e262021-03-25 13:09:17 -0700350 * Returns whether a given vsync timestamp is in phase with a frame rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800351 * If the frame rate is not a divisor of the refresh rate, it is always considered in phase.
Ady Abraham5cc2e262021-03-25 13:09:17 -0700352 * For example, if the vsync timestamps are (16.6,33.3,50.0,66.6):
353 * isVSyncInPhase(16.6, 30) = true
354 * isVSyncInPhase(33.3, 30) = false
355 * isVSyncInPhase(50.0, 30) = true
Ady Abraham0bb6a472020-10-12 10:22:13 -0700356 */
Ady Abraham20024aa2024-03-05 01:32:49 +0000357bool VSyncPredictor::isVSyncInPhase(nsecs_t timePoint, Fps frameRate) {
358 if (timePoint == 0) {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700359 return true;
360 }
361
Ady Abraham20024aa2024-03-05 01:32:49 +0000362 std::lock_guard lock(mMutex);
363 const auto model = getVSyncPredictionModelLocked();
364 const nsecs_t period = model.slope;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700365 const nsecs_t justBeforeTimePoint = timePoint - period / 2;
Ady Abraham20024aa2024-03-05 01:32:49 +0000366 const auto now = TimePoint::fromNs(mClock->now());
367 const auto vsync = snapToVsync(justBeforeTimePoint);
368
369 purgeTimelines(now);
370
371 for (auto& timeline : mTimelines) {
ramindani548f4492024-06-13 10:29:04 -0700372 const bool isVsyncValid = FlagManager::getInstance().vrr_bugfix_24q4()
373 ? timeline.isWithin(TimePoint::fromNs(vsync)) ==
374 VsyncTimeline::VsyncOnTimeline::Unique
375 : timeline.validUntil() && timeline.validUntil()->ns() > vsync;
376 if (isVsyncValid) {
Ady Abraham20024aa2024-03-05 01:32:49 +0000377 return timeline.isVSyncInPhase(model, vsync, frameRate);
378 }
379 }
380
381 // The last timeline should always be valid
382 return mTimelines.back().isVSyncInPhase(model, vsync, frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700383}
384
Ady Abrahamee6365b2024-03-06 14:31:45 -0800385void VSyncPredictor::setRenderRate(Fps renderRate, bool applyImmediately) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000386 SFTRACE_FORMAT("%s %s", __func__, to_string(renderRate).c_str());
Ady Abrahamc585dba2023-11-15 18:41:35 -0800387 ALOGV("%s %s: RenderRate %s ", __func__, to_string(mId).c_str(), to_string(renderRate).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800388 std::lock_guard lock(mMutex);
Ady Abraham77b4fb12024-03-05 17:51:53 -0800389 const auto prevRenderRate = mRenderRateOpt;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800390 mRenderRateOpt = renderRate;
Ady Abraham77b4fb12024-03-05 17:51:53 -0800391 const auto renderPeriodDelta =
392 prevRenderRate ? prevRenderRate->getPeriodNsecs() - renderRate.getPeriodNsecs() : 0;
Ady Abraham4fc2fce2024-03-08 06:43:44 +0000393 if (applyImmediately) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000394 SFTRACE_FORMAT_INSTANT("applyImmediately");
Ady Abraham4fc2fce2024-03-08 06:43:44 +0000395 while (mTimelines.size() > 1) {
396 mTimelines.pop_front();
397 }
398
399 mTimelines.front().setRenderRate(renderRate);
Ady Abraham45ed7a82024-03-14 17:36:22 -0700400 return;
401 }
402
403 const bool newRenderRateIsHigher = renderPeriodDelta > renderRate.getPeriodNsecs() &&
404 mLastCommittedVsync.ns() - mClock->now() > 2 * renderRate.getPeriodNsecs();
405 if (newRenderRateIsHigher) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000406 SFTRACE_FORMAT_INSTANT("newRenderRateIsHigher");
Ady Abraham77b4fb12024-03-05 17:51:53 -0800407 mTimelines.clear();
408 mLastCommittedVsync = TimePoint::fromNs(0);
Ady Abraham4fc2fce2024-03-08 06:43:44 +0000409
Ady Abraham77b4fb12024-03-05 17:51:53 -0800410 } else {
ramindani548f4492024-06-13 10:29:04 -0700411 if (FlagManager::getInstance().vrr_bugfix_24q4()) {
ramindani62007522024-06-28 11:17:12 -0700412 // We need to freeze the timeline at the committed vsync, and
413 // then use with threshold adjustments when required to avoid
414 // marginal errors when checking the vsync on the timeline.
ramindani548f4492024-06-13 10:29:04 -0700415 mTimelines.back().freeze(mLastCommittedVsync);
416 } else {
417 mTimelines.back().freeze(
418 TimePoint::fromNs(mLastCommittedVsync.ns() + mIdealPeriod.ns() / 2));
419 }
Ady Abraham77b4fb12024-03-05 17:51:53 -0800420 }
421 mTimelines.emplace_back(mLastCommittedVsync, mIdealPeriod, renderRate);
Ady Abraham20024aa2024-03-05 01:32:49 +0000422 purgeTimelines(TimePoint::fromNs(mClock->now()));
Ady Abrahamc585dba2023-11-15 18:41:35 -0800423}
424
425void VSyncPredictor::setDisplayModePtr(ftl::NonNull<DisplayModePtr> modePtr) {
426 LOG_ALWAYS_FATAL_IF(mId != modePtr->getPhysicalDisplayId(),
427 "mode does not belong to the display");
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000428 SFTRACE_FORMAT("%s %s", __func__, to_string(*modePtr).c_str());
Ady Abrahamc585dba2023-11-15 18:41:35 -0800429 const auto timeout = modePtr->getVrrConfig()
430 ? modePtr->getVrrConfig()->notifyExpectedPresentConfig
431 : std::nullopt;
432 ALOGV("%s %s: DisplayMode %s notifyExpectedPresentTimeout %s", __func__, to_string(mId).c_str(),
433 to_string(*modePtr).c_str(),
ramindanicbd7a6d2023-12-19 16:00:30 -0800434 timeout ? std::to_string(timeout->timeoutNs).c_str() : "N/A");
Ady Abrahamc585dba2023-11-15 18:41:35 -0800435 std::lock_guard lock(mMutex);
436
Ady Abraham9ee31132024-08-06 16:44:08 +0000437 // do not clear the timelines on VRR displays if we didn't change the mode
438 const bool isVrr = modePtr->getVrrConfig().has_value();
439 const bool clearTimelines = !isVrr || mDisplayModePtr->getId() != modePtr->getId();
Ady Abrahamc585dba2023-11-15 18:41:35 -0800440 mDisplayModePtr = modePtr;
Ady Abraham940b7a62024-03-07 10:04:27 -0800441 mNumVsyncsForFrame = numVsyncsPerFrame(mDisplayModePtr);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800442 traceInt64("VSP-setPeriod", modePtr->getVsyncRate().getPeriodNsecs());
443
444 static constexpr size_t kSizeLimit = 30;
445 if (CC_UNLIKELY(mRateMap.size() == kSizeLimit)) {
446 mRateMap.erase(mRateMap.begin());
447 }
448
449 if (mRateMap.find(idealPeriod()) == mRateMap.end()) {
450 mRateMap[idealPeriod()] = {idealPeriod(), 0};
451 }
452
Ady Abraham9ee31132024-08-06 16:44:08 +0000453 if (clearTimelines) {
454 mTimelines.clear();
455 }
456 clearTimestamps(clearTimelines);
Ady Abrahamace3d052022-11-17 16:25:05 -0800457}
458
Ady Abraham20024aa2024-03-05 01:32:49 +0000459Duration VSyncPredictor::ensureMinFrameDurationIsKept(TimePoint expectedPresentTime,
460 TimePoint lastConfirmedPresentTime) {
Ady Abraham7abbc352024-11-19 16:19:28 -0800461 SFTRACE_FORMAT("%s mNumVsyncsForFrame=%d mPastExpectedPresentTimes.size()=%zu", __func__,
462 mNumVsyncsForFrame, mPastExpectedPresentTimes.size());
Ady Abraham940b7a62024-03-07 10:04:27 -0800463
464 if (mNumVsyncsForFrame <= 1) {
465 return 0ns;
466 }
467
Ady Abrahame9883032023-11-20 17:54:54 -0800468 const auto currentPeriod = mRateMap.find(idealPeriod())->second.slope;
469 const auto threshold = currentPeriod / 2;
ramindani3614e0b2024-07-18 18:44:33 -0700470 const auto minFramePeriod = minFramePeriodLocked();
Ady Abrahame9883032023-11-20 17:54:54 -0800471
472 auto prev = lastConfirmedPresentTime.ns();
473 for (auto& current : mPastExpectedPresentTimes) {
Ady Abraham7abbc352024-11-19 16:19:28 -0800474 SFTRACE_FORMAT_INSTANT("current %.2f past last signaled fence",
475 static_cast<float>(current.ns() - prev) / 1e6f);
Ady Abrahame9883032023-11-20 17:54:54 -0800476
ramindani3614e0b2024-07-18 18:44:33 -0700477 const auto minPeriodViolation = current.ns() - prev + threshold < minFramePeriod.ns();
Ady Abrahame9883032023-11-20 17:54:54 -0800478 if (minPeriodViolation) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000479 SFTRACE_NAME("minPeriodViolation");
ramindani3614e0b2024-07-18 18:44:33 -0700480 current = TimePoint::fromNs(prev + minFramePeriod.ns());
Ady Abrahame9883032023-11-20 17:54:54 -0800481 prev = current.ns();
482 } else {
483 break;
484 }
485 }
486
487 if (!mPastExpectedPresentTimes.empty()) {
488 const auto phase = Duration(mPastExpectedPresentTimes.back() - expectedPresentTime);
489 if (phase > 0ns) {
Ady Abraham20024aa2024-03-05 01:32:49 +0000490 for (auto& timeline : mTimelines) {
ramindani3614e0b2024-07-18 18:44:33 -0700491 timeline.shiftVsyncSequence(phase, minFramePeriod);
Ady Abrahame9883032023-11-20 17:54:54 -0800492 }
Ady Abraham4335afd2023-12-18 19:10:47 -0800493 mPastExpectedPresentTimes.clear();
Ady Abraham20024aa2024-03-05 01:32:49 +0000494 return phase;
Ady Abrahame9883032023-11-20 17:54:54 -0800495 }
496 }
Ady Abraham20024aa2024-03-05 01:32:49 +0000497
498 return 0ns;
Ady Abrahame9883032023-11-20 17:54:54 -0800499}
500
ramindani7b32b3a2024-07-02 10:17:47 -0700501void VSyncPredictor::onFrameBegin(TimePoint expectedPresentTime, FrameTime lastSignaledFrameTime) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000502 SFTRACE_NAME("VSyncPredictor::onFrameBegin");
Ady Abrahame9883032023-11-20 17:54:54 -0800503 std::lock_guard lock(mMutex);
504
505 if (!mDisplayModePtr->getVrrConfig()) return;
506
ramindani7b32b3a2024-07-02 10:17:47 -0700507 const auto [lastConfirmedPresentTime, lastConfirmedExpectedPresentTime] = lastSignaledFrameTime;
Ady Abrahame9883032023-11-20 17:54:54 -0800508 if (CC_UNLIKELY(mTraceOn)) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000509 SFTRACE_FORMAT_INSTANT("vsync is %.2f past last signaled fence",
510 static_cast<float>(expectedPresentTime.ns() -
511 lastConfirmedPresentTime.ns()) /
512 1e6f);
Ady Abrahame9883032023-11-20 17:54:54 -0800513 }
Ady Abrahame9883032023-11-20 17:54:54 -0800514 const auto currentPeriod = mRateMap.find(idealPeriod())->second.slope;
515 const auto threshold = currentPeriod / 2;
Ady Abraham4335afd2023-12-18 19:10:47 -0800516 mPastExpectedPresentTimes.push_back(expectedPresentTime);
Ady Abrahame9883032023-11-20 17:54:54 -0800517
Ady Abrahame9883032023-11-20 17:54:54 -0800518 while (!mPastExpectedPresentTimes.empty()) {
519 const auto front = mPastExpectedPresentTimes.front().ns();
Ady Abraham4335afd2023-12-18 19:10:47 -0800520 const bool frontIsBeforeConfirmed = front < lastConfirmedPresentTime.ns() + threshold;
521 if (frontIsBeforeConfirmed) {
Ady Abraham7abbc352024-11-19 16:19:28 -0800522 SFTRACE_FORMAT_INSTANT("Discarding old vsync - %.2f before last signaled fence",
523 static_cast<float>(lastConfirmedPresentTime.ns() - front) /
524 1e6f);
Ady Abrahame9883032023-11-20 17:54:54 -0800525 mPastExpectedPresentTimes.pop_front();
526 } else {
527 break;
528 }
529 }
530
ramindani7b32b3a2024-07-02 10:17:47 -0700531 if (lastConfirmedExpectedPresentTime.ns() - lastConfirmedPresentTime.ns() > threshold) {
532 SFTRACE_FORMAT_INSTANT("lastFramePresentedEarly");
533 return;
534 }
535
Ady Abraham20024aa2024-03-05 01:32:49 +0000536 const auto phase = ensureMinFrameDurationIsKept(expectedPresentTime, lastConfirmedPresentTime);
537 if (phase > 0ns) {
538 mMissedVsync = {expectedPresentTime, minFramePeriodLocked()};
539 }
Ady Abrahame9883032023-11-20 17:54:54 -0800540}
541
542void VSyncPredictor::onFrameMissed(TimePoint expectedPresentTime) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000543 SFTRACE_NAME("VSyncPredictor::onFrameMissed");
Ady Abrahame9883032023-11-20 17:54:54 -0800544
545 std::lock_guard lock(mMutex);
546 if (!mDisplayModePtr->getVrrConfig()) return;
547
548 // We don't know when the frame is going to be presented, so we assume it missed one vsync
549 const auto currentPeriod = mRateMap.find(idealPeriod())->second.slope;
550 const auto lastConfirmedPresentTime =
551 TimePoint::fromNs(expectedPresentTime.ns() + currentPeriod);
552
Ady Abraham20024aa2024-03-05 01:32:49 +0000553 const auto phase = ensureMinFrameDurationIsKept(expectedPresentTime, lastConfirmedPresentTime);
554 if (phase > 0ns) {
555 mMissedVsync = {expectedPresentTime, Duration::fromNs(0)};
556 }
Ady Abrahame9883032023-11-20 17:54:54 -0800557}
558
Ady Abraham0bb6a472020-10-12 10:22:13 -0700559VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModel() const {
560 std::lock_guard lock(mMutex);
Ady Abraham20024aa2024-03-05 01:32:49 +0000561 return VSyncPredictor::getVSyncPredictionModelLocked();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700562}
563
564VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModelLocked() const {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800565 return mRateMap.find(idealPeriod())->second;
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800566}
567
Ady Abraham9ee31132024-08-06 16:44:08 +0000568void VSyncPredictor::clearTimestamps(bool clearTimelines) {
569 SFTRACE_FORMAT("%s: clearTimelines=%d", __func__, clearTimelines);
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000570
Ady Abraham92fa2f42020-02-11 15:33:56 -0800571 if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700572 auto const maxRb = *std::max_element(mTimestamps.begin(), mTimestamps.end());
573 if (mKnownTimestamp) {
574 mKnownTimestamp = std::max(*mKnownTimestamp, maxRb);
Ady Abraham9ee31132024-08-06 16:44:08 +0000575 SFTRACE_FORMAT_INSTANT("mKnownTimestamp was %.2fms ago",
576 (mClock->now() - *mKnownTimestamp) / 1e6f);
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700577 } else {
578 mKnownTimestamp = maxRb;
Ady Abraham9ee31132024-08-06 16:44:08 +0000579 SFTRACE_FORMAT_INSTANT("mKnownTimestamp (maxRb) was %.2fms ago",
580 (mClock->now() - *mKnownTimestamp) / 1e6f);
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700581 }
582
Ady Abraham92fa2f42020-02-11 15:33:56 -0800583 mTimestamps.clear();
584 mLastTimestampIndex = 0;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700585 }
Ady Abraham20024aa2024-03-05 01:32:49 +0000586
Ady Abraham20024aa2024-03-05 01:32:49 +0000587 mIdealPeriod = Period::fromNs(idealPeriod());
Ady Abrahamc5d72462024-03-23 23:56:33 +0000588 if (mTimelines.empty()) {
589 mLastCommittedVsync = TimePoint::fromNs(0);
590 mTimelines.emplace_back(mLastCommittedVsync, mIdealPeriod, mRenderRateOpt);
Ady Abraham9ee31132024-08-06 16:44:08 +0000591 } else if (clearTimelines) {
Ady Abrahamc5d72462024-03-23 23:56:33 +0000592 while (mTimelines.size() > 1) {
593 mTimelines.pop_front();
594 }
595 mTimelines.front().setRenderRate(mRenderRateOpt);
596 // set mLastCommittedVsync to a valid vsync but don't commit too much in the future
597 const auto vsyncOpt = mTimelines.front().nextAnticipatedVSyncTimeFrom(
598 getVSyncPredictionModelLocked(),
599 /* minFramePeriodOpt */ std::nullopt,
600 snapToVsync(mClock->now()), MissedVsync{},
601 /* lastVsyncOpt */ std::nullopt);
602 mLastCommittedVsync = *vsyncOpt;
603 }
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700604}
605
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700606bool VSyncPredictor::needsMoreSamples() const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700607 std::lock_guard lock(mMutex);
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700608 return mTimestamps.size() < kMinimumSamplesForPrediction;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700609}
610
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800611void VSyncPredictor::resetModel() {
Ady Abraham9ee31132024-08-06 16:44:08 +0000612 SFTRACE_CALL();
Ady Abraham9c53ee72020-07-22 21:16:18 -0700613 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800614 mRateMap[idealPeriod()] = {idealPeriod(), 0};
Ady Abraham9ee31132024-08-06 16:44:08 +0000615 clearTimestamps(/* clearTimelines */ true);
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800616}
617
Ady Abraham5e7371c2020-03-24 14:47:24 -0700618void VSyncPredictor::dump(std::string& result) const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700619 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800620 StringAppendF(&result, "\tmDisplayModePtr=%s\n", to_string(*mDisplayModePtr).c_str());
Ady Abraham5e7371c2020-03-24 14:47:24 -0700621 StringAppendF(&result, "\tRefresh Rate Map:\n");
Ady Abrahamc585dba2023-11-15 18:41:35 -0800622 for (const auto& [period, periodInterceptTuple] : mRateMap) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700623 StringAppendF(&result,
624 "\t\tFor ideal period %.2fms: period = %.2fms, intercept = %" PRId64 "\n",
Ady Abrahamc585dba2023-11-15 18:41:35 -0800625 period / 1e6f, periodInterceptTuple.slope / 1e6f,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700626 periodInterceptTuple.intercept);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700627 }
Ady Abraham20024aa2024-03-05 01:32:49 +0000628 StringAppendF(&result, "\tmTimelines.size()=%zu\n", mTimelines.size());
629}
630
631void VSyncPredictor::purgeTimelines(android::TimePoint now) {
Ady Abraham77b4fb12024-03-05 17:51:53 -0800632 const auto kEnoughFramesToBreakPhase = 5;
633 if (mRenderRateOpt &&
634 mLastCommittedVsync.ns() + mRenderRateOpt->getPeriodNsecs() * kEnoughFramesToBreakPhase <
635 mClock->now()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000636 SFTRACE_FORMAT_INSTANT("kEnoughFramesToBreakPhase");
Ady Abraham77b4fb12024-03-05 17:51:53 -0800637 mTimelines.clear();
638 mLastCommittedVsync = TimePoint::fromNs(0);
639 mTimelines.emplace_back(mLastCommittedVsync, mIdealPeriod, mRenderRateOpt);
640 return;
641 }
642
Ady Abraham20024aa2024-03-05 01:32:49 +0000643 while (mTimelines.size() > 1) {
644 const auto validUntilOpt = mTimelines.front().validUntil();
ramindani548f4492024-06-13 10:29:04 -0700645 const bool isTimelineOutDated = FlagManager::getInstance().vrr_bugfix_24q4()
646 ? mTimelines.front().isWithin(now) == VsyncTimeline::VsyncOnTimeline::Outside
647 : validUntilOpt && *validUntilOpt < now;
648 if (isTimelineOutDated) {
Ady Abraham20024aa2024-03-05 01:32:49 +0000649 mTimelines.pop_front();
650 } else {
651 break;
652 }
653 }
654 LOG_ALWAYS_FATAL_IF(mTimelines.empty());
655 LOG_ALWAYS_FATAL_IF(mTimelines.back().validUntil().has_value());
656}
657
Ady Abraham77b4fb12024-03-05 17:51:53 -0800658auto VSyncPredictor::VsyncTimeline::makeVsyncSequence(TimePoint knownVsync)
659 -> std::optional<VsyncSequence> {
660 if (knownVsync.ns() == 0) return std::nullopt;
661 return std::make_optional<VsyncSequence>({knownVsync.ns(), 0});
662}
663
664VSyncPredictor::VsyncTimeline::VsyncTimeline(TimePoint knownVsync, Period idealPeriod,
665 std::optional<Fps> renderRateOpt)
666 : mIdealPeriod(idealPeriod),
667 mRenderRateOpt(renderRateOpt),
668 mLastVsyncSequence(makeVsyncSequence(knownVsync)) {}
Ady Abraham20024aa2024-03-05 01:32:49 +0000669
670void VSyncPredictor::VsyncTimeline::freeze(TimePoint lastVsync) {
671 LOG_ALWAYS_FATAL_IF(mValidUntil.has_value());
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000672 SFTRACE_FORMAT_INSTANT("renderRate %s valid for %.2f",
673 mRenderRateOpt ? to_string(*mRenderRateOpt).c_str() : "NA",
674 float(lastVsync.ns() - TimePoint::now().ns()) / 1e6f);
Ady Abraham20024aa2024-03-05 01:32:49 +0000675 mValidUntil = lastVsync;
676}
677
678std::optional<TimePoint> VSyncPredictor::VsyncTimeline::nextAnticipatedVSyncTimeFrom(
Ady Abraham940b7a62024-03-07 10:04:27 -0800679 Model model, std::optional<Period> minFramePeriodOpt, nsecs_t vsync,
680 MissedVsync missedVsync, std::optional<nsecs_t> lastVsyncOpt) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000681 SFTRACE_FORMAT("renderRate %s", mRenderRateOpt ? to_string(*mRenderRateOpt).c_str() : "NA");
Ady Abraham20024aa2024-03-05 01:32:49 +0000682
Ady Abrahame54ce102024-03-04 23:18:38 +0000683 nsecs_t vsyncTime = snapToVsyncAlignedWithRenderRate(model, vsync);
Ady Abraham20024aa2024-03-05 01:32:49 +0000684 const auto threshold = model.slope / 2;
685 const auto lastFrameMissed =
686 lastVsyncOpt && std::abs(*lastVsyncOpt - missedVsync.vsync.ns()) < threshold;
Ady Abrahame9dcf792024-05-14 15:24:54 -0700687 const auto mightBackpressure = minFramePeriodOpt && mRenderRateOpt &&
688 mRenderRateOpt->getPeriod() < 2 * (*minFramePeriodOpt);
689 if (FlagManager::getInstance().vrr_config()) {
690 if (lastFrameMissed) {
691 // If the last frame missed is the last vsync, we already shifted the timeline. Depends
692 // on whether we skipped the frame (onFrameMissed) or not (onFrameBegin) we apply a
ramindanid03639a2024-08-23 13:06:22 -0700693 // different fixup if we are violating the minFramePeriod.
694 // There is no need to shift the vsync timeline again.
695 if (vsyncTime - missedVsync.vsync.ns() < minFramePeriodOpt->ns()) {
696 vsyncTime += missedVsync.fixup.ns();
697 SFTRACE_FORMAT_INSTANT("lastFrameMissed");
698 }
Ady Abrahame9dcf792024-05-14 15:24:54 -0700699 } else if (mightBackpressure && lastVsyncOpt) {
ramindani548f4492024-06-13 10:29:04 -0700700 if (!FlagManager::getInstance().vrr_bugfix_24q4()) {
701 // lastVsyncOpt does not need to be corrected with the new rate, and
702 // it should be used as is to avoid skipping a frame when changing rates are
703 // aligned at vsync time.
704 lastVsyncOpt = snapToVsyncAlignedWithRenderRate(model, *lastVsyncOpt);
705 }
Ady Abrahame9dcf792024-05-14 15:24:54 -0700706 const auto vsyncDiff = vsyncTime - *lastVsyncOpt;
707 if (vsyncDiff <= minFramePeriodOpt->ns() - threshold) {
708 // avoid a duplicate vsync
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000709 SFTRACE_FORMAT_INSTANT("skipping a vsync to avoid duplicate frame. next in %.2f "
710 "which "
711 "is %.2f "
712 "from "
713 "prev. "
714 "adjust by %.2f",
715 static_cast<float>(vsyncTime - TimePoint::now().ns()) / 1e6f,
716 static_cast<float>(vsyncDiff) / 1e6f,
717 static_cast<float>(mRenderRateOpt->getPeriodNsecs()) / 1e6f);
Ady Abrahame9dcf792024-05-14 15:24:54 -0700718 vsyncTime += mRenderRateOpt->getPeriodNsecs();
719 }
Ady Abrahame54ce102024-03-04 23:18:38 +0000720 }
Ady Abraham20024aa2024-03-05 01:32:49 +0000721 }
722
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000723 SFTRACE_FORMAT_INSTANT("vsync in %.2fms", float(vsyncTime - TimePoint::now().ns()) / 1e6f);
ramindani548f4492024-06-13 10:29:04 -0700724 const bool isVsyncInvalid = FlagManager::getInstance().vrr_bugfix_24q4()
725 ? isWithin(TimePoint::fromNs(vsyncTime)) == VsyncOnTimeline::Outside
726 : mValidUntil && vsyncTime > mValidUntil->ns();
727 if (isVsyncInvalid) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000728 SFTRACE_FORMAT_INSTANT("no longer valid for vsync in %.2f",
729 static_cast<float>(vsyncTime - TimePoint::now().ns()) / 1e6f);
Ady Abraham20024aa2024-03-05 01:32:49 +0000730 return std::nullopt;
731 }
732
Ady Abraham20024aa2024-03-05 01:32:49 +0000733 return TimePoint::fromNs(vsyncTime);
734}
735
736auto VSyncPredictor::VsyncTimeline::getVsyncSequenceLocked(Model model, nsecs_t vsync)
737 -> VsyncSequence {
738 if (!mLastVsyncSequence) return {vsync, 0};
739
740 const auto [lastVsyncTime, lastVsyncSequence] = *mLastVsyncSequence;
741 const auto vsyncSequence = lastVsyncSequence +
742 static_cast<int64_t>(std::round((vsync - lastVsyncTime) /
743 static_cast<float>(model.slope)));
744 return {vsync, vsyncSequence};
745}
746
747nsecs_t VSyncPredictor::VsyncTimeline::snapToVsyncAlignedWithRenderRate(Model model,
748 nsecs_t vsync) {
749 // update the mLastVsyncSequence for reference point
750 mLastVsyncSequence = getVsyncSequenceLocked(model, vsync);
751
752 const auto renderRatePhase = [&]() -> int {
753 if (!mRenderRateOpt) return 0;
754 const auto divisor =
755 RefreshRateSelector::getFrameRateDivisor(Fps::fromPeriodNsecs(mIdealPeriod.ns()),
756 *mRenderRateOpt);
757 if (divisor <= 1) return 0;
758
759 int mod = mLastVsyncSequence->seq % divisor;
760 if (mod == 0) return 0;
761
762 // This is actually a bug fix, but guarded with vrr_config since we found it with this
763 // config
764 if (FlagManager::getInstance().vrr_config()) {
765 if (mod < 0) mod += divisor;
766 }
767
768 return divisor - mod;
769 }();
770
771 if (renderRatePhase == 0) {
772 return mLastVsyncSequence->vsyncTime;
773 }
774
775 return mLastVsyncSequence->vsyncTime + model.slope * renderRatePhase;
776}
777
778bool VSyncPredictor::VsyncTimeline::isVSyncInPhase(Model model, nsecs_t vsync, Fps frameRate) {
779 const auto getVsyncIn = [](TimePoint now, nsecs_t timePoint) -> float {
780 return ticks<std::milli, float>(TimePoint::fromNs(timePoint) - now);
781 };
782
Ady Abraham4a719e82024-06-06 12:12:09 -0700783 Fps displayFps = !FlagManager::getInstance().vrr_bugfix_24q4() && mRenderRateOpt
784 ? *mRenderRateOpt
785 : Fps::fromPeriodNsecs(mIdealPeriod.ns());
Ady Abraham20024aa2024-03-05 01:32:49 +0000786 const auto divisor = RefreshRateSelector::getFrameRateDivisor(displayFps, frameRate);
787 const auto now = TimePoint::now();
788
789 if (divisor <= 1) {
790 return true;
791 }
792 const auto vsyncSequence = getVsyncSequenceLocked(model, vsync);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000793 SFTRACE_FORMAT_INSTANT("vsync in: %.2f sequence: %" PRId64 " divisor: %zu",
794 getVsyncIn(now, vsyncSequence.vsyncTime), vsyncSequence.seq, divisor);
Ady Abraham20024aa2024-03-05 01:32:49 +0000795 return vsyncSequence.seq % divisor == 0;
796}
797
ramindani3614e0b2024-07-18 18:44:33 -0700798void VSyncPredictor::VsyncTimeline::shiftVsyncSequence(Duration phase, Period minFramePeriod) {
Ady Abraham20024aa2024-03-05 01:32:49 +0000799 if (mLastVsyncSequence) {
ramindani3614e0b2024-07-18 18:44:33 -0700800 const auto renderRate = mRenderRateOpt.value_or(Fps::fromPeriodNsecs(mIdealPeriod.ns()));
801 const auto threshold = mIdealPeriod.ns() / 2;
802 if (renderRate.getPeriodNsecs() - phase.ns() + threshold >= minFramePeriod.ns()) {
803 SFTRACE_FORMAT_INSTANT("Not-Adjusting vsync by %.2f",
804 static_cast<float>(phase.ns()) / 1e6f);
805 return;
806 }
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000807 SFTRACE_FORMAT_INSTANT("adjusting vsync by %.2f", static_cast<float>(phase.ns()) / 1e6f);
Ady Abraham20024aa2024-03-05 01:32:49 +0000808 mLastVsyncSequence->vsyncTime += phase.ns();
809 }
Ady Abraham5e7371c2020-03-24 14:47:24 -0700810}
811
ramindani62007522024-06-28 11:17:12 -0700812VSyncPredictor::VsyncTimeline::VsyncOnTimeline VSyncPredictor::VsyncTimeline::isWithin(
813 TimePoint vsync) {
814 const auto threshold = mIdealPeriod.ns() / 2;
815 if (!mValidUntil || vsync.ns() < mValidUntil->ns() - threshold) {
816 // if mValidUntil is absent then timeline is not frozen and
817 // vsync should be unique to that timeline.
818 return VsyncOnTimeline::Unique;
819 }
820 if (vsync.ns() > mValidUntil->ns() + threshold) {
821 return VsyncOnTimeline::Outside;
822 }
823 return VsyncOnTimeline::Shared;
824}
825
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700826} // namespace android::scheduler
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800827
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100828// TODO(b/129481165): remove the #pragma below and fix conversion issues
Dominik Laskowski62eff352021-12-06 09:59:41 -0800829#pragma clang diagnostic pop // ignored "-Wextra"