blob: 75d1e6f1326aaff2ac149b7b0044de645a651e71 [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
17#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18//#define LOG_NDEBUG 0
19#include "VSyncPredictor.h"
20#include <android-base/logging.h>
Ady Abraham5e7371c2020-03-24 14:47:24 -070021#include <android-base/stringprintf.h>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070022#include <cutils/compiler.h>
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080023#include <cutils/properties.h>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070024#include <utils/Log.h>
25#include <utils/Trace.h>
26#include <algorithm>
27#include <chrono>
Kevin DuBois127a2d92019-12-04 13:52:52 -080028#include <sstream>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070029
Ady Abraham0bb6a472020-10-12 10:22:13 -070030#undef LOG_TAG
31#define LOG_TAG "VSyncPredictor"
32
Kevin DuBois1678e2c2019-08-22 12:26:24 -070033namespace android::scheduler {
Ady Abraham5e7371c2020-03-24 14:47:24 -070034using base::StringAppendF;
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080035
Kevin DuBois1678e2c2019-08-22 12:26:24 -070036static auto constexpr kMaxPercent = 100u;
37
38VSyncPredictor::~VSyncPredictor() = default;
39
40VSyncPredictor::VSyncPredictor(nsecs_t idealPeriod, size_t historySize,
41 size_t minimumSamplesForPrediction, uint32_t outlierTolerancePercent)
Kevin DuBoisc57f2c32019-12-20 16:32:29 -080042 : mTraceOn(property_get_bool("debug.sf.vsp_trace", true)),
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080043 kHistorySize(historySize),
Kevin DuBois1678e2c2019-08-22 12:26:24 -070044 kMinimumSamplesForPrediction(minimumSamplesForPrediction),
45 kOutlierTolerancePercent(std::min(outlierTolerancePercent, kMaxPercent)),
46 mIdealPeriod(idealPeriod) {
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -080047 resetModel();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070048}
49
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080050inline void VSyncPredictor::traceInt64If(const char* name, int64_t value) const {
51 if (CC_UNLIKELY(mTraceOn)) {
52 ATRACE_INT64(name, value);
53 }
54}
55
Ady Abraham9c53ee72020-07-22 21:16:18 -070056inline size_t VSyncPredictor::next(size_t i) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080057 return (i + 1) % mTimestamps.size();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070058}
59
60bool VSyncPredictor::validate(nsecs_t timestamp) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080061 if (mLastTimestampIndex < 0 || mTimestamps.empty()) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -070062 return true;
63 }
64
Ady Abraham92fa2f42020-02-11 15:33:56 -080065 auto const aValidTimestamp = mTimestamps[mLastTimestampIndex];
Kevin DuBois1678e2c2019-08-22 12:26:24 -070066 auto const percent = (timestamp - aValidTimestamp) % mIdealPeriod * kMaxPercent / mIdealPeriod;
67 return percent < kOutlierTolerancePercent || percent > (kMaxPercent - kOutlierTolerancePercent);
68}
69
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080070nsecs_t VSyncPredictor::currentPeriod() const {
Ady Abraham9c53ee72020-07-22 21:16:18 -070071 std::lock_guard lock(mMutex);
Ady Abraham0bb6a472020-10-12 10:22:13 -070072 return mRateMap.find(mIdealPeriod)->second.slope;
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080073}
74
Kevin DuBois02d5ed92020-01-27 11:05:46 -080075bool VSyncPredictor::addVsyncTimestamp(nsecs_t timestamp) {
Ady Abraham9c53ee72020-07-22 21:16:18 -070076 std::lock_guard lock(mMutex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -070077
78 if (!validate(timestamp)) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -070079 // VSR could elect to ignore the incongruent timestamp or resetModel(). If ts is ignored,
80 // don't insert this ts into mTimestamps ringbuffer.
81 if (!mTimestamps.empty()) {
82 mKnownTimestamp =
83 std::max(timestamp, *std::max_element(mTimestamps.begin(), mTimestamps.end()));
84 } else {
85 mKnownTimestamp = timestamp;
86 }
Kevin DuBois02d5ed92020-01-27 11:05:46 -080087 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -070088 }
89
Ady Abraham92fa2f42020-02-11 15:33:56 -080090 if (mTimestamps.size() != kHistorySize) {
91 mTimestamps.push_back(timestamp);
92 mLastTimestampIndex = next(mLastTimestampIndex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -070093 } else {
Ady Abraham92fa2f42020-02-11 15:33:56 -080094 mLastTimestampIndex = next(mLastTimestampIndex);
95 mTimestamps[mLastTimestampIndex] = timestamp;
Kevin DuBois1678e2c2019-08-22 12:26:24 -070096 }
97
Ady Abraham92fa2f42020-02-11 15:33:56 -080098 if (mTimestamps.size() < kMinimumSamplesForPrediction) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -070099 mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800100 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700101 }
102
103 // This is a 'simple linear regression' calculation of Y over X, with Y being the
104 // vsync timestamps, and X being the ordinal of vsync count.
105 // The calculated slope is the vsync period.
106 // Formula for reference:
107 // Sigma_i: means sum over all timestamps.
108 // mean(variable): statistical mean of variable.
109 // X: snapped ordinal of the timestamp
110 // Y: vsync timestamp
111 //
112 // Sigma_i( (X_i - mean(X)) * (Y_i - mean(Y) )
113 // slope = -------------------------------------------
114 // Sigma_i ( X_i - mean(X) ) ^ 2
115 //
116 // intercept = mean(Y) - slope * mean(X)
117 //
Ady Abraham92fa2f42020-02-11 15:33:56 -0800118 std::vector<nsecs_t> vsyncTS(mTimestamps.size());
119 std::vector<nsecs_t> ordinals(mTimestamps.size());
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700120
121 // normalizing to the oldest timestamp cuts down on error in calculating the intercept.
Ady Abraham92fa2f42020-02-11 15:33:56 -0800122 auto const oldest_ts = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700123 auto it = mRateMap.find(mIdealPeriod);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700124 auto const currentPeriod = it->second.slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700125 // TODO (b/144707443): its important that there's some precision in the mean of the ordinals
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700126 // for the intercept calculation, so scale the ordinals by 1000 to continue
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700127 // fixed point calculation. Explore expanding
128 // scheduler::utils::calculate_mean to have a fixed point fractional part.
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700129 static constexpr int64_t kScalingFactor = 1000;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700130
Ady Abraham92fa2f42020-02-11 15:33:56 -0800131 for (auto i = 0u; i < mTimestamps.size(); i++) {
132 traceInt64If("VSP-ts", mTimestamps[i]);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800133
Ady Abraham92fa2f42020-02-11 15:33:56 -0800134 vsyncTS[i] = mTimestamps[i] - oldest_ts;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700135 ordinals[i] = ((vsyncTS[i] + (currentPeriod / 2)) / currentPeriod) * kScalingFactor;
136 }
137
138 auto meanTS = scheduler::calculate_mean(vsyncTS);
139 auto meanOrdinal = scheduler::calculate_mean(ordinals);
Ady Abraham9c53ee72020-07-22 21:16:18 -0700140 for (size_t i = 0; i < vsyncTS.size(); i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700141 vsyncTS[i] -= meanTS;
142 ordinals[i] -= meanOrdinal;
143 }
144
145 auto top = 0ll;
146 auto bottom = 0ll;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700147 for (size_t i = 0; i < vsyncTS.size(); i++) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700148 top += vsyncTS[i] * ordinals[i];
149 bottom += ordinals[i] * ordinals[i];
150 }
151
152 if (CC_UNLIKELY(bottom == 0)) {
153 it->second = {mIdealPeriod, 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800154 clearTimestamps();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800155 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700156 }
157
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700158 nsecs_t const anticipatedPeriod = top * kScalingFactor / bottom;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700159 nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
160
Ady Abraham92fa2f42020-02-11 15:33:56 -0800161 auto const percent = std::abs(anticipatedPeriod - mIdealPeriod) * kMaxPercent / mIdealPeriod;
162 if (percent >= kOutlierTolerancePercent) {
163 it->second = {mIdealPeriod, 0};
164 clearTimestamps();
165 return false;
166 }
167
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800168 traceInt64If("VSP-period", anticipatedPeriod);
169 traceInt64If("VSP-intercept", intercept);
170
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700171 it->second = {anticipatedPeriod, intercept};
172
173 ALOGV("model update ts: %" PRId64 " slope: %" PRId64 " intercept: %" PRId64, timestamp,
174 anticipatedPeriod, intercept);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800175 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700176}
177
Ady Abraham0bb6a472020-10-12 10:22:13 -0700178nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFromLocked(nsecs_t timePoint) const {
179 auto const [slope, intercept] = getVSyncPredictionModelLocked();
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700180
Ady Abraham92fa2f42020-02-11 15:33:56 -0800181 if (mTimestamps.empty()) {
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800182 traceInt64If("VSP-mode", 1);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700183 auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
184 auto const numPeriodsOut = ((timePoint - knownTimestamp) / mIdealPeriod) + 1;
185 return knownTimestamp + numPeriodsOut * mIdealPeriod;
186 }
187
Ady Abraham92fa2f42020-02-11 15:33:56 -0800188 auto const oldest = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois127a2d92019-12-04 13:52:52 -0800189
190 // See b/145667109, the ordinal calculation must take into account the intercept.
191 auto const zeroPoint = oldest + intercept;
192 auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700193 auto const prediction = (ordinalRequest * slope) + intercept + oldest;
194
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800195 traceInt64If("VSP-mode", 0);
196 traceInt64If("VSP-timePoint", timePoint);
197 traceInt64If("VSP-prediction", prediction);
198
Kevin DuBois127a2d92019-12-04 13:52:52 -0800199 auto const printer = [&, slope = slope, intercept = intercept] {
200 std::stringstream str;
201 str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
202 << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
203 << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
204 return str.str();
205 };
206
207 ALOGV("%s", printer().c_str());
208 LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
209 printer().c_str());
210
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700211 return prediction;
212}
213
Ady Abraham0bb6a472020-10-12 10:22:13 -0700214nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint) const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700215 std::lock_guard lock(mMutex);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700216 return nextAnticipatedVSyncTimeFromLocked(timePoint);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700217}
218
Ady Abraham0bb6a472020-10-12 10:22:13 -0700219/*
220 * Returns whether a given vsync timestamp is in phase with a vsync divider.
221 * For example, if the vsync timestamps are (0,16,32,48):
222 * isVSyncInPhase(0, 2) = true
223 * isVSyncInPhase(16, 2) = false
224 * isVSyncInPhase(32, 2) = true
225 */
226bool VSyncPredictor::isVSyncInPhase(nsecs_t timePoint, int divider) const {
227 struct VsyncError {
228 nsecs_t vsyncTimestamp;
229 float error;
230
231 bool operator<(const VsyncError& other) const { return error < other.error; }
232 };
233
234 std::lock_guard lock(mMutex);
235 if (divider <= 1) {
236 return true;
237 }
238
239 const nsecs_t period = mRateMap[mIdealPeriod].slope;
240 const nsecs_t justBeforeTimePoint = timePoint - period / 2;
241 const nsecs_t dividedPeriod = mIdealPeriod / divider;
242
243 // If this is the first time we have asked about this divider with the
244 // current vsync period, it is considered in phase and we store the closest
245 // vsync timestamp
246 const auto knownTimestampIter = mRateDividerKnownTimestampMap.find(dividedPeriod);
247 if (knownTimestampIter == mRateDividerKnownTimestampMap.end()) {
248 const auto vsync = nextAnticipatedVSyncTimeFromLocked(justBeforeTimePoint);
249 mRateDividerKnownTimestampMap[dividedPeriod] = vsync;
250 return true;
251 }
252
253 // Find the next N vsync timestamp where N is the divider.
254 // One of these vsyncs will be in phase. We return the one which is
255 // the most aligned with the last known in phase vsync
256 std::vector<VsyncError> vsyncs(static_cast<size_t>(divider));
257 const nsecs_t knownVsync = knownTimestampIter->second;
258 nsecs_t point = justBeforeTimePoint;
259 for (size_t i = 0; i < divider; i++) {
260 const nsecs_t vsync = nextAnticipatedVSyncTimeFromLocked(point);
261 const auto numPeriods = static_cast<float>(vsync - knownVsync) / (period * divider);
262 const auto error = std::abs(std::round(numPeriods) - numPeriods);
263 vsyncs[i] = {vsync, error};
264 point = vsync + 1;
265 }
266
267 const auto minVsyncError = std::min_element(vsyncs.begin(), vsyncs.end());
268 mRateDividerKnownTimestampMap[dividedPeriod] = minVsyncError->vsyncTimestamp;
269 return std::abs(minVsyncError->vsyncTimestamp - timePoint) < period / 2;
270}
271
272VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModel() const {
273 std::lock_guard lock(mMutex);
274 const auto model = VSyncPredictor::getVSyncPredictionModelLocked();
275 return {model.slope, model.intercept};
276}
277
278VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModelLocked() const {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700279 return mRateMap.find(mIdealPeriod)->second;
280}
281
282void VSyncPredictor::setPeriod(nsecs_t period) {
283 ATRACE_CALL();
284
Ady Abraham9c53ee72020-07-22 21:16:18 -0700285 std::lock_guard lock(mMutex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700286 static constexpr size_t kSizeLimit = 30;
287 if (CC_UNLIKELY(mRateMap.size() == kSizeLimit)) {
288 mRateMap.erase(mRateMap.begin());
289 }
290
291 mIdealPeriod = period;
292 if (mRateMap.find(period) == mRateMap.end()) {
293 mRateMap[mIdealPeriod] = {period, 0};
294 }
295
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800296 clearTimestamps();
297}
298
299void VSyncPredictor::clearTimestamps() {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800300 if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700301 auto const maxRb = *std::max_element(mTimestamps.begin(), mTimestamps.end());
302 if (mKnownTimestamp) {
303 mKnownTimestamp = std::max(*mKnownTimestamp, maxRb);
304 } else {
305 mKnownTimestamp = maxRb;
306 }
307
Ady Abraham92fa2f42020-02-11 15:33:56 -0800308 mTimestamps.clear();
309 mLastTimestampIndex = 0;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700310 }
311}
312
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700313bool VSyncPredictor::needsMoreSamples() const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700314 std::lock_guard lock(mMutex);
Kevin DuBoisb818bfa2020-07-10 14:29:36 -0700315 return mTimestamps.size() < kMinimumSamplesForPrediction;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700316}
317
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800318void VSyncPredictor::resetModel() {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700319 std::lock_guard lock(mMutex);
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800320 mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
321 clearTimestamps();
322}
323
Ady Abraham5e7371c2020-03-24 14:47:24 -0700324void VSyncPredictor::dump(std::string& result) const {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700325 std::lock_guard lock(mMutex);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700326 StringAppendF(&result, "\tmIdealPeriod=%.2f\n", mIdealPeriod / 1e6f);
327 StringAppendF(&result, "\tRefresh Rate Map:\n");
328 for (const auto& [idealPeriod, periodInterceptTuple] : mRateMap) {
329 StringAppendF(&result,
330 "\t\tFor ideal period %.2fms: period = %.2fms, intercept = %" PRId64 "\n",
Ady Abraham0bb6a472020-10-12 10:22:13 -0700331 idealPeriod / 1e6f, periodInterceptTuple.slope / 1e6f,
332 periodInterceptTuple.intercept);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700333 }
334}
335
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700336} // namespace android::scheduler
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800337