blob: 329e4a0eb47160343e74ee6e6007c0e95149a37f [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
Kevin DuBois1678e2c2019-08-22 12:26:24 -070021#define ATRACE_TAG ATRACE_TAG_GRAPHICS
22//#define LOG_NDEBUG 0
23#include "VSyncPredictor.h"
24#include <android-base/logging.h>
Ady Abraham5e7371c2020-03-24 14:47:24 -070025#include <android-base/stringprintf.h>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070026#include <cutils/compiler.h>
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080027#include <cutils/properties.h>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070028#include <utils/Log.h>
29#include <utils/Trace.h>
30#include <algorithm>
31#include <chrono>
Kevin DuBois127a2d92019-12-04 13:52:52 -080032#include <sstream>
Ady Abraham5cc2e262021-03-25 13:09:17 -070033#include "RefreshRateConfigs.h"
Kevin DuBois1678e2c2019-08-22 12:26:24 -070034
Ady Abraham0bb6a472020-10-12 10:22:13 -070035#undef LOG_TAG
36#define LOG_TAG "VSyncPredictor"
37
Kevin DuBois1678e2c2019-08-22 12:26:24 -070038namespace android::scheduler {
Ady Abraham5e7371c2020-03-24 14:47:24 -070039using base::StringAppendF;
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080040
Kevin DuBois1678e2c2019-08-22 12:26:24 -070041static auto constexpr kMaxPercent = 100u;
42
43VSyncPredictor::~VSyncPredictor() = default;
44
45VSyncPredictor::VSyncPredictor(nsecs_t idealPeriod, size_t historySize,
46 size_t minimumSamplesForPrediction, uint32_t outlierTolerancePercent)
Kevin DuBoisc57f2c32019-12-20 16:32:29 -080047 : mTraceOn(property_get_bool("debug.sf.vsp_trace", true)),
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080048 kHistorySize(historySize),
Kevin DuBois1678e2c2019-08-22 12:26:24 -070049 kMinimumSamplesForPrediction(minimumSamplesForPrediction),
50 kOutlierTolerancePercent(std::min(outlierTolerancePercent, kMaxPercent)),
51 mIdealPeriod(idealPeriod) {
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -080052 resetModel();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070053}
54
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080055inline void VSyncPredictor::traceInt64If(const char* name, int64_t value) const {
56 if (CC_UNLIKELY(mTraceOn)) {
57 ATRACE_INT64(name, value);
58 }
59}
60
Ady Abraham9c53ee72020-07-22 21:16:18 -070061inline size_t VSyncPredictor::next(size_t i) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080062 return (i + 1) % mTimestamps.size();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070063}
64
65bool VSyncPredictor::validate(nsecs_t timestamp) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080066 if (mLastTimestampIndex < 0 || mTimestamps.empty()) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -070067 return true;
68 }
69
Ady Abraham92fa2f42020-02-11 15:33:56 -080070 auto const aValidTimestamp = mTimestamps[mLastTimestampIndex];
Kevin DuBois1678e2c2019-08-22 12:26:24 -070071 auto const percent = (timestamp - aValidTimestamp) % mIdealPeriod * kMaxPercent / mIdealPeriod;
72 return percent < kOutlierTolerancePercent || percent > (kMaxPercent - kOutlierTolerancePercent);
73}
74
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080075nsecs_t VSyncPredictor::currentPeriod() const {
Ady Abraham9c53ee72020-07-22 21:16:18 -070076 std::lock_guard lock(mMutex);
Ady Abraham0bb6a472020-10-12 10:22:13 -070077 return mRateMap.find(mIdealPeriod)->second.slope;
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080078}
79
Kevin DuBois02d5ed92020-01-27 11:05:46 -080080bool VSyncPredictor::addVsyncTimestamp(nsecs_t timestamp) {
Ady Abraham9c53ee72020-07-22 21:16:18 -070081 std::lock_guard lock(mMutex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -070082
83 if (!validate(timestamp)) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -070084 // VSR could elect to ignore the incongruent timestamp or resetModel(). If ts is ignored,
Ady Abraham43a3e692020-11-13 12:43:39 -080085 // don't insert this ts into mTimestamps ringbuffer. If we are still
86 // in the learning phase we should just clear all timestamps and start
87 // over.
88 if (mTimestamps.size() < kMinimumSamplesForPrediction) {
Ady Abraham4c56b642021-06-08 15:03:33 -070089 // Add the timestamp to mTimestamps before clearing it so we could
90 // update mKnownTimestamp based on the new timestamp.
91 mTimestamps.push_back(timestamp);
Ady Abraham43a3e692020-11-13 12:43:39 -080092 clearTimestamps();
93 } else if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -070094 mKnownTimestamp =
95 std::max(timestamp, *std::max_element(mTimestamps.begin(), mTimestamps.end()));
96 } else {
97 mKnownTimestamp = timestamp;
98 }
Kevin DuBois02d5ed92020-01-27 11:05:46 -080099 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700100 }
101
Ady Abraham92fa2f42020-02-11 15:33:56 -0800102 if (mTimestamps.size() != kHistorySize) {
103 mTimestamps.push_back(timestamp);
104 mLastTimestampIndex = next(mLastTimestampIndex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700105 } else {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800106 mLastTimestampIndex = next(mLastTimestampIndex);
107 mTimestamps[mLastTimestampIndex] = timestamp;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700108 }
109
Ady Abraham92fa2f42020-02-11 15:33:56 -0800110 if (mTimestamps.size() < kMinimumSamplesForPrediction) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700111 mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800112 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700113 }
114
115 // This is a 'simple linear regression' calculation of Y over X, with Y being the
116 // vsync timestamps, and X being the ordinal of vsync count.
117 // The calculated slope is the vsync period.
118 // Formula for reference:
119 // Sigma_i: means sum over all timestamps.
120 // mean(variable): statistical mean of variable.
121 // X: snapped ordinal of the timestamp
122 // Y: vsync timestamp
123 //
124 // Sigma_i( (X_i - mean(X)) * (Y_i - mean(Y) )
125 // slope = -------------------------------------------
126 // Sigma_i ( X_i - mean(X) ) ^ 2
127 //
128 // intercept = mean(Y) - slope * mean(X)
129 //
Ady Abraham92fa2f42020-02-11 15:33:56 -0800130 std::vector<nsecs_t> vsyncTS(mTimestamps.size());
131 std::vector<nsecs_t> ordinals(mTimestamps.size());
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700132
133 // normalizing to the oldest timestamp cuts down on error in calculating the intercept.
Ady Abraham92fa2f42020-02-11 15:33:56 -0800134 auto const oldest_ts = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700135 auto it = mRateMap.find(mIdealPeriod);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700136 auto const currentPeriod = it->second.slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700137 // TODO (b/144707443): its important that there's some precision in the mean of the ordinals
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700138 // for the intercept calculation, so scale the ordinals by 1000 to continue
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700139 // fixed point calculation. Explore expanding
140 // scheduler::utils::calculate_mean to have a fixed point fractional part.
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700141 static constexpr int64_t kScalingFactor = 1000;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700142
Ady Abraham92fa2f42020-02-11 15:33:56 -0800143 for (auto i = 0u; i < mTimestamps.size(); i++) {
144 traceInt64If("VSP-ts", mTimestamps[i]);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800145
Ady Abraham92fa2f42020-02-11 15:33:56 -0800146 vsyncTS[i] = mTimestamps[i] - oldest_ts;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700147 ordinals[i] = ((vsyncTS[i] + (currentPeriod / 2)) / currentPeriod) * kScalingFactor;
148 }
149
150 auto meanTS = scheduler::calculate_mean(vsyncTS);
151 auto meanOrdinal = scheduler::calculate_mean(ordinals);
Ady Abraham9c53ee72020-07-22 21:16:18 -0700152 for (size_t i = 0; i < vsyncTS.size(); i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700153 vsyncTS[i] -= meanTS;
154 ordinals[i] -= meanOrdinal;
155 }
156
157 auto top = 0ll;
158 auto bottom = 0ll;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700159 for (size_t i = 0; i < vsyncTS.size(); i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700160 top += vsyncTS[i] * ordinals[i];
161 bottom += ordinals[i] * ordinals[i];
162 }
163
164 if (CC_UNLIKELY(bottom == 0)) {
165 it->second = {mIdealPeriod, 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800166 clearTimestamps();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800167 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700168 }
169
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700170 nsecs_t const anticipatedPeriod = top * kScalingFactor / bottom;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700171 nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
172
Ady Abraham92fa2f42020-02-11 15:33:56 -0800173 auto const percent = std::abs(anticipatedPeriod - mIdealPeriod) * kMaxPercent / mIdealPeriod;
174 if (percent >= kOutlierTolerancePercent) {
175 it->second = {mIdealPeriod, 0};
176 clearTimestamps();
177 return false;
178 }
179
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800180 traceInt64If("VSP-period", anticipatedPeriod);
181 traceInt64If("VSP-intercept", intercept);
182
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700183 it->second = {anticipatedPeriod, intercept};
184
185 ALOGV("model update ts: %" PRId64 " slope: %" PRId64 " intercept: %" PRId64, timestamp,
186 anticipatedPeriod, intercept);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800187 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700188}
189
Ady Abraham0bb6a472020-10-12 10:22:13 -0700190nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFromLocked(nsecs_t timePoint) const {
191 auto const [slope, intercept] = getVSyncPredictionModelLocked();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700192
Ady Abraham92fa2f42020-02-11 15:33:56 -0800193 if (mTimestamps.empty()) {
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800194 traceInt64If("VSP-mode", 1);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700195 auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
196 auto const numPeriodsOut = ((timePoint - knownTimestamp) / mIdealPeriod) + 1;
197 return knownTimestamp + numPeriodsOut * mIdealPeriod;
198 }
199
Ady Abraham92fa2f42020-02-11 15:33:56 -0800200 auto const oldest = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois127a2d92019-12-04 13:52:52 -0800201
202 // See b/145667109, the ordinal calculation must take into account the intercept.
203 auto const zeroPoint = oldest + intercept;
204 auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700205 auto const prediction = (ordinalRequest * slope) + intercept + oldest;
206
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800207 traceInt64If("VSP-mode", 0);
208 traceInt64If("VSP-timePoint", timePoint);
209 traceInt64If("VSP-prediction", prediction);
210
Kevin DuBois127a2d92019-12-04 13:52:52 -0800211 auto const printer = [&, slope = slope, intercept = intercept] {
212 std::stringstream str;
213 str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
214 << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
215 << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
216 return str.str();
217 };
218
219 ALOGV("%s", printer().c_str());
220 LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
221 printer().c_str());
222
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700223 return prediction;
224}
225
Ady Abraham0bb6a472020-10-12 10:22:13 -0700226nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint) const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700227 std::lock_guard lock(mMutex);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700228 return nextAnticipatedVSyncTimeFromLocked(timePoint);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700229}
230
Ady Abraham0bb6a472020-10-12 10:22:13 -0700231/*
Ady Abraham5cc2e262021-03-25 13:09:17 -0700232 * Returns whether a given vsync timestamp is in phase with a frame rate.
233 * If the frame rate is not a divider of the refresh rate, it is always considered in phase.
234 * For example, if the vsync timestamps are (16.6,33.3,50.0,66.6):
235 * isVSyncInPhase(16.6, 30) = true
236 * isVSyncInPhase(33.3, 30) = false
237 * isVSyncInPhase(50.0, 30) = true
Ady Abraham0bb6a472020-10-12 10:22:13 -0700238 */
Ady Abraham5cc2e262021-03-25 13:09:17 -0700239bool VSyncPredictor::isVSyncInPhase(nsecs_t timePoint, Fps frameRate) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700240 struct VsyncError {
241 nsecs_t vsyncTimestamp;
242 float error;
243
244 bool operator<(const VsyncError& other) const { return error < other.error; }
245 };
246
Ady Abraham5cc2e262021-03-25 13:09:17 -0700247 std::lock_guard lock(mMutex);
248 const auto divider =
249 RefreshRateConfigs::getFrameRateDivider(Fps::fromPeriodNsecs(mIdealPeriod), frameRate);
Ady Abraham6de88c42020-11-10 20:16:03 -0800250 if (divider <= 1 || timePoint == 0) {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700251 return true;
252 }
253
254 const nsecs_t period = mRateMap[mIdealPeriod].slope;
255 const nsecs_t justBeforeTimePoint = timePoint - period / 2;
256 const nsecs_t dividedPeriod = mIdealPeriod / divider;
257
258 // If this is the first time we have asked about this divider with the
259 // current vsync period, it is considered in phase and we store the closest
260 // vsync timestamp
261 const auto knownTimestampIter = mRateDividerKnownTimestampMap.find(dividedPeriod);
262 if (knownTimestampIter == mRateDividerKnownTimestampMap.end()) {
263 const auto vsync = nextAnticipatedVSyncTimeFromLocked(justBeforeTimePoint);
264 mRateDividerKnownTimestampMap[dividedPeriod] = vsync;
265 return true;
266 }
267
268 // Find the next N vsync timestamp where N is the divider.
269 // One of these vsyncs will be in phase. We return the one which is
270 // the most aligned with the last known in phase vsync
271 std::vector<VsyncError> vsyncs(static_cast<size_t>(divider));
272 const nsecs_t knownVsync = knownTimestampIter->second;
273 nsecs_t point = justBeforeTimePoint;
274 for (size_t i = 0; i < divider; i++) {
275 const nsecs_t vsync = nextAnticipatedVSyncTimeFromLocked(point);
276 const auto numPeriods = static_cast<float>(vsync - knownVsync) / (period * divider);
277 const auto error = std::abs(std::round(numPeriods) - numPeriods);
278 vsyncs[i] = {vsync, error};
279 point = vsync + 1;
280 }
281
282 const auto minVsyncError = std::min_element(vsyncs.begin(), vsyncs.end());
283 mRateDividerKnownTimestampMap[dividedPeriod] = minVsyncError->vsyncTimestamp;
284 return std::abs(minVsyncError->vsyncTimestamp - timePoint) < period / 2;
285}
286
287VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModel() const {
288 std::lock_guard lock(mMutex);
289 const auto model = VSyncPredictor::getVSyncPredictionModelLocked();
290 return {model.slope, model.intercept};
291}
292
293VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModelLocked() const {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700294 return mRateMap.find(mIdealPeriod)->second;
295}
296
297void VSyncPredictor::setPeriod(nsecs_t period) {
298 ATRACE_CALL();
299
Ady Abraham9c53ee72020-07-22 21:16:18 -0700300 std::lock_guard lock(mMutex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700301 static constexpr size_t kSizeLimit = 30;
302 if (CC_UNLIKELY(mRateMap.size() == kSizeLimit)) {
303 mRateMap.erase(mRateMap.begin());
304 }
305
306 mIdealPeriod = period;
307 if (mRateMap.find(period) == mRateMap.end()) {
308 mRateMap[mIdealPeriod] = {period, 0};
309 }
310
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800311 clearTimestamps();
312}
313
314void VSyncPredictor::clearTimestamps() {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800315 if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700316 auto const maxRb = *std::max_element(mTimestamps.begin(), mTimestamps.end());
317 if (mKnownTimestamp) {
318 mKnownTimestamp = std::max(*mKnownTimestamp, maxRb);
319 } else {
320 mKnownTimestamp = maxRb;
321 }
322
Ady Abraham92fa2f42020-02-11 15:33:56 -0800323 mTimestamps.clear();
324 mLastTimestampIndex = 0;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700325 }
326}
327
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700328bool VSyncPredictor::needsMoreSamples() const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700329 std::lock_guard lock(mMutex);
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700330 return mTimestamps.size() < kMinimumSamplesForPrediction;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700331}
332
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800333void VSyncPredictor::resetModel() {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700334 std::lock_guard lock(mMutex);
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800335 mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
336 clearTimestamps();
337}
338
Ady Abraham5e7371c2020-03-24 14:47:24 -0700339void VSyncPredictor::dump(std::string& result) const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700340 std::lock_guard lock(mMutex);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700341 StringAppendF(&result, "\tmIdealPeriod=%.2f\n", mIdealPeriod / 1e6f);
342 StringAppendF(&result, "\tRefresh Rate Map:\n");
343 for (const auto& [idealPeriod, periodInterceptTuple] : mRateMap) {
344 StringAppendF(&result,
345 "\t\tFor ideal period %.2fms: period = %.2fms, intercept = %" PRId64 "\n",
Ady Abraham0bb6a472020-10-12 10:22:13 -0700346 idealPeriod / 1e6f, periodInterceptTuple.slope / 1e6f,
347 periodInterceptTuple.intercept);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700348 }
349}
350
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700351} // namespace android::scheduler
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800352
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100353// TODO(b/129481165): remove the #pragma below and fix conversion issues
354#pragma clang diagnostic pop // ignored "-Wextra"