blob: 7379a4605dc84040ee9cf8a2fb9317a2c471ac25 [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 Abrahamc585dba2023-11-15 18:41:35 -080050VSyncPredictor::VSyncPredictor(ftl::NonNull<DisplayModePtr> modePtr, size_t historySize,
ramindanid4354a92023-10-02 15:11:09 -070051 size_t minimumSamplesForPrediction, uint32_t outlierTolerancePercent,
52 IVsyncTrackerCallback& callback)
Ady Abrahamc585dba2023-11-15 18:41:35 -080053 : mId(modePtr->getPhysicalDisplayId()),
Leon Scroggins III67388622023-02-06 20:36:20 -050054 mTraceOn(property_get_bool("debug.sf.vsp_trace", false)),
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080055 kHistorySize(historySize),
Kevin DuBois1678e2c2019-08-22 12:26:24 -070056 kMinimumSamplesForPrediction(minimumSamplesForPrediction),
57 kOutlierTolerancePercent(std::min(outlierTolerancePercent, kMaxPercent)),
ramindanid4354a92023-10-02 15:11:09 -070058 mVsyncTrackerCallback(callback),
Ady Abrahamc585dba2023-11-15 18:41:35 -080059 mDisplayModePtr(modePtr) {
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -080060 resetModel();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070061}
62
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080063inline void VSyncPredictor::traceInt64If(const char* name, int64_t value) const {
64 if (CC_UNLIKELY(mTraceOn)) {
Leon Scroggins III67388622023-02-06 20:36:20 -050065 traceInt64(name, value);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080066 }
67}
68
Ady Abrahamd9b9a042023-01-13 11:30:58 -080069inline void VSyncPredictor::traceInt64(const char* name, int64_t value) const {
Leon Scroggins III67388622023-02-06 20:36:20 -050070 ATRACE_INT64(ftl::Concat(ftl::truncated<14>(name), " ", mId.value).c_str(), value);
Ady Abrahamd9b9a042023-01-13 11:30:58 -080071}
72
Ady Abraham9c53ee72020-07-22 21:16:18 -070073inline size_t VSyncPredictor::next(size_t i) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080074 return (i + 1) % mTimestamps.size();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070075}
76
Ady Abrahamc585dba2023-11-15 18:41:35 -080077nsecs_t VSyncPredictor::idealPeriod() const {
78 return mDisplayModePtr->getVsyncRate().getPeriodNsecs();
79}
80
Kevin DuBois1678e2c2019-08-22 12:26:24 -070081bool VSyncPredictor::validate(nsecs_t timestamp) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080082 if (mLastTimestampIndex < 0 || mTimestamps.empty()) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -070083 return true;
84 }
85
Ady Abrahamc585dba2023-11-15 18:41:35 -080086 const auto aValidTimestamp = mTimestamps[mLastTimestampIndex];
87 const auto percent =
88 (timestamp - aValidTimestamp) % idealPeriod() * kMaxPercent / idealPeriod();
Ady Abraham99ca3362021-06-17 12:28:46 -070089 if (percent >= kOutlierTolerancePercent &&
90 percent <= (kMaxPercent - kOutlierTolerancePercent)) {
91 return false;
92 }
93
94 const auto iter = std::min_element(mTimestamps.begin(), mTimestamps.end(),
95 [timestamp](nsecs_t a, nsecs_t b) {
96 return std::abs(timestamp - a) < std::abs(timestamp - b);
97 });
Ady Abrahamc585dba2023-11-15 18:41:35 -080098 const auto distancePercent = std::abs(*iter - timestamp) * kMaxPercent / idealPeriod();
Ady Abraham99ca3362021-06-17 12:28:46 -070099 if (distancePercent < kOutlierTolerancePercent) {
100 // duplicate timestamp
101 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 Abraham9c53ee72020-07-22 21:16:18 -0700129 std::lock_guard lock(mMutex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700130
131 if (!validate(timestamp)) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700132 // VSR could elect to ignore the incongruent timestamp or resetModel(). If ts is ignored,
Ady Abraham43a3e692020-11-13 12:43:39 -0800133 // don't insert this ts into mTimestamps ringbuffer. If we are still
134 // in the learning phase we should just clear all timestamps and start
135 // over.
136 if (mTimestamps.size() < kMinimumSamplesForPrediction) {
Ady Abraham4c56b642021-06-08 15:03:33 -0700137 // Add the timestamp to mTimestamps before clearing it so we could
138 // update mKnownTimestamp based on the new timestamp.
139 mTimestamps.push_back(timestamp);
Ady Abraham43a3e692020-11-13 12:43:39 -0800140 clearTimestamps();
141 } else if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700142 mKnownTimestamp =
143 std::max(timestamp, *std::max_element(mTimestamps.begin(), mTimestamps.end()));
144 } else {
145 mKnownTimestamp = timestamp;
146 }
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800147 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700148 }
149
Ady Abraham92fa2f42020-02-11 15:33:56 -0800150 if (mTimestamps.size() != kHistorySize) {
151 mTimestamps.push_back(timestamp);
152 mLastTimestampIndex = next(mLastTimestampIndex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700153 } else {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800154 mLastTimestampIndex = next(mLastTimestampIndex);
155 mTimestamps[mLastTimestampIndex] = timestamp;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700156 }
157
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800158 traceInt64If("VSP-ts", timestamp);
159
Dominik Laskowski62eff352021-12-06 09:59:41 -0800160 const size_t numSamples = mTimestamps.size();
161 if (numSamples < kMinimumSamplesForPrediction) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800162 mRateMap[idealPeriod()] = {idealPeriod(), 0};
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800163 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700164 }
165
166 // This is a 'simple linear regression' calculation of Y over X, with Y being the
167 // vsync timestamps, and X being the ordinal of vsync count.
168 // The calculated slope is the vsync period.
169 // Formula for reference:
170 // Sigma_i: means sum over all timestamps.
171 // mean(variable): statistical mean of variable.
172 // X: snapped ordinal of the timestamp
173 // Y: vsync timestamp
174 //
175 // Sigma_i( (X_i - mean(X)) * (Y_i - mean(Y) )
176 // slope = -------------------------------------------
177 // Sigma_i ( X_i - mean(X) ) ^ 2
178 //
179 // intercept = mean(Y) - slope * mean(X)
180 //
Dominik Laskowski62eff352021-12-06 09:59:41 -0800181 std::vector<nsecs_t> vsyncTS(numSamples);
182 std::vector<nsecs_t> ordinals(numSamples);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700183
Dominik Laskowski62eff352021-12-06 09:59:41 -0800184 // Normalizing to the oldest timestamp cuts down on error in calculating the intercept.
185 const auto oldestTS = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Ady Abrahamc585dba2023-11-15 18:41:35 -0800186 auto it = mRateMap.find(idealPeriod());
Ady Abraham0bb6a472020-10-12 10:22:13 -0700187 auto const currentPeriod = it->second.slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700188
Dominik Laskowski62eff352021-12-06 09:59:41 -0800189 // The mean of the ordinals must be precise for the intercept calculation, so scale them up for
190 // fixed-point arithmetic.
191 constexpr int64_t kScalingFactor = 1000;
192
193 nsecs_t meanTS = 0;
194 nsecs_t meanOrdinal = 0;
195
196 for (size_t i = 0; i < numSamples; i++) {
Dominik Laskowski62eff352021-12-06 09:59:41 -0800197 const auto timestamp = mTimestamps[i] - oldestTS;
198 vsyncTS[i] = timestamp;
199 meanTS += timestamp;
200
Rachel Lee934017e2022-08-10 15:34:14 -0700201 const auto ordinal = currentPeriod == 0
202 ? 0
203 : (vsyncTS[i] + currentPeriod / 2) / currentPeriod * kScalingFactor;
Dominik Laskowski62eff352021-12-06 09:59:41 -0800204 ordinals[i] = ordinal;
205 meanOrdinal += ordinal;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700206 }
207
Dominik Laskowski62eff352021-12-06 09:59:41 -0800208 meanTS /= numSamples;
209 meanOrdinal /= numSamples;
210
211 for (size_t i = 0; i < numSamples; i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700212 vsyncTS[i] -= meanTS;
213 ordinals[i] -= meanOrdinal;
214 }
215
Dominik Laskowski62eff352021-12-06 09:59:41 -0800216 nsecs_t top = 0;
217 nsecs_t bottom = 0;
218 for (size_t i = 0; i < numSamples; i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700219 top += vsyncTS[i] * ordinals[i];
220 bottom += ordinals[i] * ordinals[i];
221 }
222
223 if (CC_UNLIKELY(bottom == 0)) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800224 it->second = {idealPeriod(), 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800225 clearTimestamps();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800226 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700227 }
228
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700229 nsecs_t const anticipatedPeriod = top * kScalingFactor / bottom;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700230 nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
231
Ady Abrahamc585dba2023-11-15 18:41:35 -0800232 auto const percent = std::abs(anticipatedPeriod - idealPeriod()) * kMaxPercent / idealPeriod();
Ady Abraham92fa2f42020-02-11 15:33:56 -0800233 if (percent >= kOutlierTolerancePercent) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800234 it->second = {idealPeriod(), 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800235 clearTimestamps();
236 return false;
237 }
238
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800239 traceInt64If("VSP-period", anticipatedPeriod);
240 traceInt64If("VSP-intercept", intercept);
241
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700242 it->second = {anticipatedPeriod, intercept};
243
Leon Scroggins III67388622023-02-06 20:36:20 -0500244 ALOGV("model update ts %" PRIu64 ": %" PRId64 " slope: %" PRId64 " intercept: %" PRId64,
245 mId.value, timestamp, anticipatedPeriod, intercept);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800246 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700247}
248
Ady Abrahamf34a8132023-02-13 20:49:48 -0800249auto VSyncPredictor::getVsyncSequenceLocked(nsecs_t timestamp) const -> VsyncSequence {
250 const auto vsync = nextAnticipatedVSyncTimeFromLocked(timestamp);
251 if (!mLastVsyncSequence) return {vsync, 0};
252
253 const auto [slope, _] = getVSyncPredictionModelLocked();
254 const auto [lastVsyncTime, lastVsyncSequence] = *mLastVsyncSequence;
255 const auto vsyncSequence = lastVsyncSequence +
256 static_cast<int64_t>(std::round((vsync - lastVsyncTime) / static_cast<float>(slope)));
257 return {vsync, vsyncSequence};
258}
259
Ady Abraham0bb6a472020-10-12 10:22:13 -0700260nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFromLocked(nsecs_t timePoint) const {
261 auto const [slope, intercept] = getVSyncPredictionModelLocked();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700262
Ady Abraham92fa2f42020-02-11 15:33:56 -0800263 if (mTimestamps.empty()) {
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800264 traceInt64("VSP-mode", 1);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700265 auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800266 auto const numPeriodsOut = ((timePoint - knownTimestamp) / idealPeriod()) + 1;
267 return knownTimestamp + numPeriodsOut * idealPeriod();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700268 }
269
Ady Abraham92fa2f42020-02-11 15:33:56 -0800270 auto const oldest = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois127a2d92019-12-04 13:52:52 -0800271
272 // See b/145667109, the ordinal calculation must take into account the intercept.
273 auto const zeroPoint = oldest + intercept;
274 auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700275 auto const prediction = (ordinalRequest * slope) + intercept + oldest;
276
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800277 traceInt64("VSP-mode", 0);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800278 traceInt64If("VSP-timePoint", timePoint);
279 traceInt64If("VSP-prediction", prediction);
280
Kevin DuBois127a2d92019-12-04 13:52:52 -0800281 auto const printer = [&, slope = slope, intercept = intercept] {
282 std::stringstream str;
283 str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
284 << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
285 << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
286 return str.str();
287 };
288
289 ALOGV("%s", printer().c_str());
290 LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
291 printer().c_str());
292
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700293 return prediction;
294}
295
Ady Abraham0bb6a472020-10-12 10:22:13 -0700296nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint) const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700297 std::lock_guard lock(mMutex);
Ady Abrahamace3d052022-11-17 16:25:05 -0800298
Ady Abrahamf34a8132023-02-13 20:49:48 -0800299 // update the mLastVsyncSequence for reference point
300 mLastVsyncSequence = getVsyncSequenceLocked(timePoint);
301
Ady Abrahamfdc049c2023-02-17 14:52:05 +0000302 const auto renderRatePhase = [&]() REQUIRES(mMutex) -> int {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800303 if (!mRenderRateOpt) return 0;
Ady Abrahamfdc049c2023-02-17 14:52:05 +0000304 const auto divisor =
Ady Abrahamc585dba2023-11-15 18:41:35 -0800305 RefreshRateSelector::getFrameRateDivisor(Fps::fromPeriodNsecs(idealPeriod()),
306 *mRenderRateOpt);
Ady Abrahamfdc049c2023-02-17 14:52:05 +0000307 if (divisor <= 1) return 0;
308
Ady Abrahame9883032023-11-20 17:54:54 -0800309 int mod = mLastVsyncSequence->seq % divisor;
Ady Abrahamfdc049c2023-02-17 14:52:05 +0000310 if (mod == 0) return 0;
311
Ady Abrahame9883032023-11-20 17:54:54 -0800312 // This is actually a bug fix, but guarded with vrr_config since we found it with this
313 // config
314 if (FlagManager::getInstance().vrr_config()) {
315 if (mod < 0) mod += divisor;
316 }
317
Ady Abrahamfdc049c2023-02-17 14:52:05 +0000318 return divisor - mod;
319 }();
320
321 if (renderRatePhase == 0) {
ramindanid4354a92023-10-02 15:11:09 -0700322 const auto vsyncTime = mLastVsyncSequence->vsyncTime;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800323 if (FlagManager::getInstance().vrr_config()) {
ramindani2c65b0d2023-10-30 10:37:31 -0700324 const auto vsyncTimePoint = TimePoint::fromNs(vsyncTime);
325 ATRACE_FORMAT("%s InPhase vsyncIn %.2fms", __func__,
326 ticks<std::milli, float>(vsyncTimePoint - TimePoint::now()));
Ady Abrahamc585dba2023-11-15 18:41:35 -0800327 const Fps renderRate = mRenderRateOpt ? *mRenderRateOpt : mDisplayModePtr->getPeakFps();
328 mVsyncTrackerCallback.onVsyncGenerated(vsyncTimePoint, mDisplayModePtr, renderRate);
ramindanid4354a92023-10-02 15:11:09 -0700329 }
330 return vsyncTime;
Ady Abrahamace3d052022-11-17 16:25:05 -0800331 }
Ady Abrahamf34a8132023-02-13 20:49:48 -0800332
333 auto const [slope, intercept] = getVSyncPredictionModelLocked();
Ady Abrahamfdc049c2023-02-17 14:52:05 +0000334 const auto approximateNextVsync = mLastVsyncSequence->vsyncTime + slope * renderRatePhase;
ramindanid4354a92023-10-02 15:11:09 -0700335 const auto nextAnticipatedVsyncTime =
336 nextAnticipatedVSyncTimeFromLocked(approximateNextVsync - slope / 2);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800337 if (FlagManager::getInstance().vrr_config()) {
ramindani2c65b0d2023-10-30 10:37:31 -0700338 const auto nextAnticipatedVsyncTimePoint = TimePoint::fromNs(nextAnticipatedVsyncTime);
339 ATRACE_FORMAT("%s outOfPhase vsyncIn %.2fms", __func__,
340 ticks<std::milli, float>(nextAnticipatedVsyncTimePoint - TimePoint::now()));
Ady Abrahamc585dba2023-11-15 18:41:35 -0800341 const Fps renderRate = mRenderRateOpt ? *mRenderRateOpt : mDisplayModePtr->getPeakFps();
342 mVsyncTrackerCallback.onVsyncGenerated(nextAnticipatedVsyncTimePoint, mDisplayModePtr,
343 renderRate);
ramindanid4354a92023-10-02 15:11:09 -0700344 }
345 return nextAnticipatedVsyncTime;
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 Abraham5cc2e262021-03-25 13:09:17 -0700356bool VSyncPredictor::isVSyncInPhase(nsecs_t timePoint, Fps frameRate) const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800357 std::lock_guard lock(mMutex);
358 const auto divisor =
Ady Abrahamc585dba2023-11-15 18:41:35 -0800359 RefreshRateSelector::getFrameRateDivisor(Fps::fromPeriodNsecs(idealPeriod()),
360 frameRate);
Ady Abrahamace3d052022-11-17 16:25:05 -0800361 return isVSyncInPhaseLocked(timePoint, static_cast<unsigned>(divisor));
362}
363
364bool VSyncPredictor::isVSyncInPhaseLocked(nsecs_t timePoint, unsigned divisor) const {
Ady Abraham9243bba2023-02-10 15:31:14 -0800365 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
Ady Abrahamcc315492022-02-17 17:06:39 -0800372 if (divisor <= 1 || timePoint == 0) {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700373 return true;
374 }
375
Ady Abrahamc585dba2023-11-15 18:41:35 -0800376 const nsecs_t period = mRateMap[idealPeriod()].slope;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700377 const nsecs_t justBeforeTimePoint = timePoint - period / 2;
Ady Abrahamf34a8132023-02-13 20:49:48 -0800378 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(),
400 timeout ? std::to_string(timeout->notifyExpectedPresentTimeoutNs).c_str() : "N/A");
401 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 Abrahame9883032023-11-20 17:54:54 -0800418void VSyncPredictor::ensureMinFrameDurationIsKept(TimePoint expectedPresentTime,
419 TimePoint lastConfirmedPresentTime) {
420 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) {
445 if (mLastVsyncSequence) {
446 mLastVsyncSequence->vsyncTime += phase.ns();
447 }
448 }
449 }
450}
451
452void VSyncPredictor::onFrameBegin(TimePoint expectedPresentTime,
453 TimePoint lastConfirmedPresentTime) {
454 ATRACE_CALL();
455 std::lock_guard lock(mMutex);
456
457 if (!mDisplayModePtr->getVrrConfig()) return;
458
459 if (CC_UNLIKELY(mTraceOn)) {
460 ATRACE_FORMAT_INSTANT("vsync is %.2f past last signaled fence",
461 static_cast<float>(expectedPresentTime.ns() -
462 lastConfirmedPresentTime.ns()) /
463 1e6f);
464 }
465 mPastExpectedPresentTimes.push_back(expectedPresentTime);
466
467 const auto currentPeriod = mRateMap.find(idealPeriod())->second.slope;
468 const auto threshold = currentPeriod / 2;
469
470 const auto minFramePeriod = minFramePeriodLocked().ns();
471 while (!mPastExpectedPresentTimes.empty()) {
472 const auto front = mPastExpectedPresentTimes.front().ns();
473 const bool frontIsLastConfirmed =
474 std::abs(front - lastConfirmedPresentTime.ns()) < threshold;
475 const bool frontIsBeforeConfirmed =
476 front < lastConfirmedPresentTime.ns() - minFramePeriod + threshold;
477 if (frontIsLastConfirmed || frontIsBeforeConfirmed) {
478 if (CC_UNLIKELY(mTraceOn)) {
479 ATRACE_FORMAT_INSTANT("Discarding old vsync - %.2f before last signaled fence",
480 static_cast<float>(lastConfirmedPresentTime.ns() -
481 mPastExpectedPresentTimes.front().ns()) /
482 1e6f);
483 }
484 mPastExpectedPresentTimes.pop_front();
485 } else {
486 break;
487 }
488 }
489
490 ensureMinFrameDurationIsKept(expectedPresentTime, lastConfirmedPresentTime);
491}
492
493void VSyncPredictor::onFrameMissed(TimePoint expectedPresentTime) {
494 ATRACE_CALL();
495
496 std::lock_guard lock(mMutex);
497 if (!mDisplayModePtr->getVrrConfig()) return;
498
499 // We don't know when the frame is going to be presented, so we assume it missed one vsync
500 const auto currentPeriod = mRateMap.find(idealPeriod())->second.slope;
501 const auto lastConfirmedPresentTime =
502 TimePoint::fromNs(expectedPresentTime.ns() + currentPeriod);
503
504 ensureMinFrameDurationIsKept(expectedPresentTime, lastConfirmedPresentTime);
505}
506
Ady Abraham0bb6a472020-10-12 10:22:13 -0700507VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModel() const {
508 std::lock_guard lock(mMutex);
509 const auto model = VSyncPredictor::getVSyncPredictionModelLocked();
510 return {model.slope, model.intercept};
511}
512
513VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModelLocked() const {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800514 return mRateMap.find(idealPeriod())->second;
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800515}
516
517void VSyncPredictor::clearTimestamps() {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800518 if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700519 auto const maxRb = *std::max_element(mTimestamps.begin(), mTimestamps.end());
520 if (mKnownTimestamp) {
521 mKnownTimestamp = std::max(*mKnownTimestamp, maxRb);
522 } else {
523 mKnownTimestamp = maxRb;
524 }
525
Ady Abraham92fa2f42020-02-11 15:33:56 -0800526 mTimestamps.clear();
527 mLastTimestampIndex = 0;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700528 }
529}
530
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700531bool VSyncPredictor::needsMoreSamples() const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700532 std::lock_guard lock(mMutex);
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700533 return mTimestamps.size() < kMinimumSamplesForPrediction;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700534}
535
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800536void VSyncPredictor::resetModel() {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700537 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800538 mRateMap[idealPeriod()] = {idealPeriod(), 0};
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800539 clearTimestamps();
540}
541
Ady Abraham5e7371c2020-03-24 14:47:24 -0700542void VSyncPredictor::dump(std::string& result) const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700543 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800544 StringAppendF(&result, "\tmDisplayModePtr=%s\n", to_string(*mDisplayModePtr).c_str());
Ady Abraham5e7371c2020-03-24 14:47:24 -0700545 StringAppendF(&result, "\tRefresh Rate Map:\n");
Ady Abrahamc585dba2023-11-15 18:41:35 -0800546 for (const auto& [period, periodInterceptTuple] : mRateMap) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700547 StringAppendF(&result,
548 "\t\tFor ideal period %.2fms: period = %.2fms, intercept = %" PRId64 "\n",
Ady Abrahamc585dba2023-11-15 18:41:35 -0800549 period / 1e6f, periodInterceptTuple.slope / 1e6f,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700550 periodInterceptTuple.intercept);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700551 }
552}
553
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700554} // namespace android::scheduler
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800555
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100556// TODO(b/129481165): remove the #pragma below and fix conversion issues
Dominik Laskowski62eff352021-12-06 09:59:41 -0800557#pragma clang diagnostic pop // ignored "-Wextra"