blob: 399da19c75ec6552edcdb951876cd47f98d93a91 [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>
25#include <cutils/compiler.h>
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080026#include <cutils/properties.h>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070027#include <utils/Log.h>
28#include <utils/Trace.h>
29#include <algorithm>
30#include <chrono>
Kevin DuBois127a2d92019-12-04 13:52:52 -080031#include <sstream>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070032
33namespace android::scheduler {
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080034
Kevin DuBois1678e2c2019-08-22 12:26:24 -070035static auto constexpr kMaxPercent = 100u;
36
37VSyncPredictor::~VSyncPredictor() = default;
38
39VSyncPredictor::VSyncPredictor(nsecs_t idealPeriod, size_t historySize,
40 size_t minimumSamplesForPrediction, uint32_t outlierTolerancePercent)
Kevin DuBoisc57f2c32019-12-20 16:32:29 -080041 : mTraceOn(property_get_bool("debug.sf.vsp_trace", true)),
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080042 kHistorySize(historySize),
Kevin DuBois1678e2c2019-08-22 12:26:24 -070043 kMinimumSamplesForPrediction(minimumSamplesForPrediction),
44 kOutlierTolerancePercent(std::min(outlierTolerancePercent, kMaxPercent)),
45 mIdealPeriod(idealPeriod) {
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -080046 resetModel();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070047}
48
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080049inline void VSyncPredictor::traceInt64If(const char* name, int64_t value) const {
50 if (CC_UNLIKELY(mTraceOn)) {
51 ATRACE_INT64(name, value);
52 }
53}
54
Kevin DuBois1678e2c2019-08-22 12:26:24 -070055inline size_t VSyncPredictor::next(int i) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080056 return (i + 1) % mTimestamps.size();
Kevin DuBois1678e2c2019-08-22 12:26:24 -070057}
58
59bool VSyncPredictor::validate(nsecs_t timestamp) const {
Ady Abraham92fa2f42020-02-11 15:33:56 -080060 if (mLastTimestampIndex < 0 || mTimestamps.empty()) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -070061 return true;
62 }
63
Ady Abraham92fa2f42020-02-11 15:33:56 -080064 auto const aValidTimestamp = mTimestamps[mLastTimestampIndex];
Kevin DuBois1678e2c2019-08-22 12:26:24 -070065 auto const percent = (timestamp - aValidTimestamp) % mIdealPeriod * kMaxPercent / mIdealPeriod;
66 return percent < kOutlierTolerancePercent || percent > (kMaxPercent - kOutlierTolerancePercent);
67}
68
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080069nsecs_t VSyncPredictor::currentPeriod() const {
70 std::lock_guard<std::mutex> lk(mMutex);
71 return std::get<0>(mRateMap.find(mIdealPeriod)->second);
72}
73
Kevin DuBois02d5ed92020-01-27 11:05:46 -080074bool VSyncPredictor::addVsyncTimestamp(nsecs_t timestamp) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -070075 std::lock_guard<std::mutex> lk(mMutex);
76
77 if (!validate(timestamp)) {
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080078 ALOGV("timestamp was too far off the last known timestamp");
Kevin DuBois02d5ed92020-01-27 11:05:46 -080079 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -070080 }
81
Ady Abraham92fa2f42020-02-11 15:33:56 -080082 if (mTimestamps.size() != kHistorySize) {
83 mTimestamps.push_back(timestamp);
84 mLastTimestampIndex = next(mLastTimestampIndex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -070085 } else {
Ady Abraham92fa2f42020-02-11 15:33:56 -080086 mLastTimestampIndex = next(mLastTimestampIndex);
87 mTimestamps[mLastTimestampIndex] = timestamp;
Kevin DuBois1678e2c2019-08-22 12:26:24 -070088 }
89
Ady Abraham92fa2f42020-02-11 15:33:56 -080090 if (mTimestamps.size() < kMinimumSamplesForPrediction) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -070091 mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
Kevin DuBois02d5ed92020-01-27 11:05:46 -080092 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -070093 }
94
95 // This is a 'simple linear regression' calculation of Y over X, with Y being the
96 // vsync timestamps, and X being the ordinal of vsync count.
97 // The calculated slope is the vsync period.
98 // Formula for reference:
99 // Sigma_i: means sum over all timestamps.
100 // mean(variable): statistical mean of variable.
101 // X: snapped ordinal of the timestamp
102 // Y: vsync timestamp
103 //
104 // Sigma_i( (X_i - mean(X)) * (Y_i - mean(Y) )
105 // slope = -------------------------------------------
106 // Sigma_i ( X_i - mean(X) ) ^ 2
107 //
108 // intercept = mean(Y) - slope * mean(X)
109 //
Ady Abraham92fa2f42020-02-11 15:33:56 -0800110 std::vector<nsecs_t> vsyncTS(mTimestamps.size());
111 std::vector<nsecs_t> ordinals(mTimestamps.size());
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700112
113 // normalizing to the oldest timestamp cuts down on error in calculating the intercept.
Ady Abraham92fa2f42020-02-11 15:33:56 -0800114 auto const oldest_ts = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700115 auto it = mRateMap.find(mIdealPeriod);
116 auto const currentPeriod = std::get<0>(it->second);
117 // TODO (b/144707443): its important that there's some precision in the mean of the ordinals
118 // for the intercept calculation, so scale the ordinals by 10 to continue
119 // fixed point calculation. Explore expanding
120 // scheduler::utils::calculate_mean to have a fixed point fractional part.
121 static constexpr int kScalingFactor = 10;
122
Ady Abraham92fa2f42020-02-11 15:33:56 -0800123 for (auto i = 0u; i < mTimestamps.size(); i++) {
124 traceInt64If("VSP-ts", mTimestamps[i]);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800125
Ady Abraham92fa2f42020-02-11 15:33:56 -0800126 vsyncTS[i] = mTimestamps[i] - oldest_ts;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700127 ordinals[i] = ((vsyncTS[i] + (currentPeriod / 2)) / currentPeriod) * kScalingFactor;
128 }
129
130 auto meanTS = scheduler::calculate_mean(vsyncTS);
131 auto meanOrdinal = scheduler::calculate_mean(ordinals);
132 for (auto i = 0; i < vsyncTS.size(); i++) {
133 vsyncTS[i] -= meanTS;
134 ordinals[i] -= meanOrdinal;
135 }
136
137 auto top = 0ll;
138 auto bottom = 0ll;
139 for (auto i = 0; i < vsyncTS.size(); i++) {
140 top += vsyncTS[i] * ordinals[i];
141 bottom += ordinals[i] * ordinals[i];
142 }
143
144 if (CC_UNLIKELY(bottom == 0)) {
145 it->second = {mIdealPeriod, 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800146 clearTimestamps();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800147 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700148 }
149
150 nsecs_t const anticipatedPeriod = top / bottom * kScalingFactor;
151 nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
152
Ady Abraham92fa2f42020-02-11 15:33:56 -0800153 auto const percent = std::abs(anticipatedPeriod - mIdealPeriod) * kMaxPercent / mIdealPeriod;
154 if (percent >= kOutlierTolerancePercent) {
155 it->second = {mIdealPeriod, 0};
156 clearTimestamps();
157 return false;
158 }
159
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800160 traceInt64If("VSP-period", anticipatedPeriod);
161 traceInt64If("VSP-intercept", intercept);
162
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700163 it->second = {anticipatedPeriod, intercept};
164
165 ALOGV("model update ts: %" PRId64 " slope: %" PRId64 " intercept: %" PRId64, timestamp,
166 anticipatedPeriod, intercept);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800167 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700168}
169
170nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint) const {
171 std::lock_guard<std::mutex> lk(mMutex);
172
173 auto const [slope, intercept] = getVSyncPredictionModel(lk);
174
Ady Abraham92fa2f42020-02-11 15:33:56 -0800175 if (mTimestamps.empty()) {
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800176 traceInt64If("VSP-mode", 1);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700177 auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
178 auto const numPeriodsOut = ((timePoint - knownTimestamp) / mIdealPeriod) + 1;
179 return knownTimestamp + numPeriodsOut * mIdealPeriod;
180 }
181
Ady Abraham92fa2f42020-02-11 15:33:56 -0800182 auto const oldest = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois127a2d92019-12-04 13:52:52 -0800183
184 // See b/145667109, the ordinal calculation must take into account the intercept.
185 auto const zeroPoint = oldest + intercept;
186 auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700187 auto const prediction = (ordinalRequest * slope) + intercept + oldest;
188
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800189 traceInt64If("VSP-mode", 0);
190 traceInt64If("VSP-timePoint", timePoint);
191 traceInt64If("VSP-prediction", prediction);
192
Kevin DuBois127a2d92019-12-04 13:52:52 -0800193 auto const printer = [&, slope = slope, intercept = intercept] {
194 std::stringstream str;
195 str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
196 << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
197 << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
198 return str.str();
199 };
200
201 ALOGV("%s", printer().c_str());
202 LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
203 printer().c_str());
204
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700205 return prediction;
206}
207
208std::tuple<nsecs_t, nsecs_t> VSyncPredictor::getVSyncPredictionModel() const {
209 std::lock_guard<std::mutex> lk(mMutex);
210 return VSyncPredictor::getVSyncPredictionModel(lk);
211}
212
213std::tuple<nsecs_t, nsecs_t> VSyncPredictor::getVSyncPredictionModel(
214 std::lock_guard<std::mutex> const&) const {
215 return mRateMap.find(mIdealPeriod)->second;
216}
217
218void VSyncPredictor::setPeriod(nsecs_t period) {
219 ATRACE_CALL();
220
221 std::lock_guard<std::mutex> lk(mMutex);
222 static constexpr size_t kSizeLimit = 30;
223 if (CC_UNLIKELY(mRateMap.size() == kSizeLimit)) {
224 mRateMap.erase(mRateMap.begin());
225 }
226
227 mIdealPeriod = period;
228 if (mRateMap.find(period) == mRateMap.end()) {
229 mRateMap[mIdealPeriod] = {period, 0};
230 }
231
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800232 clearTimestamps();
233}
234
235void VSyncPredictor::clearTimestamps() {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800236 if (!mTimestamps.empty()) {
237 mKnownTimestamp = *std::max_element(mTimestamps.begin(), mTimestamps.end());
238 mTimestamps.clear();
239 mLastTimestampIndex = 0;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700240 }
241}
242
243bool VSyncPredictor::needsMoreSamples(nsecs_t now) const {
244 using namespace std::literals::chrono_literals;
245 std::lock_guard<std::mutex> lk(mMutex);
246 bool needsMoreSamples = true;
Ady Abraham92fa2f42020-02-11 15:33:56 -0800247 if (mTimestamps.size() >= kMinimumSamplesForPrediction) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700248 nsecs_t constexpr aLongTime =
249 std::chrono::duration_cast<std::chrono::nanoseconds>(500ms).count();
Ady Abraham92fa2f42020-02-11 15:33:56 -0800250 if (!(mLastTimestampIndex < 0 || mTimestamps.empty())) {
251 auto const lastTimestamp = mTimestamps[mLastTimestampIndex];
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700252 needsMoreSamples = !((lastTimestamp + aLongTime) > now);
253 }
254 }
255
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800256 ATRACE_INT("VSP-moreSamples", needsMoreSamples);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700257 return needsMoreSamples;
258}
259
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800260void VSyncPredictor::resetModel() {
261 std::lock_guard<std::mutex> lk(mMutex);
262 mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
263 clearTimestamps();
264}
265
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700266} // namespace android::scheduler
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800267
268// TODO(b/129481165): remove the #pragma below and fix conversion issues
269#pragma clang diagnostic pop // ignored "-Wconversion"