blob: 8697696915a636329faa349dd9064d93bf632f18 [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
48VSyncPredictor::~VSyncPredictor() = default;
49
Ady Abraham9633f8e2024-03-04 19:38:12 +000050VSyncPredictor::VSyncPredictor(ftl::NonNull<DisplayModePtr> modePtr, size_t historySize,
51 size_t minimumSamplesForPrediction, uint32_t outlierTolerancePercent)
52 : mId(modePtr->getPhysicalDisplayId()),
Leon Scroggins III67388622023-02-06 20:36:20 -050053 mTraceOn(property_get_bool("debug.sf.vsp_trace", false)),
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080054 kHistorySize(historySize),
Kevin DuBois1678e2c2019-08-22 12:26:24 -070055 kMinimumSamplesForPrediction(minimumSamplesForPrediction),
56 kOutlierTolerancePercent(std::min(outlierTolerancePercent, kMaxPercent)),
Ady Abrahamc585dba2023-11-15 18:41:35 -080057 mDisplayModePtr(modePtr) {
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -080058 resetModel();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070059}
60
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080061inline void VSyncPredictor::traceInt64If(const char* name, int64_t value) const {
62 if (CC_UNLIKELY(mTraceOn)) {
Leon Scroggins III67388622023-02-06 20:36:20 -050063 traceInt64(name, value);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080064 }
65}
66
Ady Abrahamd9b9a042023-01-13 11:30:58 -080067inline void VSyncPredictor::traceInt64(const char* name, int64_t value) const {
Leon Scroggins III67388622023-02-06 20:36:20 -050068 ATRACE_INT64(ftl::Concat(ftl::truncated<14>(name), " ", mId.value).c_str(), value);
Ady Abrahamd9b9a042023-01-13 11:30:58 -080069}
70
Ady Abraham9c53ee72020-07-22 21:16:18 -070071inline size_t VSyncPredictor::next(size_t i) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080072 return (i + 1) % mTimestamps.size();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070073}
74
Ady Abrahamc585dba2023-11-15 18:41:35 -080075nsecs_t VSyncPredictor::idealPeriod() const {
76 return mDisplayModePtr->getVsyncRate().getPeriodNsecs();
77}
78
Kevin DuBois1678e2c2019-08-22 12:26:24 -070079bool VSyncPredictor::validate(nsecs_t timestamp) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080080 if (mLastTimestampIndex < 0 || mTimestamps.empty()) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -070081 return true;
82 }
83
Ady Abrahamc585dba2023-11-15 18:41:35 -080084 const auto aValidTimestamp = mTimestamps[mLastTimestampIndex];
85 const auto percent =
86 (timestamp - aValidTimestamp) % idealPeriod() * kMaxPercent / idealPeriod();
Ady Abraham99ca3362021-06-17 12:28:46 -070087 if (percent >= kOutlierTolerancePercent &&
88 percent <= (kMaxPercent - kOutlierTolerancePercent)) {
Ady Abrahamf0b2bf92023-12-13 23:36:35 +000089 ATRACE_FORMAT_INSTANT("timestamp is not aligned with model");
Ady Abraham99ca3362021-06-17 12:28:46 -070090 return false;
91 }
92
93 const auto iter = std::min_element(mTimestamps.begin(), mTimestamps.end(),
94 [timestamp](nsecs_t a, nsecs_t b) {
95 return std::abs(timestamp - a) < std::abs(timestamp - b);
96 });
Ady Abrahamc585dba2023-11-15 18:41:35 -080097 const auto distancePercent = std::abs(*iter - timestamp) * kMaxPercent / idealPeriod();
Ady Abraham99ca3362021-06-17 12:28:46 -070098 if (distancePercent < kOutlierTolerancePercent) {
99 // duplicate timestamp
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000100 ATRACE_FORMAT_INSTANT("duplicate timestamp");
Ady Abraham99ca3362021-06-17 12:28:46 -0700101 return false;
102 }
103 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700104}
105
Kevin DuBois2fd3cea2019-11-14 08:52:45 -0800106nsecs_t VSyncPredictor::currentPeriod() const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700107 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800108 return mRateMap.find(idealPeriod())->second.slope;
Kevin DuBois2fd3cea2019-11-14 08:52:45 -0800109}
110
Ady Abraham3db8a3c2023-11-20 17:53:47 -0800111Period VSyncPredictor::minFramePeriod() const {
112 if (!FlagManager::getInstance().vrr_config()) {
113 return Period::fromNs(currentPeriod());
114 }
115
116 std::lock_guard lock(mMutex);
Ady Abrahame9883032023-11-20 17:54:54 -0800117 return minFramePeriodLocked();
118}
119
120Period VSyncPredictor::minFramePeriodLocked() const {
Ady Abraham3db8a3c2023-11-20 17:53:47 -0800121 const auto idealPeakRefreshPeriod = mDisplayModePtr->getPeakFps().getPeriodNsecs();
122 const auto numPeriods = static_cast<int>(std::round(static_cast<float>(idealPeakRefreshPeriod) /
123 static_cast<float>(idealPeriod())));
124 const auto slope = mRateMap.find(idealPeriod())->second.slope;
125 return Period::fromNs(slope * numPeriods);
126}
127
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800128bool VSyncPredictor::addVsyncTimestamp(nsecs_t timestamp) {
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000129 ATRACE_CALL();
130
Ady Abraham9c53ee72020-07-22 21:16:18 -0700131 std::lock_guard lock(mMutex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700132
133 if (!validate(timestamp)) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700134 // VSR could elect to ignore the incongruent timestamp or resetModel(). If ts is ignored,
Ady Abraham43a3e692020-11-13 12:43:39 -0800135 // don't insert this ts into mTimestamps ringbuffer. If we are still
136 // in the learning phase we should just clear all timestamps and start
137 // over.
138 if (mTimestamps.size() < kMinimumSamplesForPrediction) {
Ady Abraham4c56b642021-06-08 15:03:33 -0700139 // Add the timestamp to mTimestamps before clearing it so we could
140 // update mKnownTimestamp based on the new timestamp.
141 mTimestamps.push_back(timestamp);
Ady Abraham43a3e692020-11-13 12:43:39 -0800142 clearTimestamps();
143 } else if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700144 mKnownTimestamp =
145 std::max(timestamp, *std::max_element(mTimestamps.begin(), mTimestamps.end()));
146 } else {
147 mKnownTimestamp = timestamp;
148 }
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000149 ATRACE_FORMAT_INSTANT("timestamp rejected. mKnownTimestamp was %.2fms ago",
Ady Abraham9633f8e2024-03-04 19:38:12 +0000150 (systemTime() - *mKnownTimestamp) / 1e6f);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800151 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700152 }
153
Ady Abraham92fa2f42020-02-11 15:33:56 -0800154 if (mTimestamps.size() != kHistorySize) {
155 mTimestamps.push_back(timestamp);
156 mLastTimestampIndex = next(mLastTimestampIndex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700157 } else {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800158 mLastTimestampIndex = next(mLastTimestampIndex);
159 mTimestamps[mLastTimestampIndex] = timestamp;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700160 }
161
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800162 traceInt64If("VSP-ts", timestamp);
163
Dominik Laskowski62eff352021-12-06 09:59:41 -0800164 const size_t numSamples = mTimestamps.size();
165 if (numSamples < kMinimumSamplesForPrediction) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800166 mRateMap[idealPeriod()] = {idealPeriod(), 0};
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800167 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700168 }
169
170 // This is a 'simple linear regression' calculation of Y over X, with Y being the
171 // vsync timestamps, and X being the ordinal of vsync count.
172 // The calculated slope is the vsync period.
173 // Formula for reference:
174 // Sigma_i: means sum over all timestamps.
175 // mean(variable): statistical mean of variable.
176 // X: snapped ordinal of the timestamp
177 // Y: vsync timestamp
178 //
179 // Sigma_i( (X_i - mean(X)) * (Y_i - mean(Y) )
180 // slope = -------------------------------------------
181 // Sigma_i ( X_i - mean(X) ) ^ 2
182 //
183 // intercept = mean(Y) - slope * mean(X)
184 //
Dominik Laskowski62eff352021-12-06 09:59:41 -0800185 std::vector<nsecs_t> vsyncTS(numSamples);
186 std::vector<nsecs_t> ordinals(numSamples);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700187
Dominik Laskowski62eff352021-12-06 09:59:41 -0800188 // Normalizing to the oldest timestamp cuts down on error in calculating the intercept.
189 const auto oldestTS = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Ady Abrahamc585dba2023-11-15 18:41:35 -0800190 auto it = mRateMap.find(idealPeriod());
Ady Abraham0bb6a472020-10-12 10:22:13 -0700191 auto const currentPeriod = it->second.slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700192
Dominik Laskowski62eff352021-12-06 09:59:41 -0800193 // The mean of the ordinals must be precise for the intercept calculation, so scale them up for
194 // fixed-point arithmetic.
195 constexpr int64_t kScalingFactor = 1000;
196
197 nsecs_t meanTS = 0;
198 nsecs_t meanOrdinal = 0;
199
200 for (size_t i = 0; i < numSamples; i++) {
Dominik Laskowski62eff352021-12-06 09:59:41 -0800201 const auto timestamp = mTimestamps[i] - oldestTS;
202 vsyncTS[i] = timestamp;
203 meanTS += timestamp;
204
Rachel Lee934017e2022-08-10 15:34:14 -0700205 const auto ordinal = currentPeriod == 0
206 ? 0
207 : (vsyncTS[i] + currentPeriod / 2) / currentPeriod * kScalingFactor;
Dominik Laskowski62eff352021-12-06 09:59:41 -0800208 ordinals[i] = ordinal;
209 meanOrdinal += ordinal;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700210 }
211
Dominik Laskowski62eff352021-12-06 09:59:41 -0800212 meanTS /= numSamples;
213 meanOrdinal /= numSamples;
214
215 for (size_t i = 0; i < numSamples; i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700216 vsyncTS[i] -= meanTS;
217 ordinals[i] -= meanOrdinal;
218 }
219
Dominik Laskowski62eff352021-12-06 09:59:41 -0800220 nsecs_t top = 0;
221 nsecs_t bottom = 0;
222 for (size_t i = 0; i < numSamples; i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700223 top += vsyncTS[i] * ordinals[i];
224 bottom += ordinals[i] * ordinals[i];
225 }
226
227 if (CC_UNLIKELY(bottom == 0)) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800228 it->second = {idealPeriod(), 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800229 clearTimestamps();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800230 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700231 }
232
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700233 nsecs_t const anticipatedPeriod = top * kScalingFactor / bottom;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700234 nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
235
Ady Abrahamc585dba2023-11-15 18:41:35 -0800236 auto const percent = std::abs(anticipatedPeriod - idealPeriod()) * kMaxPercent / idealPeriod();
Ady Abraham92fa2f42020-02-11 15:33:56 -0800237 if (percent >= kOutlierTolerancePercent) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800238 it->second = {idealPeriod(), 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800239 clearTimestamps();
240 return false;
241 }
242
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800243 traceInt64If("VSP-period", anticipatedPeriod);
244 traceInt64If("VSP-intercept", intercept);
245
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700246 it->second = {anticipatedPeriod, intercept};
247
Leon Scroggins III67388622023-02-06 20:36:20 -0500248 ALOGV("model update ts %" PRIu64 ": %" PRId64 " slope: %" PRId64 " intercept: %" PRId64,
249 mId.value, timestamp, anticipatedPeriod, intercept);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800250 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700251}
252
Ady Abraham9633f8e2024-03-04 19:38:12 +0000253auto VSyncPredictor::getVsyncSequenceLocked(nsecs_t timestamp) const -> VsyncSequence {
254 const auto vsync = snapToVsync(timestamp);
255 if (!mLastVsyncSequence) return {vsync, 0};
256
257 const auto [slope, _] = getVSyncPredictionModelLocked();
258 const auto [lastVsyncTime, lastVsyncSequence] = *mLastVsyncSequence;
259 const auto vsyncSequence = lastVsyncSequence +
260 static_cast<int64_t>(std::round((vsync - lastVsyncTime) / static_cast<float>(slope)));
261 return {vsync, vsyncSequence};
262}
263
Ady Abraham4335afd2023-12-18 19:10:47 -0800264nsecs_t VSyncPredictor::snapToVsync(nsecs_t timePoint) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700265 auto const [slope, intercept] = getVSyncPredictionModelLocked();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700266
Ady Abraham92fa2f42020-02-11 15:33:56 -0800267 if (mTimestamps.empty()) {
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800268 traceInt64("VSP-mode", 1);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700269 auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800270 auto const numPeriodsOut = ((timePoint - knownTimestamp) / idealPeriod()) + 1;
271 return knownTimestamp + numPeriodsOut * idealPeriod();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700272 }
273
Ady Abraham92fa2f42020-02-11 15:33:56 -0800274 auto const oldest = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois127a2d92019-12-04 13:52:52 -0800275
276 // See b/145667109, the ordinal calculation must take into account the intercept.
277 auto const zeroPoint = oldest + intercept;
278 auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700279 auto const prediction = (ordinalRequest * slope) + intercept + oldest;
280
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800281 traceInt64("VSP-mode", 0);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800282 traceInt64If("VSP-timePoint", timePoint);
283 traceInt64If("VSP-prediction", prediction);
284
Kevin DuBois127a2d92019-12-04 13:52:52 -0800285 auto const printer = [&, slope = slope, intercept = intercept] {
286 std::stringstream str;
287 str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
288 << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
289 << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
290 return str.str();
291 };
292
293 ALOGV("%s", printer().c_str());
294 LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
295 printer().c_str());
296
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700297 return prediction;
298}
299
Ady Abraham4335afd2023-12-18 19:10:47 -0800300nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint,
Ady Abraham9633f8e2024-03-04 19:38:12 +0000301 std::optional<nsecs_t> lastVsyncOpt) const {
Ady Abraham4335afd2023-12-18 19:10:47 -0800302 ATRACE_CALL();
Ady Abraham9c53ee72020-07-22 21:16:18 -0700303 std::lock_guard lock(mMutex);
Ady Abraham9633f8e2024-03-04 19:38:12 +0000304 const auto currentPeriod = mRateMap.find(idealPeriod())->second.slope;
305 const auto threshold = currentPeriod / 2;
306 const auto minFramePeriod = minFramePeriodLocked().ns();
307 const auto lastFrameMissed =
308 lastVsyncOpt && std::abs(*lastVsyncOpt - mLastMissedVsync.ns()) < threshold;
309 const nsecs_t baseTime =
310 FlagManager::getInstance().vrr_config() && !lastFrameMissed && lastVsyncOpt
311 ? std::max(timePoint, *lastVsyncOpt + minFramePeriod - threshold)
312 : timePoint;
313 return snapToVsyncAlignedWithRenderRate(baseTime);
314}
Ady Abrahamace3d052022-11-17 16:25:05 -0800315
Ady Abraham9633f8e2024-03-04 19:38:12 +0000316nsecs_t VSyncPredictor::snapToVsyncAlignedWithRenderRate(nsecs_t timePoint) const {
317 // update the mLastVsyncSequence for reference point
318 mLastVsyncSequence = getVsyncSequenceLocked(timePoint);
Ady Abrahamf34a8132023-02-13 20:49:48 -0800319
Ady Abraham9633f8e2024-03-04 19:38:12 +0000320 const auto renderRatePhase = [&]() REQUIRES(mMutex) -> int {
321 if (!mRenderRateOpt) return 0;
322 const auto divisor =
323 RefreshRateSelector::getFrameRateDivisor(Fps::fromPeriodNsecs(idealPeriod()),
324 *mRenderRateOpt);
325 if (divisor <= 1) return 0;
326
327 int mod = mLastVsyncSequence->seq % divisor;
328 if (mod == 0) return 0;
329
330 // This is actually a bug fix, but guarded with vrr_config since we found it with this
331 // config
332 if (FlagManager::getInstance().vrr_config()) {
333 if (mod < 0) mod += divisor;
Ady Abrahame9883032023-11-20 17:54:54 -0800334 }
335
Ady Abraham9633f8e2024-03-04 19:38:12 +0000336 return divisor - mod;
337 }();
338
339 if (renderRatePhase == 0) {
340 return mLastVsyncSequence->vsyncTime;
Ady Abrahamace3d052022-11-17 16:25:05 -0800341 }
Ady Abrahamf34a8132023-02-13 20:49:48 -0800342
Ady Abraham9633f8e2024-03-04 19:38:12 +0000343 auto const [slope, intercept] = getVSyncPredictionModelLocked();
344 const auto approximateNextVsync = mLastVsyncSequence->vsyncTime + slope * renderRatePhase;
345 return snapToVsync(approximateNextVsync - slope / 2);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700346}
347
Ady Abraham0bb6a472020-10-12 10:22:13 -0700348/*
Ady Abraham5cc2e262021-03-25 13:09:17 -0700349 * Returns whether a given vsync timestamp is in phase with a frame rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800350 * 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 -0700351 * For example, if the vsync timestamps are (16.6,33.3,50.0,66.6):
352 * isVSyncInPhase(16.6, 30) = true
353 * isVSyncInPhase(33.3, 30) = false
354 * isVSyncInPhase(50.0, 30) = true
Ady Abraham0bb6a472020-10-12 10:22:13 -0700355 */
Ady Abraham9633f8e2024-03-04 19:38:12 +0000356bool VSyncPredictor::isVSyncInPhase(nsecs_t timePoint, Fps frameRate) const {
357 std::lock_guard lock(mMutex);
358 const auto divisor =
359 RefreshRateSelector::getFrameRateDivisor(Fps::fromPeriodNsecs(idealPeriod()),
360 frameRate);
361 return isVSyncInPhaseLocked(timePoint, static_cast<unsigned>(divisor));
362}
363
364bool VSyncPredictor::isVSyncInPhaseLocked(nsecs_t timePoint, unsigned divisor) const {
365 const TimePoint now = TimePoint::now();
366 const auto getTimePointIn = [](TimePoint now, nsecs_t timePoint) -> float {
367 return ticks<std::milli, float>(TimePoint::fromNs(timePoint) - now);
368 };
369 ATRACE_FORMAT("%s timePoint in: %.2f divisor: %zu", __func__, getTimePointIn(now, timePoint),
370 divisor);
371
372 if (divisor <= 1 || timePoint == 0) {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700373 return true;
374 }
375
Ady Abraham9633f8e2024-03-04 19:38:12 +0000376 const nsecs_t period = mRateMap[idealPeriod()].slope;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700377 const nsecs_t justBeforeTimePoint = timePoint - period / 2;
Ady Abraham9633f8e2024-03-04 19:38:12 +0000378 const auto vsyncSequence = getVsyncSequenceLocked(justBeforeTimePoint);
379 ATRACE_FORMAT_INSTANT("vsync in: %.2f sequence: %" PRId64,
380 getTimePointIn(now, vsyncSequence.vsyncTime), vsyncSequence.seq);
381 return vsyncSequence.seq % divisor == 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700382}
383
Ady Abrahamc585dba2023-11-15 18:41:35 -0800384void VSyncPredictor::setRenderRate(Fps renderRate) {
385 ATRACE_FORMAT("%s %s", __func__, to_string(renderRate).c_str());
386 ALOGV("%s %s: RenderRate %s ", __func__, to_string(mId).c_str(), to_string(renderRate).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800387 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800388 mRenderRateOpt = renderRate;
389}
390
391void VSyncPredictor::setDisplayModePtr(ftl::NonNull<DisplayModePtr> modePtr) {
392 LOG_ALWAYS_FATAL_IF(mId != modePtr->getPhysicalDisplayId(),
393 "mode does not belong to the display");
394 ATRACE_FORMAT("%s %s", __func__, to_string(*modePtr).c_str());
395 const auto timeout = modePtr->getVrrConfig()
396 ? modePtr->getVrrConfig()->notifyExpectedPresentConfig
397 : std::nullopt;
398 ALOGV("%s %s: DisplayMode %s notifyExpectedPresentTimeout %s", __func__, to_string(mId).c_str(),
399 to_string(*modePtr).c_str(),
ramindanicbd7a6d2023-12-19 16:00:30 -0800400 timeout ? std::to_string(timeout->timeoutNs).c_str() : "N/A");
Ady Abrahamc585dba2023-11-15 18:41:35 -0800401 std::lock_guard lock(mMutex);
402
403 mDisplayModePtr = modePtr;
404 traceInt64("VSP-setPeriod", modePtr->getVsyncRate().getPeriodNsecs());
405
406 static constexpr size_t kSizeLimit = 30;
407 if (CC_UNLIKELY(mRateMap.size() == kSizeLimit)) {
408 mRateMap.erase(mRateMap.begin());
409 }
410
411 if (mRateMap.find(idealPeriod()) == mRateMap.end()) {
412 mRateMap[idealPeriod()] = {idealPeriod(), 0};
413 }
414
415 clearTimestamps();
Ady Abrahamace3d052022-11-17 16:25:05 -0800416}
417
Ady Abraham9633f8e2024-03-04 19:38:12 +0000418void VSyncPredictor::ensureMinFrameDurationIsKept(TimePoint expectedPresentTime,
419 TimePoint lastConfirmedPresentTime) {
Ady Abrahame9883032023-11-20 17:54:54 -0800420 const auto currentPeriod = mRateMap.find(idealPeriod())->second.slope;
421 const auto threshold = currentPeriod / 2;
422 const auto minFramePeriod = minFramePeriodLocked().ns();
423
424 auto prev = lastConfirmedPresentTime.ns();
425 for (auto& current : mPastExpectedPresentTimes) {
426 if (CC_UNLIKELY(mTraceOn)) {
427 ATRACE_FORMAT_INSTANT("current %.2f past last signaled fence",
428 static_cast<float>(current.ns() - lastConfirmedPresentTime.ns()) /
429 1e6f);
430 }
431
432 const auto minPeriodViolation = current.ns() - prev + threshold < minFramePeriod;
433 if (minPeriodViolation) {
434 ATRACE_NAME("minPeriodViolation");
435 current = TimePoint::fromNs(prev + minFramePeriod);
436 prev = current.ns();
437 } else {
438 break;
439 }
440 }
441
442 if (!mPastExpectedPresentTimes.empty()) {
443 const auto phase = Duration(mPastExpectedPresentTimes.back() - expectedPresentTime);
444 if (phase > 0ns) {
Ady Abraham9633f8e2024-03-04 19:38:12 +0000445 if (mLastVsyncSequence) {
446 mLastVsyncSequence->vsyncTime += phase.ns();
Ady Abrahame9883032023-11-20 17:54:54 -0800447 }
Ady Abraham4335afd2023-12-18 19:10:47 -0800448 mPastExpectedPresentTimes.clear();
Ady Abrahame9883032023-11-20 17:54:54 -0800449 }
450 }
451}
452
453void VSyncPredictor::onFrameBegin(TimePoint expectedPresentTime,
454 TimePoint lastConfirmedPresentTime) {
Ady Abraham9633f8e2024-03-04 19:38:12 +0000455 ATRACE_CALL();
Ady Abrahame9883032023-11-20 17:54:54 -0800456 std::lock_guard lock(mMutex);
457
458 if (!mDisplayModePtr->getVrrConfig()) return;
459
460 if (CC_UNLIKELY(mTraceOn)) {
461 ATRACE_FORMAT_INSTANT("vsync is %.2f past last signaled fence",
462 static_cast<float>(expectedPresentTime.ns() -
463 lastConfirmedPresentTime.ns()) /
464 1e6f);
465 }
Ady Abrahame9883032023-11-20 17:54:54 -0800466 const auto currentPeriod = mRateMap.find(idealPeriod())->second.slope;
467 const auto threshold = currentPeriod / 2;
Ady Abraham4335afd2023-12-18 19:10:47 -0800468 mPastExpectedPresentTimes.push_back(expectedPresentTime);
Ady Abrahame9883032023-11-20 17:54:54 -0800469
Ady Abrahame9883032023-11-20 17:54:54 -0800470 while (!mPastExpectedPresentTimes.empty()) {
471 const auto front = mPastExpectedPresentTimes.front().ns();
Ady Abraham4335afd2023-12-18 19:10:47 -0800472 const bool frontIsBeforeConfirmed = front < lastConfirmedPresentTime.ns() + threshold;
473 if (frontIsBeforeConfirmed) {
Ady Abrahame9883032023-11-20 17:54:54 -0800474 if (CC_UNLIKELY(mTraceOn)) {
475 ATRACE_FORMAT_INSTANT("Discarding old vsync - %.2f before last signaled fence",
Ady Abraham4335afd2023-12-18 19:10:47 -0800476 static_cast<float>(lastConfirmedPresentTime.ns() - front) /
Ady Abrahame9883032023-11-20 17:54:54 -0800477 1e6f);
478 }
479 mPastExpectedPresentTimes.pop_front();
480 } else {
481 break;
482 }
483 }
484
Ady Abraham9633f8e2024-03-04 19:38:12 +0000485 ensureMinFrameDurationIsKept(expectedPresentTime, lastConfirmedPresentTime);
Ady Abrahame9883032023-11-20 17:54:54 -0800486}
487
488void VSyncPredictor::onFrameMissed(TimePoint expectedPresentTime) {
Ady Abraham9633f8e2024-03-04 19:38:12 +0000489 ATRACE_CALL();
Ady Abrahame9883032023-11-20 17:54:54 -0800490
491 std::lock_guard lock(mMutex);
492 if (!mDisplayModePtr->getVrrConfig()) return;
493
494 // We don't know when the frame is going to be presented, so we assume it missed one vsync
495 const auto currentPeriod = mRateMap.find(idealPeriod())->second.slope;
496 const auto lastConfirmedPresentTime =
497 TimePoint::fromNs(expectedPresentTime.ns() + currentPeriod);
498
Ady Abraham9633f8e2024-03-04 19:38:12 +0000499 ensureMinFrameDurationIsKept(expectedPresentTime, lastConfirmedPresentTime);
500 mLastMissedVsync = expectedPresentTime;
Ady Abrahame9883032023-11-20 17:54:54 -0800501}
502
Ady Abraham0bb6a472020-10-12 10:22:13 -0700503VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModel() const {
504 std::lock_guard lock(mMutex);
Ady Abraham9633f8e2024-03-04 19:38:12 +0000505 const auto model = VSyncPredictor::getVSyncPredictionModelLocked();
506 return {model.slope, model.intercept};
Ady Abraham0bb6a472020-10-12 10:22:13 -0700507}
508
509VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModelLocked() const {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800510 return mRateMap.find(idealPeriod())->second;
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800511}
512
513void VSyncPredictor::clearTimestamps() {
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000514 ATRACE_CALL();
515
Ady Abraham92fa2f42020-02-11 15:33:56 -0800516 if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700517 auto const maxRb = *std::max_element(mTimestamps.begin(), mTimestamps.end());
518 if (mKnownTimestamp) {
519 mKnownTimestamp = std::max(*mKnownTimestamp, maxRb);
520 } else {
521 mKnownTimestamp = maxRb;
522 }
523
Ady Abraham92fa2f42020-02-11 15:33:56 -0800524 mTimestamps.clear();
525 mLastTimestampIndex = 0;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700526 }
527}
528
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700529bool VSyncPredictor::needsMoreSamples() const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700530 std::lock_guard lock(mMutex);
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700531 return mTimestamps.size() < kMinimumSamplesForPrediction;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700532}
533
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800534void VSyncPredictor::resetModel() {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700535 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800536 mRateMap[idealPeriod()] = {idealPeriod(), 0};
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800537 clearTimestamps();
538}
539
Ady Abraham5e7371c2020-03-24 14:47:24 -0700540void VSyncPredictor::dump(std::string& result) const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700541 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800542 StringAppendF(&result, "\tmDisplayModePtr=%s\n", to_string(*mDisplayModePtr).c_str());
Ady Abraham5e7371c2020-03-24 14:47:24 -0700543 StringAppendF(&result, "\tRefresh Rate Map:\n");
Ady Abrahamc585dba2023-11-15 18:41:35 -0800544 for (const auto& [period, periodInterceptTuple] : mRateMap) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700545 StringAppendF(&result,
546 "\t\tFor ideal period %.2fms: period = %.2fms, intercept = %" PRId64 "\n",
Ady Abrahamc585dba2023-11-15 18:41:35 -0800547 period / 1e6f, periodInterceptTuple.slope / 1e6f,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700548 periodInterceptTuple.intercept);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700549 }
550}
551
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700552} // namespace android::scheduler
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800553
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100554// TODO(b/129481165): remove the #pragma below and fix conversion issues
Dominik Laskowski62eff352021-12-06 09:59:41 -0800555#pragma clang diagnostic pop // ignored "-Wextra"