blob: 0644acaee27af5e01550680ceca747e7174b5727 [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>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070033#include <cutils/compiler.h>
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080034#include <cutils/properties.h>
Leon Scroggins III67388622023-02-06 20:36:20 -050035#include <ftl/concat.h>
Ady Abraham9243bba2023-02-10 15:31:14 -080036#include <gui/TraceUtils.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 {
Leon Scroggins III67388622023-02-06 20:36:20 -050080 ATRACE_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 Abraham92fa2f42020-02-11 15:33:56 -080092 if (mLastTimestampIndex < 0 || mTimestamps.empty()) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -070093 return true;
94 }
95
Ady Abrahamc585dba2023-11-15 18:41:35 -080096 const auto aValidTimestamp = mTimestamps[mLastTimestampIndex];
97 const auto percent =
98 (timestamp - aValidTimestamp) % idealPeriod() * kMaxPercent / idealPeriod();
Ady Abraham99ca3362021-06-17 12:28:46 -070099 if (percent >= kOutlierTolerancePercent &&
100 percent <= (kMaxPercent - kOutlierTolerancePercent)) {
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000101 ATRACE_FORMAT_INSTANT("timestamp is not aligned with model");
Ady Abraham99ca3362021-06-17 12:28:46 -0700102 return false;
103 }
104
105 const auto iter = std::min_element(mTimestamps.begin(), mTimestamps.end(),
106 [timestamp](nsecs_t a, nsecs_t b) {
107 return std::abs(timestamp - a) < std::abs(timestamp - b);
108 });
Ady Abrahamc585dba2023-11-15 18:41:35 -0800109 const auto distancePercent = std::abs(*iter - timestamp) * kMaxPercent / idealPeriod();
Ady Abraham99ca3362021-06-17 12:28:46 -0700110 if (distancePercent < kOutlierTolerancePercent) {
111 // duplicate timestamp
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000112 ATRACE_FORMAT_INSTANT("duplicate timestamp");
Ady Abraham99ca3362021-06-17 12:28:46 -0700113 return false;
114 }
115 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700116}
117
Kevin DuBois2fd3cea2019-11-14 08:52:45 -0800118nsecs_t VSyncPredictor::currentPeriod() const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700119 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800120 return mRateMap.find(idealPeriod())->second.slope;
Kevin DuBois2fd3cea2019-11-14 08:52:45 -0800121}
122
Ady Abraham3db8a3c2023-11-20 17:53:47 -0800123Period VSyncPredictor::minFramePeriod() const {
124 if (!FlagManager::getInstance().vrr_config()) {
125 return Period::fromNs(currentPeriod());
126 }
127
128 std::lock_guard lock(mMutex);
Ady Abrahame9883032023-11-20 17:54:54 -0800129 return minFramePeriodLocked();
130}
131
132Period VSyncPredictor::minFramePeriodLocked() const {
Ady Abraham3db8a3c2023-11-20 17:53:47 -0800133 const auto slope = mRateMap.find(idealPeriod())->second.slope;
Ady Abraham940b7a62024-03-07 10:04:27 -0800134 return Period::fromNs(slope * mNumVsyncsForFrame);
Ady Abraham3db8a3c2023-11-20 17:53:47 -0800135}
136
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800137bool VSyncPredictor::addVsyncTimestamp(nsecs_t timestamp) {
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000138 ATRACE_CALL();
139
Ady Abraham9c53ee72020-07-22 21:16:18 -0700140 std::lock_guard lock(mMutex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700141
142 if (!validate(timestamp)) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700143 // VSR could elect to ignore the incongruent timestamp or resetModel(). If ts is ignored,
Ady Abraham43a3e692020-11-13 12:43:39 -0800144 // don't insert this ts into mTimestamps ringbuffer. If we are still
145 // in the learning phase we should just clear all timestamps and start
146 // over.
147 if (mTimestamps.size() < kMinimumSamplesForPrediction) {
Ady Abraham4c56b642021-06-08 15:03:33 -0700148 // Add the timestamp to mTimestamps before clearing it so we could
149 // update mKnownTimestamp based on the new timestamp.
150 mTimestamps.push_back(timestamp);
Ady Abraham43a3e692020-11-13 12:43:39 -0800151 clearTimestamps();
152 } else if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700153 mKnownTimestamp =
154 std::max(timestamp, *std::max_element(mTimestamps.begin(), mTimestamps.end()));
155 } else {
156 mKnownTimestamp = timestamp;
157 }
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000158 ATRACE_FORMAT_INSTANT("timestamp rejected. mKnownTimestamp was %.2fms ago",
Ady Abraham20024aa2024-03-05 01:32:49 +0000159 (mClock->now() - *mKnownTimestamp) / 1e6f);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800160 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700161 }
162
Ady Abraham92fa2f42020-02-11 15:33:56 -0800163 if (mTimestamps.size() != kHistorySize) {
164 mTimestamps.push_back(timestamp);
165 mLastTimestampIndex = next(mLastTimestampIndex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700166 } else {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800167 mLastTimestampIndex = next(mLastTimestampIndex);
168 mTimestamps[mLastTimestampIndex] = timestamp;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700169 }
170
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800171 traceInt64If("VSP-ts", timestamp);
172
Dominik Laskowski62eff352021-12-06 09:59:41 -0800173 const size_t numSamples = mTimestamps.size();
174 if (numSamples < kMinimumSamplesForPrediction) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800175 mRateMap[idealPeriod()] = {idealPeriod(), 0};
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800176 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700177 }
178
179 // This is a 'simple linear regression' calculation of Y over X, with Y being the
180 // vsync timestamps, and X being the ordinal of vsync count.
181 // The calculated slope is the vsync period.
182 // Formula for reference:
183 // Sigma_i: means sum over all timestamps.
184 // mean(variable): statistical mean of variable.
185 // X: snapped ordinal of the timestamp
186 // Y: vsync timestamp
187 //
188 // Sigma_i( (X_i - mean(X)) * (Y_i - mean(Y) )
189 // slope = -------------------------------------------
190 // Sigma_i ( X_i - mean(X) ) ^ 2
191 //
192 // intercept = mean(Y) - slope * mean(X)
193 //
Dominik Laskowski62eff352021-12-06 09:59:41 -0800194 std::vector<nsecs_t> vsyncTS(numSamples);
195 std::vector<nsecs_t> ordinals(numSamples);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700196
Dominik Laskowski62eff352021-12-06 09:59:41 -0800197 // Normalizing to the oldest timestamp cuts down on error in calculating the intercept.
198 const auto oldestTS = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Ady Abrahamc585dba2023-11-15 18:41:35 -0800199 auto it = mRateMap.find(idealPeriod());
Ady Abraham0bb6a472020-10-12 10:22:13 -0700200 auto const currentPeriod = it->second.slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700201
Dominik Laskowski62eff352021-12-06 09:59:41 -0800202 // The mean of the ordinals must be precise for the intercept calculation, so scale them up for
203 // fixed-point arithmetic.
204 constexpr int64_t kScalingFactor = 1000;
205
206 nsecs_t meanTS = 0;
207 nsecs_t meanOrdinal = 0;
208
209 for (size_t i = 0; i < numSamples; i++) {
Dominik Laskowski62eff352021-12-06 09:59:41 -0800210 const auto timestamp = mTimestamps[i] - oldestTS;
211 vsyncTS[i] = timestamp;
212 meanTS += timestamp;
213
Rachel Lee934017e2022-08-10 15:34:14 -0700214 const auto ordinal = currentPeriod == 0
215 ? 0
216 : (vsyncTS[i] + currentPeriod / 2) / currentPeriod * kScalingFactor;
Dominik Laskowski62eff352021-12-06 09:59:41 -0800217 ordinals[i] = ordinal;
218 meanOrdinal += ordinal;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700219 }
220
Dominik Laskowski62eff352021-12-06 09:59:41 -0800221 meanTS /= numSamples;
222 meanOrdinal /= numSamples;
223
224 for (size_t i = 0; i < numSamples; i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700225 vsyncTS[i] -= meanTS;
226 ordinals[i] -= meanOrdinal;
227 }
228
Dominik Laskowski62eff352021-12-06 09:59:41 -0800229 nsecs_t top = 0;
230 nsecs_t bottom = 0;
231 for (size_t i = 0; i < numSamples; i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700232 top += vsyncTS[i] * ordinals[i];
233 bottom += ordinals[i] * ordinals[i];
234 }
235
236 if (CC_UNLIKELY(bottom == 0)) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800237 it->second = {idealPeriod(), 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800238 clearTimestamps();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800239 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700240 }
241
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700242 nsecs_t const anticipatedPeriod = top * kScalingFactor / bottom;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700243 nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
244
Ady Abrahamc585dba2023-11-15 18:41:35 -0800245 auto const percent = std::abs(anticipatedPeriod - idealPeriod()) * kMaxPercent / idealPeriod();
Ady Abraham92fa2f42020-02-11 15:33:56 -0800246 if (percent >= kOutlierTolerancePercent) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800247 it->second = {idealPeriod(), 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800248 clearTimestamps();
249 return false;
250 }
251
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800252 traceInt64If("VSP-period", anticipatedPeriod);
253 traceInt64If("VSP-intercept", intercept);
254
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700255 it->second = {anticipatedPeriod, intercept};
256
Leon Scroggins III67388622023-02-06 20:36:20 -0500257 ALOGV("model update ts %" PRIu64 ": %" PRId64 " slope: %" PRId64 " intercept: %" PRId64,
258 mId.value, timestamp, anticipatedPeriod, intercept);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800259 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700260}
261
Ady Abraham4335afd2023-12-18 19:10:47 -0800262nsecs_t VSyncPredictor::snapToVsync(nsecs_t timePoint) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700263 auto const [slope, intercept] = getVSyncPredictionModelLocked();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700264
Ady Abraham92fa2f42020-02-11 15:33:56 -0800265 if (mTimestamps.empty()) {
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800266 traceInt64("VSP-mode", 1);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700267 auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800268 auto const numPeriodsOut = ((timePoint - knownTimestamp) / idealPeriod()) + 1;
269 return knownTimestamp + numPeriodsOut * idealPeriod();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700270 }
271
Ady Abraham92fa2f42020-02-11 15:33:56 -0800272 auto const oldest = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois127a2d92019-12-04 13:52:52 -0800273
274 // See b/145667109, the ordinal calculation must take into account the intercept.
275 auto const zeroPoint = oldest + intercept;
276 auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700277 auto const prediction = (ordinalRequest * slope) + intercept + oldest;
278
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800279 traceInt64("VSP-mode", 0);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800280 traceInt64If("VSP-timePoint", timePoint);
281 traceInt64If("VSP-prediction", prediction);
282
Kevin DuBois127a2d92019-12-04 13:52:52 -0800283 auto const printer = [&, slope = slope, intercept = intercept] {
284 std::stringstream str;
285 str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
286 << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
287 << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
288 return str.str();
289 };
290
291 ALOGV("%s", printer().c_str());
292 LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
293 printer().c_str());
294
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700295 return prediction;
296}
297
Ady Abraham4335afd2023-12-18 19:10:47 -0800298nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint,
Ady Abraham20024aa2024-03-05 01:32:49 +0000299 std::optional<nsecs_t> lastVsyncOpt) {
Ady Abraham4335afd2023-12-18 19:10:47 -0800300 ATRACE_CALL();
Ady Abraham9c53ee72020-07-22 21:16:18 -0700301 std::lock_guard lock(mMutex);
Ady Abrahamace3d052022-11-17 16:25:05 -0800302
Ady Abraham20024aa2024-03-05 01:32:49 +0000303 const auto now = TimePoint::fromNs(mClock->now());
304 purgeTimelines(now);
Ady Abrahamf34a8132023-02-13 20:49:48 -0800305
Ady Abrahamee6365b2024-03-06 14:31:45 -0800306 if (lastVsyncOpt && *lastVsyncOpt > timePoint) {
307 timePoint = *lastVsyncOpt;
308 }
309
Ady Abraham77b4fb12024-03-05 17:51:53 -0800310 const auto model = getVSyncPredictionModelLocked();
311 const auto threshold = model.slope / 2;
Ady Abraham940b7a62024-03-07 10:04:27 -0800312 std::optional<Period> minFramePeriodOpt;
313
314 if (mNumVsyncsForFrame > 1) {
315 minFramePeriodOpt = minFramePeriodLocked();
316 }
317
Ady Abraham20024aa2024-03-05 01:32:49 +0000318 std::optional<TimePoint> vsyncOpt;
319 for (auto& timeline : mTimelines) {
Ady Abraham940b7a62024-03-07 10:04:27 -0800320 vsyncOpt = timeline.nextAnticipatedVSyncTimeFrom(model, minFramePeriodOpt,
Ady Abraham20024aa2024-03-05 01:32:49 +0000321 snapToVsync(timePoint), mMissedVsync,
Ady Abraham77b4fb12024-03-05 17:51:53 -0800322 lastVsyncOpt ? snapToVsync(*lastVsyncOpt -
323 threshold)
324 : lastVsyncOpt);
Ady Abraham20024aa2024-03-05 01:32:49 +0000325 if (vsyncOpt) {
326 break;
Ady Abrahame9883032023-11-20 17:54:54 -0800327 }
Ady Abraham20024aa2024-03-05 01:32:49 +0000328 }
329 LOG_ALWAYS_FATAL_IF(!vsyncOpt);
Ady Abrahame9883032023-11-20 17:54:54 -0800330
Ady Abraham20024aa2024-03-05 01:32:49 +0000331 if (*vsyncOpt > mLastCommittedVsync) {
332 mLastCommittedVsync = *vsyncOpt;
333 ATRACE_FORMAT_INSTANT("mLastCommittedVsync in %.2fms",
334 float(mLastCommittedVsync.ns() - mClock->now()) / 1e6f);
Ady Abrahamace3d052022-11-17 16:25:05 -0800335 }
Ady Abrahamf34a8132023-02-13 20:49:48 -0800336
Ady Abraham20024aa2024-03-05 01:32:49 +0000337 return vsyncOpt->ns();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700338}
339
Ady Abraham0bb6a472020-10-12 10:22:13 -0700340/*
Ady Abraham5cc2e262021-03-25 13:09:17 -0700341 * Returns whether a given vsync timestamp is in phase with a frame rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800342 * 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 -0700343 * For example, if the vsync timestamps are (16.6,33.3,50.0,66.6):
344 * isVSyncInPhase(16.6, 30) = true
345 * isVSyncInPhase(33.3, 30) = false
346 * isVSyncInPhase(50.0, 30) = true
Ady Abraham0bb6a472020-10-12 10:22:13 -0700347 */
Ady Abraham20024aa2024-03-05 01:32:49 +0000348bool VSyncPredictor::isVSyncInPhase(nsecs_t timePoint, Fps frameRate) {
349 if (timePoint == 0) {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700350 return true;
351 }
352
Ady Abraham20024aa2024-03-05 01:32:49 +0000353 std::lock_guard lock(mMutex);
354 const auto model = getVSyncPredictionModelLocked();
355 const nsecs_t period = model.slope;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700356 const nsecs_t justBeforeTimePoint = timePoint - period / 2;
Ady Abraham20024aa2024-03-05 01:32:49 +0000357 const auto now = TimePoint::fromNs(mClock->now());
358 const auto vsync = snapToVsync(justBeforeTimePoint);
359
360 purgeTimelines(now);
361
362 for (auto& timeline : mTimelines) {
ramindani548f4492024-06-13 10:29:04 -0700363 const bool isVsyncValid = FlagManager::getInstance().vrr_bugfix_24q4()
364 ? timeline.isWithin(TimePoint::fromNs(vsync)) ==
365 VsyncTimeline::VsyncOnTimeline::Unique
366 : timeline.validUntil() && timeline.validUntil()->ns() > vsync;
367 if (isVsyncValid) {
Ady Abraham20024aa2024-03-05 01:32:49 +0000368 return timeline.isVSyncInPhase(model, vsync, frameRate);
369 }
370 }
371
372 // The last timeline should always be valid
373 return mTimelines.back().isVSyncInPhase(model, vsync, frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700374}
375
Ady Abrahamee6365b2024-03-06 14:31:45 -0800376void VSyncPredictor::setRenderRate(Fps renderRate, bool applyImmediately) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800377 ATRACE_FORMAT("%s %s", __func__, to_string(renderRate).c_str());
378 ALOGV("%s %s: RenderRate %s ", __func__, to_string(mId).c_str(), to_string(renderRate).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800379 std::lock_guard lock(mMutex);
Ady Abraham77b4fb12024-03-05 17:51:53 -0800380 const auto prevRenderRate = mRenderRateOpt;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800381 mRenderRateOpt = renderRate;
Ady Abraham77b4fb12024-03-05 17:51:53 -0800382 const auto renderPeriodDelta =
383 prevRenderRate ? prevRenderRate->getPeriodNsecs() - renderRate.getPeriodNsecs() : 0;
Ady Abraham4fc2fce2024-03-08 06:43:44 +0000384 if (applyImmediately) {
Ady Abraham45ed7a82024-03-14 17:36:22 -0700385 ATRACE_FORMAT_INSTANT("applyImmediately");
Ady Abraham4fc2fce2024-03-08 06:43:44 +0000386 while (mTimelines.size() > 1) {
387 mTimelines.pop_front();
388 }
389
390 mTimelines.front().setRenderRate(renderRate);
Ady Abraham45ed7a82024-03-14 17:36:22 -0700391 return;
392 }
393
394 const bool newRenderRateIsHigher = renderPeriodDelta > renderRate.getPeriodNsecs() &&
395 mLastCommittedVsync.ns() - mClock->now() > 2 * renderRate.getPeriodNsecs();
396 if (newRenderRateIsHigher) {
397 ATRACE_FORMAT_INSTANT("newRenderRateIsHigher");
Ady Abraham77b4fb12024-03-05 17:51:53 -0800398 mTimelines.clear();
399 mLastCommittedVsync = TimePoint::fromNs(0);
Ady Abraham4fc2fce2024-03-08 06:43:44 +0000400
Ady Abraham77b4fb12024-03-05 17:51:53 -0800401 } else {
ramindani548f4492024-06-13 10:29:04 -0700402 if (FlagManager::getInstance().vrr_bugfix_24q4()) {
403 // We need to freeze the timeline at the committed vsync so that we don't
404 // overshoot the deadline.
405 mTimelines.back().freeze(mLastCommittedVsync);
406 } else {
407 mTimelines.back().freeze(
408 TimePoint::fromNs(mLastCommittedVsync.ns() + mIdealPeriod.ns() / 2));
409 }
Ady Abraham77b4fb12024-03-05 17:51:53 -0800410 }
411 mTimelines.emplace_back(mLastCommittedVsync, mIdealPeriod, renderRate);
Ady Abraham20024aa2024-03-05 01:32:49 +0000412 purgeTimelines(TimePoint::fromNs(mClock->now()));
Ady Abrahamc585dba2023-11-15 18:41:35 -0800413}
414
415void VSyncPredictor::setDisplayModePtr(ftl::NonNull<DisplayModePtr> modePtr) {
416 LOG_ALWAYS_FATAL_IF(mId != modePtr->getPhysicalDisplayId(),
417 "mode does not belong to the display");
418 ATRACE_FORMAT("%s %s", __func__, to_string(*modePtr).c_str());
419 const auto timeout = modePtr->getVrrConfig()
420 ? modePtr->getVrrConfig()->notifyExpectedPresentConfig
421 : std::nullopt;
422 ALOGV("%s %s: DisplayMode %s notifyExpectedPresentTimeout %s", __func__, to_string(mId).c_str(),
423 to_string(*modePtr).c_str(),
ramindanicbd7a6d2023-12-19 16:00:30 -0800424 timeout ? std::to_string(timeout->timeoutNs).c_str() : "N/A");
Ady Abrahamc585dba2023-11-15 18:41:35 -0800425 std::lock_guard lock(mMutex);
426
427 mDisplayModePtr = modePtr;
Ady Abraham940b7a62024-03-07 10:04:27 -0800428 mNumVsyncsForFrame = numVsyncsPerFrame(mDisplayModePtr);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800429 traceInt64("VSP-setPeriod", modePtr->getVsyncRate().getPeriodNsecs());
430
431 static constexpr size_t kSizeLimit = 30;
432 if (CC_UNLIKELY(mRateMap.size() == kSizeLimit)) {
433 mRateMap.erase(mRateMap.begin());
434 }
435
436 if (mRateMap.find(idealPeriod()) == mRateMap.end()) {
437 mRateMap[idealPeriod()] = {idealPeriod(), 0};
438 }
439
Ady Abraham54410052024-03-25 23:08:59 +0000440 mTimelines.clear();
Ady Abrahamc585dba2023-11-15 18:41:35 -0800441 clearTimestamps();
Ady Abrahamace3d052022-11-17 16:25:05 -0800442}
443
Ady Abraham20024aa2024-03-05 01:32:49 +0000444Duration VSyncPredictor::ensureMinFrameDurationIsKept(TimePoint expectedPresentTime,
445 TimePoint lastConfirmedPresentTime) {
446 ATRACE_CALL();
Ady Abraham940b7a62024-03-07 10:04:27 -0800447
448 if (mNumVsyncsForFrame <= 1) {
449 return 0ns;
450 }
451
Ady Abrahame9883032023-11-20 17:54:54 -0800452 const auto currentPeriod = mRateMap.find(idealPeriod())->second.slope;
453 const auto threshold = currentPeriod / 2;
454 const auto minFramePeriod = minFramePeriodLocked().ns();
455
456 auto prev = lastConfirmedPresentTime.ns();
457 for (auto& current : mPastExpectedPresentTimes) {
458 if (CC_UNLIKELY(mTraceOn)) {
459 ATRACE_FORMAT_INSTANT("current %.2f past last signaled fence",
460 static_cast<float>(current.ns() - lastConfirmedPresentTime.ns()) /
461 1e6f);
462 }
463
464 const auto minPeriodViolation = current.ns() - prev + threshold < minFramePeriod;
465 if (minPeriodViolation) {
466 ATRACE_NAME("minPeriodViolation");
467 current = TimePoint::fromNs(prev + minFramePeriod);
468 prev = current.ns();
469 } else {
470 break;
471 }
472 }
473
474 if (!mPastExpectedPresentTimes.empty()) {
475 const auto phase = Duration(mPastExpectedPresentTimes.back() - expectedPresentTime);
476 if (phase > 0ns) {
Ady Abraham20024aa2024-03-05 01:32:49 +0000477 for (auto& timeline : mTimelines) {
478 timeline.shiftVsyncSequence(phase);
Ady Abrahame9883032023-11-20 17:54:54 -0800479 }
Ady Abraham4335afd2023-12-18 19:10:47 -0800480 mPastExpectedPresentTimes.clear();
Ady Abraham20024aa2024-03-05 01:32:49 +0000481 return phase;
Ady Abrahame9883032023-11-20 17:54:54 -0800482 }
483 }
Ady Abraham20024aa2024-03-05 01:32:49 +0000484
485 return 0ns;
Ady Abrahame9883032023-11-20 17:54:54 -0800486}
487
488void VSyncPredictor::onFrameBegin(TimePoint expectedPresentTime,
489 TimePoint lastConfirmedPresentTime) {
Ady Abraham20024aa2024-03-05 01:32:49 +0000490 ATRACE_NAME("VSyncPredictor::onFrameBegin");
Ady Abrahame9883032023-11-20 17:54:54 -0800491 std::lock_guard lock(mMutex);
492
493 if (!mDisplayModePtr->getVrrConfig()) return;
494
495 if (CC_UNLIKELY(mTraceOn)) {
496 ATRACE_FORMAT_INSTANT("vsync is %.2f past last signaled fence",
497 static_cast<float>(expectedPresentTime.ns() -
498 lastConfirmedPresentTime.ns()) /
499 1e6f);
500 }
Ady Abrahame9883032023-11-20 17:54:54 -0800501 const auto currentPeriod = mRateMap.find(idealPeriod())->second.slope;
502 const auto threshold = currentPeriod / 2;
Ady Abraham4335afd2023-12-18 19:10:47 -0800503 mPastExpectedPresentTimes.push_back(expectedPresentTime);
Ady Abrahame9883032023-11-20 17:54:54 -0800504
Ady Abrahame9883032023-11-20 17:54:54 -0800505 while (!mPastExpectedPresentTimes.empty()) {
506 const auto front = mPastExpectedPresentTimes.front().ns();
Ady Abraham4335afd2023-12-18 19:10:47 -0800507 const bool frontIsBeforeConfirmed = front < lastConfirmedPresentTime.ns() + threshold;
508 if (frontIsBeforeConfirmed) {
Ady Abrahame9883032023-11-20 17:54:54 -0800509 if (CC_UNLIKELY(mTraceOn)) {
510 ATRACE_FORMAT_INSTANT("Discarding old vsync - %.2f before last signaled fence",
Ady Abraham4335afd2023-12-18 19:10:47 -0800511 static_cast<float>(lastConfirmedPresentTime.ns() - front) /
Ady Abrahame9883032023-11-20 17:54:54 -0800512 1e6f);
513 }
514 mPastExpectedPresentTimes.pop_front();
515 } else {
516 break;
517 }
518 }
519
Ady Abraham20024aa2024-03-05 01:32:49 +0000520 const auto phase = ensureMinFrameDurationIsKept(expectedPresentTime, lastConfirmedPresentTime);
521 if (phase > 0ns) {
522 mMissedVsync = {expectedPresentTime, minFramePeriodLocked()};
523 }
Ady Abrahame9883032023-11-20 17:54:54 -0800524}
525
526void VSyncPredictor::onFrameMissed(TimePoint expectedPresentTime) {
Ady Abraham20024aa2024-03-05 01:32:49 +0000527 ATRACE_NAME("VSyncPredictor::onFrameMissed");
Ady Abrahame9883032023-11-20 17:54:54 -0800528
529 std::lock_guard lock(mMutex);
530 if (!mDisplayModePtr->getVrrConfig()) return;
531
532 // We don't know when the frame is going to be presented, so we assume it missed one vsync
533 const auto currentPeriod = mRateMap.find(idealPeriod())->second.slope;
534 const auto lastConfirmedPresentTime =
535 TimePoint::fromNs(expectedPresentTime.ns() + currentPeriod);
536
Ady Abraham20024aa2024-03-05 01:32:49 +0000537 const auto phase = ensureMinFrameDurationIsKept(expectedPresentTime, lastConfirmedPresentTime);
538 if (phase > 0ns) {
539 mMissedVsync = {expectedPresentTime, Duration::fromNs(0)};
540 }
Ady Abrahame9883032023-11-20 17:54:54 -0800541}
542
Ady Abraham0bb6a472020-10-12 10:22:13 -0700543VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModel() const {
544 std::lock_guard lock(mMutex);
Ady Abraham20024aa2024-03-05 01:32:49 +0000545 return VSyncPredictor::getVSyncPredictionModelLocked();
Ady Abraham0bb6a472020-10-12 10:22:13 -0700546}
547
548VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModelLocked() const {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800549 return mRateMap.find(idealPeriod())->second;
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800550}
551
552void VSyncPredictor::clearTimestamps() {
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000553 ATRACE_CALL();
554
Ady Abraham92fa2f42020-02-11 15:33:56 -0800555 if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700556 auto const maxRb = *std::max_element(mTimestamps.begin(), mTimestamps.end());
557 if (mKnownTimestamp) {
558 mKnownTimestamp = std::max(*mKnownTimestamp, maxRb);
559 } else {
560 mKnownTimestamp = maxRb;
561 }
562
Ady Abraham92fa2f42020-02-11 15:33:56 -0800563 mTimestamps.clear();
564 mLastTimestampIndex = 0;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700565 }
Ady Abraham20024aa2024-03-05 01:32:49 +0000566
Ady Abraham20024aa2024-03-05 01:32:49 +0000567 mIdealPeriod = Period::fromNs(idealPeriod());
Ady Abrahamc5d72462024-03-23 23:56:33 +0000568 if (mTimelines.empty()) {
569 mLastCommittedVsync = TimePoint::fromNs(0);
570 mTimelines.emplace_back(mLastCommittedVsync, mIdealPeriod, mRenderRateOpt);
571 } else {
572 while (mTimelines.size() > 1) {
573 mTimelines.pop_front();
574 }
575 mTimelines.front().setRenderRate(mRenderRateOpt);
576 // set mLastCommittedVsync to a valid vsync but don't commit too much in the future
577 const auto vsyncOpt = mTimelines.front().nextAnticipatedVSyncTimeFrom(
578 getVSyncPredictionModelLocked(),
579 /* minFramePeriodOpt */ std::nullopt,
580 snapToVsync(mClock->now()), MissedVsync{},
581 /* lastVsyncOpt */ std::nullopt);
582 mLastCommittedVsync = *vsyncOpt;
583 }
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700584}
585
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700586bool VSyncPredictor::needsMoreSamples() const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700587 std::lock_guard lock(mMutex);
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700588 return mTimestamps.size() < kMinimumSamplesForPrediction;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700589}
590
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800591void VSyncPredictor::resetModel() {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700592 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800593 mRateMap[idealPeriod()] = {idealPeriod(), 0};
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800594 clearTimestamps();
595}
596
Ady Abraham5e7371c2020-03-24 14:47:24 -0700597void VSyncPredictor::dump(std::string& result) const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700598 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800599 StringAppendF(&result, "\tmDisplayModePtr=%s\n", to_string(*mDisplayModePtr).c_str());
Ady Abraham5e7371c2020-03-24 14:47:24 -0700600 StringAppendF(&result, "\tRefresh Rate Map:\n");
Ady Abrahamc585dba2023-11-15 18:41:35 -0800601 for (const auto& [period, periodInterceptTuple] : mRateMap) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700602 StringAppendF(&result,
603 "\t\tFor ideal period %.2fms: period = %.2fms, intercept = %" PRId64 "\n",
Ady Abrahamc585dba2023-11-15 18:41:35 -0800604 period / 1e6f, periodInterceptTuple.slope / 1e6f,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700605 periodInterceptTuple.intercept);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700606 }
Ady Abraham20024aa2024-03-05 01:32:49 +0000607 StringAppendF(&result, "\tmTimelines.size()=%zu\n", mTimelines.size());
608}
609
610void VSyncPredictor::purgeTimelines(android::TimePoint now) {
Ady Abraham77b4fb12024-03-05 17:51:53 -0800611 const auto kEnoughFramesToBreakPhase = 5;
612 if (mRenderRateOpt &&
613 mLastCommittedVsync.ns() + mRenderRateOpt->getPeriodNsecs() * kEnoughFramesToBreakPhase <
614 mClock->now()) {
Ady Abrahamc5d72462024-03-23 23:56:33 +0000615 ATRACE_FORMAT_INSTANT("kEnoughFramesToBreakPhase");
Ady Abraham77b4fb12024-03-05 17:51:53 -0800616 mTimelines.clear();
617 mLastCommittedVsync = TimePoint::fromNs(0);
618 mTimelines.emplace_back(mLastCommittedVsync, mIdealPeriod, mRenderRateOpt);
619 return;
620 }
621
Ady Abraham20024aa2024-03-05 01:32:49 +0000622 while (mTimelines.size() > 1) {
623 const auto validUntilOpt = mTimelines.front().validUntil();
ramindani548f4492024-06-13 10:29:04 -0700624 const bool isTimelineOutDated = FlagManager::getInstance().vrr_bugfix_24q4()
625 ? mTimelines.front().isWithin(now) == VsyncTimeline::VsyncOnTimeline::Outside
626 : validUntilOpt && *validUntilOpt < now;
627 if (isTimelineOutDated) {
Ady Abraham20024aa2024-03-05 01:32:49 +0000628 mTimelines.pop_front();
629 } else {
630 break;
631 }
632 }
633 LOG_ALWAYS_FATAL_IF(mTimelines.empty());
634 LOG_ALWAYS_FATAL_IF(mTimelines.back().validUntil().has_value());
635}
636
Ady Abraham77b4fb12024-03-05 17:51:53 -0800637auto VSyncPredictor::VsyncTimeline::makeVsyncSequence(TimePoint knownVsync)
638 -> std::optional<VsyncSequence> {
639 if (knownVsync.ns() == 0) return std::nullopt;
640 return std::make_optional<VsyncSequence>({knownVsync.ns(), 0});
641}
642
643VSyncPredictor::VsyncTimeline::VsyncTimeline(TimePoint knownVsync, Period idealPeriod,
644 std::optional<Fps> renderRateOpt)
645 : mIdealPeriod(idealPeriod),
646 mRenderRateOpt(renderRateOpt),
647 mLastVsyncSequence(makeVsyncSequence(knownVsync)) {}
Ady Abraham20024aa2024-03-05 01:32:49 +0000648
649void VSyncPredictor::VsyncTimeline::freeze(TimePoint lastVsync) {
650 LOG_ALWAYS_FATAL_IF(mValidUntil.has_value());
651 ATRACE_FORMAT_INSTANT("renderRate %s valid for %.2f",
652 mRenderRateOpt ? to_string(*mRenderRateOpt).c_str() : "NA",
653 float(lastVsync.ns() - TimePoint::now().ns()) / 1e6f);
654 mValidUntil = lastVsync;
655}
656
657std::optional<TimePoint> VSyncPredictor::VsyncTimeline::nextAnticipatedVSyncTimeFrom(
Ady Abraham940b7a62024-03-07 10:04:27 -0800658 Model model, std::optional<Period> minFramePeriodOpt, nsecs_t vsync,
659 MissedVsync missedVsync, std::optional<nsecs_t> lastVsyncOpt) {
Ady Abraham20024aa2024-03-05 01:32:49 +0000660 ATRACE_FORMAT("renderRate %s", mRenderRateOpt ? to_string(*mRenderRateOpt).c_str() : "NA");
661
Ady Abrahame54ce102024-03-04 23:18:38 +0000662 nsecs_t vsyncTime = snapToVsyncAlignedWithRenderRate(model, vsync);
Ady Abraham20024aa2024-03-05 01:32:49 +0000663 const auto threshold = model.slope / 2;
664 const auto lastFrameMissed =
665 lastVsyncOpt && std::abs(*lastVsyncOpt - missedVsync.vsync.ns()) < threshold;
Ady Abrahame9dcf792024-05-14 15:24:54 -0700666 const auto mightBackpressure = minFramePeriodOpt && mRenderRateOpt &&
667 mRenderRateOpt->getPeriod() < 2 * (*minFramePeriodOpt);
668 if (FlagManager::getInstance().vrr_config()) {
669 if (lastFrameMissed) {
670 // If the last frame missed is the last vsync, we already shifted the timeline. Depends
671 // on whether we skipped the frame (onFrameMissed) or not (onFrameBegin) we apply a
672 // different fixup. There is no need to to shift the vsync timeline again.
673 vsyncTime += missedVsync.fixup.ns();
674 ATRACE_FORMAT_INSTANT("lastFrameMissed");
675 } else if (mightBackpressure && lastVsyncOpt) {
ramindani548f4492024-06-13 10:29:04 -0700676 if (!FlagManager::getInstance().vrr_bugfix_24q4()) {
677 // lastVsyncOpt does not need to be corrected with the new rate, and
678 // it should be used as is to avoid skipping a frame when changing rates are
679 // aligned at vsync time.
680 lastVsyncOpt = snapToVsyncAlignedWithRenderRate(model, *lastVsyncOpt);
681 }
Ady Abrahame9dcf792024-05-14 15:24:54 -0700682 const auto vsyncDiff = vsyncTime - *lastVsyncOpt;
683 if (vsyncDiff <= minFramePeriodOpt->ns() - threshold) {
684 // avoid a duplicate vsync
685 ATRACE_FORMAT_INSTANT("skipping a vsync to avoid duplicate frame. next in %.2f "
686 "which "
687 "is %.2f "
688 "from "
689 "prev. "
690 "adjust by %.2f",
691 static_cast<float>(vsyncTime - TimePoint::now().ns()) / 1e6f,
692 static_cast<float>(vsyncDiff) / 1e6f,
693 static_cast<float>(mRenderRateOpt->getPeriodNsecs()) / 1e6f);
694 vsyncTime += mRenderRateOpt->getPeriodNsecs();
695 }
Ady Abrahame54ce102024-03-04 23:18:38 +0000696 }
Ady Abraham20024aa2024-03-05 01:32:49 +0000697 }
698
699 ATRACE_FORMAT_INSTANT("vsync in %.2fms", float(vsyncTime - TimePoint::now().ns()) / 1e6f);
ramindani548f4492024-06-13 10:29:04 -0700700 const bool isVsyncInvalid = FlagManager::getInstance().vrr_bugfix_24q4()
701 ? isWithin(TimePoint::fromNs(vsyncTime)) == VsyncOnTimeline::Outside
702 : mValidUntil && vsyncTime > mValidUntil->ns();
703 if (isVsyncInvalid) {
Ady Abraham20024aa2024-03-05 01:32:49 +0000704 ATRACE_FORMAT_INSTANT("no longer valid for vsync in %.2f",
705 static_cast<float>(vsyncTime - TimePoint::now().ns()) / 1e6f);
706 return std::nullopt;
707 }
708
Ady Abraham20024aa2024-03-05 01:32:49 +0000709 return TimePoint::fromNs(vsyncTime);
710}
711
712auto VSyncPredictor::VsyncTimeline::getVsyncSequenceLocked(Model model, nsecs_t vsync)
713 -> VsyncSequence {
714 if (!mLastVsyncSequence) return {vsync, 0};
715
716 const auto [lastVsyncTime, lastVsyncSequence] = *mLastVsyncSequence;
717 const auto vsyncSequence = lastVsyncSequence +
718 static_cast<int64_t>(std::round((vsync - lastVsyncTime) /
719 static_cast<float>(model.slope)));
720 return {vsync, vsyncSequence};
721}
722
723nsecs_t VSyncPredictor::VsyncTimeline::snapToVsyncAlignedWithRenderRate(Model model,
724 nsecs_t vsync) {
725 // update the mLastVsyncSequence for reference point
726 mLastVsyncSequence = getVsyncSequenceLocked(model, vsync);
727
728 const auto renderRatePhase = [&]() -> int {
729 if (!mRenderRateOpt) return 0;
730 const auto divisor =
731 RefreshRateSelector::getFrameRateDivisor(Fps::fromPeriodNsecs(mIdealPeriod.ns()),
732 *mRenderRateOpt);
733 if (divisor <= 1) return 0;
734
735 int mod = mLastVsyncSequence->seq % divisor;
736 if (mod == 0) return 0;
737
738 // This is actually a bug fix, but guarded with vrr_config since we found it with this
739 // config
740 if (FlagManager::getInstance().vrr_config()) {
741 if (mod < 0) mod += divisor;
742 }
743
744 return divisor - mod;
745 }();
746
747 if (renderRatePhase == 0) {
748 return mLastVsyncSequence->vsyncTime;
749 }
750
751 return mLastVsyncSequence->vsyncTime + model.slope * renderRatePhase;
752}
753
754bool VSyncPredictor::VsyncTimeline::isVSyncInPhase(Model model, nsecs_t vsync, Fps frameRate) {
755 const auto getVsyncIn = [](TimePoint now, nsecs_t timePoint) -> float {
756 return ticks<std::milli, float>(TimePoint::fromNs(timePoint) - now);
757 };
758
Ady Abraham4a719e82024-06-06 12:12:09 -0700759 Fps displayFps = !FlagManager::getInstance().vrr_bugfix_24q4() && mRenderRateOpt
760 ? *mRenderRateOpt
761 : Fps::fromPeriodNsecs(mIdealPeriod.ns());
Ady Abraham20024aa2024-03-05 01:32:49 +0000762 const auto divisor = RefreshRateSelector::getFrameRateDivisor(displayFps, frameRate);
763 const auto now = TimePoint::now();
764
765 if (divisor <= 1) {
766 return true;
767 }
768 const auto vsyncSequence = getVsyncSequenceLocked(model, vsync);
769 ATRACE_FORMAT_INSTANT("vsync in: %.2f sequence: %" PRId64 " divisor: %zu",
770 getVsyncIn(now, vsyncSequence.vsyncTime), vsyncSequence.seq, divisor);
771 return vsyncSequence.seq % divisor == 0;
772}
773
774void VSyncPredictor::VsyncTimeline::shiftVsyncSequence(Duration phase) {
775 if (mLastVsyncSequence) {
776 ATRACE_FORMAT_INSTANT("adjusting vsync by %.2f", static_cast<float>(phase.ns()) / 1e6f);
777 mLastVsyncSequence->vsyncTime += phase.ns();
778 }
Ady Abraham5e7371c2020-03-24 14:47:24 -0700779}
780
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700781} // namespace android::scheduler
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800782
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100783// TODO(b/129481165): remove the #pragma below and fix conversion issues
Dominik Laskowski62eff352021-12-06 09:59:41 -0800784#pragma clang diagnostic pop // ignored "-Wextra"