blob: acb7265fc5094bf9e37835b79aea0d2a6da1b59a [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
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800111bool VSyncPredictor::addVsyncTimestamp(nsecs_t timestamp) {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700112 std::lock_guard lock(mMutex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700113
114 if (!validate(timestamp)) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700115 // VSR could elect to ignore the incongruent timestamp or resetModel(). If ts is ignored,
Ady Abraham43a3e692020-11-13 12:43:39 -0800116 // don't insert this ts into mTimestamps ringbuffer. If we are still
117 // in the learning phase we should just clear all timestamps and start
118 // over.
119 if (mTimestamps.size() < kMinimumSamplesForPrediction) {
Ady Abraham4c56b642021-06-08 15:03:33 -0700120 // Add the timestamp to mTimestamps before clearing it so we could
121 // update mKnownTimestamp based on the new timestamp.
122 mTimestamps.push_back(timestamp);
Ady Abraham43a3e692020-11-13 12:43:39 -0800123 clearTimestamps();
124 } else if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700125 mKnownTimestamp =
126 std::max(timestamp, *std::max_element(mTimestamps.begin(), mTimestamps.end()));
127 } else {
128 mKnownTimestamp = timestamp;
129 }
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800130 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700131 }
132
Ady Abraham92fa2f42020-02-11 15:33:56 -0800133 if (mTimestamps.size() != kHistorySize) {
134 mTimestamps.push_back(timestamp);
135 mLastTimestampIndex = next(mLastTimestampIndex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700136 } else {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800137 mLastTimestampIndex = next(mLastTimestampIndex);
138 mTimestamps[mLastTimestampIndex] = timestamp;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700139 }
140
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800141 traceInt64If("VSP-ts", timestamp);
142
Dominik Laskowski62eff352021-12-06 09:59:41 -0800143 const size_t numSamples = mTimestamps.size();
144 if (numSamples < kMinimumSamplesForPrediction) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800145 mRateMap[idealPeriod()] = {idealPeriod(), 0};
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800146 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700147 }
148
149 // This is a 'simple linear regression' calculation of Y over X, with Y being the
150 // vsync timestamps, and X being the ordinal of vsync count.
151 // The calculated slope is the vsync period.
152 // Formula for reference:
153 // Sigma_i: means sum over all timestamps.
154 // mean(variable): statistical mean of variable.
155 // X: snapped ordinal of the timestamp
156 // Y: vsync timestamp
157 //
158 // Sigma_i( (X_i - mean(X)) * (Y_i - mean(Y) )
159 // slope = -------------------------------------------
160 // Sigma_i ( X_i - mean(X) ) ^ 2
161 //
162 // intercept = mean(Y) - slope * mean(X)
163 //
Dominik Laskowski62eff352021-12-06 09:59:41 -0800164 std::vector<nsecs_t> vsyncTS(numSamples);
165 std::vector<nsecs_t> ordinals(numSamples);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700166
Dominik Laskowski62eff352021-12-06 09:59:41 -0800167 // Normalizing to the oldest timestamp cuts down on error in calculating the intercept.
168 const auto oldestTS = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Ady Abrahamc585dba2023-11-15 18:41:35 -0800169 auto it = mRateMap.find(idealPeriod());
Ady Abraham0bb6a472020-10-12 10:22:13 -0700170 auto const currentPeriod = it->second.slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700171
Dominik Laskowski62eff352021-12-06 09:59:41 -0800172 // The mean of the ordinals must be precise for the intercept calculation, so scale them up for
173 // fixed-point arithmetic.
174 constexpr int64_t kScalingFactor = 1000;
175
176 nsecs_t meanTS = 0;
177 nsecs_t meanOrdinal = 0;
178
179 for (size_t i = 0; i < numSamples; i++) {
Dominik Laskowski62eff352021-12-06 09:59:41 -0800180 const auto timestamp = mTimestamps[i] - oldestTS;
181 vsyncTS[i] = timestamp;
182 meanTS += timestamp;
183
Rachel Lee934017e2022-08-10 15:34:14 -0700184 const auto ordinal = currentPeriod == 0
185 ? 0
186 : (vsyncTS[i] + currentPeriod / 2) / currentPeriod * kScalingFactor;
Dominik Laskowski62eff352021-12-06 09:59:41 -0800187 ordinals[i] = ordinal;
188 meanOrdinal += ordinal;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700189 }
190
Dominik Laskowski62eff352021-12-06 09:59:41 -0800191 meanTS /= numSamples;
192 meanOrdinal /= numSamples;
193
194 for (size_t i = 0; i < numSamples; i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700195 vsyncTS[i] -= meanTS;
196 ordinals[i] -= meanOrdinal;
197 }
198
Dominik Laskowski62eff352021-12-06 09:59:41 -0800199 nsecs_t top = 0;
200 nsecs_t bottom = 0;
201 for (size_t i = 0; i < numSamples; i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700202 top += vsyncTS[i] * ordinals[i];
203 bottom += ordinals[i] * ordinals[i];
204 }
205
206 if (CC_UNLIKELY(bottom == 0)) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800207 it->second = {idealPeriod(), 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800208 clearTimestamps();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800209 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700210 }
211
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700212 nsecs_t const anticipatedPeriod = top * kScalingFactor / bottom;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700213 nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
214
Ady Abrahamc585dba2023-11-15 18:41:35 -0800215 auto const percent = std::abs(anticipatedPeriod - idealPeriod()) * kMaxPercent / idealPeriod();
Ady Abraham92fa2f42020-02-11 15:33:56 -0800216 if (percent >= kOutlierTolerancePercent) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800217 it->second = {idealPeriod(), 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800218 clearTimestamps();
219 return false;
220 }
221
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800222 traceInt64If("VSP-period", anticipatedPeriod);
223 traceInt64If("VSP-intercept", intercept);
224
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700225 it->second = {anticipatedPeriod, intercept};
226
Leon Scroggins III67388622023-02-06 20:36:20 -0500227 ALOGV("model update ts %" PRIu64 ": %" PRId64 " slope: %" PRId64 " intercept: %" PRId64,
228 mId.value, timestamp, anticipatedPeriod, intercept);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800229 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700230}
231
Ady Abrahamf34a8132023-02-13 20:49:48 -0800232auto VSyncPredictor::getVsyncSequenceLocked(nsecs_t timestamp) const -> VsyncSequence {
233 const auto vsync = nextAnticipatedVSyncTimeFromLocked(timestamp);
234 if (!mLastVsyncSequence) return {vsync, 0};
235
236 const auto [slope, _] = getVSyncPredictionModelLocked();
237 const auto [lastVsyncTime, lastVsyncSequence] = *mLastVsyncSequence;
238 const auto vsyncSequence = lastVsyncSequence +
239 static_cast<int64_t>(std::round((vsync - lastVsyncTime) / static_cast<float>(slope)));
240 return {vsync, vsyncSequence};
241}
242
Ady Abraham0bb6a472020-10-12 10:22:13 -0700243nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFromLocked(nsecs_t timePoint) const {
244 auto const [slope, intercept] = getVSyncPredictionModelLocked();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700245
Ady Abraham92fa2f42020-02-11 15:33:56 -0800246 if (mTimestamps.empty()) {
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800247 traceInt64("VSP-mode", 1);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700248 auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800249 auto const numPeriodsOut = ((timePoint - knownTimestamp) / idealPeriod()) + 1;
250 return knownTimestamp + numPeriodsOut * idealPeriod();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700251 }
252
Ady Abraham92fa2f42020-02-11 15:33:56 -0800253 auto const oldest = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois127a2d92019-12-04 13:52:52 -0800254
255 // See b/145667109, the ordinal calculation must take into account the intercept.
256 auto const zeroPoint = oldest + intercept;
257 auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700258 auto const prediction = (ordinalRequest * slope) + intercept + oldest;
259
Ady Abrahamd9b9a042023-01-13 11:30:58 -0800260 traceInt64("VSP-mode", 0);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800261 traceInt64If("VSP-timePoint", timePoint);
262 traceInt64If("VSP-prediction", prediction);
263
Kevin DuBois127a2d92019-12-04 13:52:52 -0800264 auto const printer = [&, slope = slope, intercept = intercept] {
265 std::stringstream str;
266 str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
267 << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
268 << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
269 return str.str();
270 };
271
272 ALOGV("%s", printer().c_str());
273 LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
274 printer().c_str());
275
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700276 return prediction;
277}
278
Ady Abraham0bb6a472020-10-12 10:22:13 -0700279nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint) const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700280 std::lock_guard lock(mMutex);
Ady Abrahamace3d052022-11-17 16:25:05 -0800281
Ady Abrahamf34a8132023-02-13 20:49:48 -0800282 // update the mLastVsyncSequence for reference point
283 mLastVsyncSequence = getVsyncSequenceLocked(timePoint);
284
Ady Abrahamfdc049c2023-02-17 14:52:05 +0000285 const auto renderRatePhase = [&]() REQUIRES(mMutex) -> int {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800286 if (!mRenderRateOpt) return 0;
Ady Abrahamfdc049c2023-02-17 14:52:05 +0000287
288 const auto divisor =
Ady Abrahamc585dba2023-11-15 18:41:35 -0800289 RefreshRateSelector::getFrameRateDivisor(Fps::fromPeriodNsecs(idealPeriod()),
290 *mRenderRateOpt);
Ady Abrahamfdc049c2023-02-17 14:52:05 +0000291 if (divisor <= 1) return 0;
292
293 const int mod = mLastVsyncSequence->seq % divisor;
294 if (mod == 0) return 0;
295
296 return divisor - mod;
297 }();
298
299 if (renderRatePhase == 0) {
ramindanid4354a92023-10-02 15:11:09 -0700300 const auto vsyncTime = mLastVsyncSequence->vsyncTime;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800301 if (FlagManager::getInstance().vrr_config()) {
ramindani2c65b0d2023-10-30 10:37:31 -0700302 const auto vsyncTimePoint = TimePoint::fromNs(vsyncTime);
303 ATRACE_FORMAT("%s InPhase vsyncIn %.2fms", __func__,
304 ticks<std::milli, float>(vsyncTimePoint - TimePoint::now()));
Ady Abrahamc585dba2023-11-15 18:41:35 -0800305 const Fps renderRate = mRenderRateOpt ? *mRenderRateOpt : mDisplayModePtr->getPeakFps();
306 mVsyncTrackerCallback.onVsyncGenerated(vsyncTimePoint, mDisplayModePtr, renderRate);
ramindanid4354a92023-10-02 15:11:09 -0700307 }
308 return vsyncTime;
Ady Abrahamace3d052022-11-17 16:25:05 -0800309 }
Ady Abrahamf34a8132023-02-13 20:49:48 -0800310
311 auto const [slope, intercept] = getVSyncPredictionModelLocked();
Ady Abrahamfdc049c2023-02-17 14:52:05 +0000312 const auto approximateNextVsync = mLastVsyncSequence->vsyncTime + slope * renderRatePhase;
ramindanid4354a92023-10-02 15:11:09 -0700313 const auto nextAnticipatedVsyncTime =
314 nextAnticipatedVSyncTimeFromLocked(approximateNextVsync - slope / 2);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800315 if (FlagManager::getInstance().vrr_config()) {
ramindani2c65b0d2023-10-30 10:37:31 -0700316 const auto nextAnticipatedVsyncTimePoint = TimePoint::fromNs(nextAnticipatedVsyncTime);
317 ATRACE_FORMAT("%s outOfPhase vsyncIn %.2fms", __func__,
318 ticks<std::milli, float>(nextAnticipatedVsyncTimePoint - TimePoint::now()));
Ady Abrahamc585dba2023-11-15 18:41:35 -0800319 const Fps renderRate = mRenderRateOpt ? *mRenderRateOpt : mDisplayModePtr->getPeakFps();
320 mVsyncTrackerCallback.onVsyncGenerated(nextAnticipatedVsyncTimePoint, mDisplayModePtr,
321 renderRate);
ramindanid4354a92023-10-02 15:11:09 -0700322 }
323 return nextAnticipatedVsyncTime;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700324}
325
Ady Abraham0bb6a472020-10-12 10:22:13 -0700326/*
Ady Abraham5cc2e262021-03-25 13:09:17 -0700327 * Returns whether a given vsync timestamp is in phase with a frame rate.
Ady Abrahamcc315492022-02-17 17:06:39 -0800328 * 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 -0700329 * For example, if the vsync timestamps are (16.6,33.3,50.0,66.6):
330 * isVSyncInPhase(16.6, 30) = true
331 * isVSyncInPhase(33.3, 30) = false
332 * isVSyncInPhase(50.0, 30) = true
Ady Abraham0bb6a472020-10-12 10:22:13 -0700333 */
Ady Abraham5cc2e262021-03-25 13:09:17 -0700334bool VSyncPredictor::isVSyncInPhase(nsecs_t timePoint, Fps frameRate) const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800335 std::lock_guard lock(mMutex);
336 const auto divisor =
Ady Abrahamc585dba2023-11-15 18:41:35 -0800337 RefreshRateSelector::getFrameRateDivisor(Fps::fromPeriodNsecs(idealPeriod()),
338 frameRate);
Ady Abrahamace3d052022-11-17 16:25:05 -0800339 return isVSyncInPhaseLocked(timePoint, static_cast<unsigned>(divisor));
340}
341
342bool VSyncPredictor::isVSyncInPhaseLocked(nsecs_t timePoint, unsigned divisor) const {
Ady Abraham9243bba2023-02-10 15:31:14 -0800343 const TimePoint now = TimePoint::now();
344 const auto getTimePointIn = [](TimePoint now, nsecs_t timePoint) -> float {
345 return ticks<std::milli, float>(TimePoint::fromNs(timePoint) - now);
346 };
347 ATRACE_FORMAT("%s timePoint in: %.2f divisor: %zu", __func__, getTimePointIn(now, timePoint),
348 divisor);
349
Ady Abrahamcc315492022-02-17 17:06:39 -0800350 if (divisor <= 1 || timePoint == 0) {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700351 return true;
352 }
353
Ady Abrahamc585dba2023-11-15 18:41:35 -0800354 const nsecs_t period = mRateMap[idealPeriod()].slope;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700355 const nsecs_t justBeforeTimePoint = timePoint - period / 2;
Ady Abrahamf34a8132023-02-13 20:49:48 -0800356 const auto vsyncSequence = getVsyncSequenceLocked(justBeforeTimePoint);
357 ATRACE_FORMAT_INSTANT("vsync in: %.2f sequence: %" PRId64,
358 getTimePointIn(now, vsyncSequence.vsyncTime), vsyncSequence.seq);
359 return vsyncSequence.seq % divisor == 0;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700360}
361
Ady Abrahamc585dba2023-11-15 18:41:35 -0800362void VSyncPredictor::setRenderRate(Fps renderRate) {
363 ATRACE_FORMAT("%s %s", __func__, to_string(renderRate).c_str());
364 ALOGV("%s %s: RenderRate %s ", __func__, to_string(mId).c_str(), to_string(renderRate).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800365 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800366 mRenderRateOpt = renderRate;
367}
368
369void VSyncPredictor::setDisplayModePtr(ftl::NonNull<DisplayModePtr> modePtr) {
370 LOG_ALWAYS_FATAL_IF(mId != modePtr->getPhysicalDisplayId(),
371 "mode does not belong to the display");
372 ATRACE_FORMAT("%s %s", __func__, to_string(*modePtr).c_str());
373 const auto timeout = modePtr->getVrrConfig()
374 ? modePtr->getVrrConfig()->notifyExpectedPresentConfig
375 : std::nullopt;
376 ALOGV("%s %s: DisplayMode %s notifyExpectedPresentTimeout %s", __func__, to_string(mId).c_str(),
377 to_string(*modePtr).c_str(),
378 timeout ? std::to_string(timeout->notifyExpectedPresentTimeoutNs).c_str() : "N/A");
379 std::lock_guard lock(mMutex);
380
381 mDisplayModePtr = modePtr;
382 traceInt64("VSP-setPeriod", modePtr->getVsyncRate().getPeriodNsecs());
383
384 static constexpr size_t kSizeLimit = 30;
385 if (CC_UNLIKELY(mRateMap.size() == kSizeLimit)) {
386 mRateMap.erase(mRateMap.begin());
387 }
388
389 if (mRateMap.find(idealPeriod()) == mRateMap.end()) {
390 mRateMap[idealPeriod()] = {idealPeriod(), 0};
391 }
392
393 clearTimestamps();
Ady Abrahamace3d052022-11-17 16:25:05 -0800394}
395
Ady Abraham0bb6a472020-10-12 10:22:13 -0700396VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModel() const {
397 std::lock_guard lock(mMutex);
398 const auto model = VSyncPredictor::getVSyncPredictionModelLocked();
399 return {model.slope, model.intercept};
400}
401
402VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModelLocked() const {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800403 return mRateMap.find(idealPeriod())->second;
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800404}
405
406void VSyncPredictor::clearTimestamps() {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800407 if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700408 auto const maxRb = *std::max_element(mTimestamps.begin(), mTimestamps.end());
409 if (mKnownTimestamp) {
410 mKnownTimestamp = std::max(*mKnownTimestamp, maxRb);
411 } else {
412 mKnownTimestamp = maxRb;
413 }
414
Ady Abraham92fa2f42020-02-11 15:33:56 -0800415 mTimestamps.clear();
416 mLastTimestampIndex = 0;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700417 }
418}
419
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700420bool VSyncPredictor::needsMoreSamples() const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700421 std::lock_guard lock(mMutex);
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700422 return mTimestamps.size() < kMinimumSamplesForPrediction;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700423}
424
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800425void VSyncPredictor::resetModel() {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700426 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800427 mRateMap[idealPeriod()] = {idealPeriod(), 0};
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800428 clearTimestamps();
429}
430
Ady Abraham5e7371c2020-03-24 14:47:24 -0700431void VSyncPredictor::dump(std::string& result) const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700432 std::lock_guard lock(mMutex);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800433 StringAppendF(&result, "\tmDisplayModePtr=%s\n", to_string(*mDisplayModePtr).c_str());
Ady Abraham5e7371c2020-03-24 14:47:24 -0700434 StringAppendF(&result, "\tRefresh Rate Map:\n");
Ady Abrahamc585dba2023-11-15 18:41:35 -0800435 for (const auto& [period, periodInterceptTuple] : mRateMap) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700436 StringAppendF(&result,
437 "\t\tFor ideal period %.2fms: period = %.2fms, intercept = %" PRId64 "\n",
Ady Abrahamc585dba2023-11-15 18:41:35 -0800438 period / 1e6f, periodInterceptTuple.slope / 1e6f,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700439 periodInterceptTuple.intercept);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700440 }
441}
442
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700443} // namespace android::scheduler
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800444
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100445// TODO(b/129481165): remove the #pragma below and fix conversion issues
Dominik Laskowski62eff352021-12-06 09:59:41 -0800446#pragma clang diagnostic pop // ignored "-Wextra"