blob: 708a5b87beee5d3b5fa9a5a481e6191372b0a0fc [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
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
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>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070033
34namespace android::scheduler {
Ady Abraham5e7371c2020-03-24 14:47:24 -070035using base::StringAppendF;
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080036
Kevin DuBois1678e2c2019-08-22 12:26:24 -070037static auto constexpr kMaxPercent = 100u;
38
39VSyncPredictor::~VSyncPredictor() = default;
40
41VSyncPredictor::VSyncPredictor(nsecs_t idealPeriod, size_t historySize,
42 size_t minimumSamplesForPrediction, uint32_t outlierTolerancePercent)
Kevin DuBoisc57f2c32019-12-20 16:32:29 -080043 : mTraceOn(property_get_bool("debug.sf.vsp_trace", true)),
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080044 kHistorySize(historySize),
Kevin DuBois1678e2c2019-08-22 12:26:24 -070045 kMinimumSamplesForPrediction(minimumSamplesForPrediction),
46 kOutlierTolerancePercent(std::min(outlierTolerancePercent, kMaxPercent)),
47 mIdealPeriod(idealPeriod) {
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -080048 resetModel();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070049}
50
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080051inline void VSyncPredictor::traceInt64If(const char* name, int64_t value) const {
52 if (CC_UNLIKELY(mTraceOn)) {
53 ATRACE_INT64(name, value);
54 }
55}
56
Kevin DuBois1678e2c2019-08-22 12:26:24 -070057inline size_t VSyncPredictor::next(int i) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080058 return (i + 1) % mTimestamps.size();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070059}
60
61bool VSyncPredictor::validate(nsecs_t timestamp) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080062 if (mLastTimestampIndex < 0 || mTimestamps.empty()) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -070063 return true;
64 }
65
Ady Abraham92fa2f42020-02-11 15:33:56 -080066 auto const aValidTimestamp = mTimestamps[mLastTimestampIndex];
Kevin DuBois1678e2c2019-08-22 12:26:24 -070067 auto const percent = (timestamp - aValidTimestamp) % mIdealPeriod * kMaxPercent / mIdealPeriod;
68 return percent < kOutlierTolerancePercent || percent > (kMaxPercent - kOutlierTolerancePercent);
69}
70
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080071nsecs_t VSyncPredictor::currentPeriod() const {
72 std::lock_guard<std::mutex> lk(mMutex);
73 return std::get<0>(mRateMap.find(mIdealPeriod)->second);
74}
75
Kevin DuBois02d5ed92020-01-27 11:05:46 -080076bool VSyncPredictor::addVsyncTimestamp(nsecs_t timestamp) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -070077 std::lock_guard<std::mutex> lk(mMutex);
78
79 if (!validate(timestamp)) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -070080 // VSR could elect to ignore the incongruent timestamp or resetModel(). If ts is ignored,
Ady Abraham707840a2020-11-13 12:43:39 -080081 // don't insert this ts into mTimestamps ringbuffer. If we are still
82 // in the learning phase we should just clear all timestamps and start
83 // over.
84 if (mTimestamps.size() < kMinimumSamplesForPrediction) {
85 clearTimestamps();
86 } else if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -070087 mKnownTimestamp =
88 std::max(timestamp, *std::max_element(mTimestamps.begin(), mTimestamps.end()));
89 } else {
90 mKnownTimestamp = timestamp;
91 }
Kevin DuBois02d5ed92020-01-27 11:05:46 -080092 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -070093 }
94
Ady Abraham92fa2f42020-02-11 15:33:56 -080095 if (mTimestamps.size() != kHistorySize) {
96 mTimestamps.push_back(timestamp);
97 mLastTimestampIndex = next(mLastTimestampIndex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -070098 } else {
Ady Abraham92fa2f42020-02-11 15:33:56 -080099 mLastTimestampIndex = next(mLastTimestampIndex);
100 mTimestamps[mLastTimestampIndex] = timestamp;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700101 }
102
Ady Abraham92fa2f42020-02-11 15:33:56 -0800103 if (mTimestamps.size() < kMinimumSamplesForPrediction) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700104 mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800105 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700106 }
107
108 // This is a 'simple linear regression' calculation of Y over X, with Y being the
109 // vsync timestamps, and X being the ordinal of vsync count.
110 // The calculated slope is the vsync period.
111 // Formula for reference:
112 // Sigma_i: means sum over all timestamps.
113 // mean(variable): statistical mean of variable.
114 // X: snapped ordinal of the timestamp
115 // Y: vsync timestamp
116 //
117 // Sigma_i( (X_i - mean(X)) * (Y_i - mean(Y) )
118 // slope = -------------------------------------------
119 // Sigma_i ( X_i - mean(X) ) ^ 2
120 //
121 // intercept = mean(Y) - slope * mean(X)
122 //
Ady Abraham92fa2f42020-02-11 15:33:56 -0800123 std::vector<nsecs_t> vsyncTS(mTimestamps.size());
124 std::vector<nsecs_t> ordinals(mTimestamps.size());
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700125
126 // normalizing to the oldest timestamp cuts down on error in calculating the intercept.
Ady Abraham92fa2f42020-02-11 15:33:56 -0800127 auto const oldest_ts = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700128 auto it = mRateMap.find(mIdealPeriod);
129 auto const currentPeriod = std::get<0>(it->second);
130 // TODO (b/144707443): its important that there's some precision in the mean of the ordinals
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700131 // for the intercept calculation, so scale the ordinals by 1000 to continue
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700132 // fixed point calculation. Explore expanding
133 // scheduler::utils::calculate_mean to have a fixed point fractional part.
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700134 static constexpr int64_t kScalingFactor = 1000;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700135
Ady Abraham92fa2f42020-02-11 15:33:56 -0800136 for (auto i = 0u; i < mTimestamps.size(); i++) {
137 traceInt64If("VSP-ts", mTimestamps[i]);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800138
Ady Abraham92fa2f42020-02-11 15:33:56 -0800139 vsyncTS[i] = mTimestamps[i] - oldest_ts;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700140 ordinals[i] = ((vsyncTS[i] + (currentPeriod / 2)) / currentPeriod) * kScalingFactor;
141 }
142
143 auto meanTS = scheduler::calculate_mean(vsyncTS);
144 auto meanOrdinal = scheduler::calculate_mean(ordinals);
145 for (auto i = 0; i < vsyncTS.size(); i++) {
146 vsyncTS[i] -= meanTS;
147 ordinals[i] -= meanOrdinal;
148 }
149
150 auto top = 0ll;
151 auto bottom = 0ll;
152 for (auto i = 0; i < vsyncTS.size(); i++) {
153 top += vsyncTS[i] * ordinals[i];
154 bottom += ordinals[i] * ordinals[i];
155 }
156
157 if (CC_UNLIKELY(bottom == 0)) {
158 it->second = {mIdealPeriod, 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800159 clearTimestamps();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800160 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700161 }
162
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700163 nsecs_t const anticipatedPeriod = top * kScalingFactor / bottom;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700164 nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
165
Ady Abraham92fa2f42020-02-11 15:33:56 -0800166 auto const percent = std::abs(anticipatedPeriod - mIdealPeriod) * kMaxPercent / mIdealPeriod;
167 if (percent >= kOutlierTolerancePercent) {
168 it->second = {mIdealPeriod, 0};
169 clearTimestamps();
170 return false;
171 }
172
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800173 traceInt64If("VSP-period", anticipatedPeriod);
174 traceInt64If("VSP-intercept", intercept);
175
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700176 it->second = {anticipatedPeriod, intercept};
177
178 ALOGV("model update ts: %" PRId64 " slope: %" PRId64 " intercept: %" PRId64, timestamp,
179 anticipatedPeriod, intercept);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800180 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700181}
182
183nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint) const {
184 std::lock_guard<std::mutex> lk(mMutex);
185
186 auto const [slope, intercept] = getVSyncPredictionModel(lk);
187
Ady Abraham92fa2f42020-02-11 15:33:56 -0800188 if (mTimestamps.empty()) {
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800189 traceInt64If("VSP-mode", 1);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700190 auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
191 auto const numPeriodsOut = ((timePoint - knownTimestamp) / mIdealPeriod) + 1;
192 return knownTimestamp + numPeriodsOut * mIdealPeriod;
193 }
194
Ady Abraham92fa2f42020-02-11 15:33:56 -0800195 auto const oldest = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois127a2d92019-12-04 13:52:52 -0800196
197 // See b/145667109, the ordinal calculation must take into account the intercept.
198 auto const zeroPoint = oldest + intercept;
199 auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700200 auto const prediction = (ordinalRequest * slope) + intercept + oldest;
201
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800202 traceInt64If("VSP-mode", 0);
203 traceInt64If("VSP-timePoint", timePoint);
204 traceInt64If("VSP-prediction", prediction);
205
Kevin DuBois127a2d92019-12-04 13:52:52 -0800206 auto const printer = [&, slope = slope, intercept = intercept] {
207 std::stringstream str;
208 str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
209 << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
210 << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
211 return str.str();
212 };
213
214 ALOGV("%s", printer().c_str());
215 LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
216 printer().c_str());
217
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700218 return prediction;
219}
220
221std::tuple<nsecs_t, nsecs_t> VSyncPredictor::getVSyncPredictionModel() const {
222 std::lock_guard<std::mutex> lk(mMutex);
223 return VSyncPredictor::getVSyncPredictionModel(lk);
224}
225
226std::tuple<nsecs_t, nsecs_t> VSyncPredictor::getVSyncPredictionModel(
227 std::lock_guard<std::mutex> const&) const {
228 return mRateMap.find(mIdealPeriod)->second;
229}
230
231void VSyncPredictor::setPeriod(nsecs_t period) {
232 ATRACE_CALL();
233
234 std::lock_guard<std::mutex> lk(mMutex);
235 static constexpr size_t kSizeLimit = 30;
236 if (CC_UNLIKELY(mRateMap.size() == kSizeLimit)) {
237 mRateMap.erase(mRateMap.begin());
238 }
239
240 mIdealPeriod = period;
241 if (mRateMap.find(period) == mRateMap.end()) {
242 mRateMap[mIdealPeriod] = {period, 0};
243 }
244
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800245 clearTimestamps();
246}
247
248void VSyncPredictor::clearTimestamps() {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800249 if (!mTimestamps.empty()) {
Kevin DuBois241d0ee2020-06-26 17:00:15 -0700250 auto const maxRb = *std::max_element(mTimestamps.begin(), mTimestamps.end());
251 if (mKnownTimestamp) {
252 mKnownTimestamp = std::max(*mKnownTimestamp, maxRb);
253 } else {
254 mKnownTimestamp = maxRb;
255 }
256
Ady Abraham92fa2f42020-02-11 15:33:56 -0800257 mTimestamps.clear();
258 mLastTimestampIndex = 0;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700259 }
260}
261
Kevin DuBoisbc7ddff2020-07-10 14:29:36 -0700262bool VSyncPredictor::needsMoreSamples() const {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700263 std::lock_guard<std::mutex> lk(mMutex);
Kevin DuBoisbc7ddff2020-07-10 14:29:36 -0700264 return mTimestamps.size() < kMinimumSamplesForPrediction;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700265}
266
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800267void VSyncPredictor::resetModel() {
268 std::lock_guard<std::mutex> lk(mMutex);
269 mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
270 clearTimestamps();
271}
272
Ady Abraham5e7371c2020-03-24 14:47:24 -0700273void VSyncPredictor::dump(std::string& result) const {
274 std::lock_guard<std::mutex> lk(mMutex);
275 StringAppendF(&result, "\tmIdealPeriod=%.2f\n", mIdealPeriod / 1e6f);
276 StringAppendF(&result, "\tRefresh Rate Map:\n");
277 for (const auto& [idealPeriod, periodInterceptTuple] : mRateMap) {
278 StringAppendF(&result,
279 "\t\tFor ideal period %.2fms: period = %.2fms, intercept = %" PRId64 "\n",
280 idealPeriod / 1e6f, std::get<0>(periodInterceptTuple) / 1e6f,
281 std::get<1>(periodInterceptTuple));
282 }
283}
284
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700285} // namespace android::scheduler
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800286
287// TODO(b/129481165): remove the #pragma below and fix conversion issues
288#pragma clang diagnostic pop // ignored "-Wconversion"