blob: a3cb7725a71d9c1b23321f309de2ea1d68b41c47 [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 DuBoisecb1f0d2019-12-12 10:47:41 -080080 ALOGV("timestamp was too far off the last known timestamp");
Kevin DuBois02d5ed92020-01-27 11:05:46 -080081 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -070082 }
83
Ady Abraham92fa2f42020-02-11 15:33:56 -080084 if (mTimestamps.size() != kHistorySize) {
85 mTimestamps.push_back(timestamp);
86 mLastTimestampIndex = next(mLastTimestampIndex);
Kevin DuBois1678e2c2019-08-22 12:26:24 -070087 } else {
Ady Abraham92fa2f42020-02-11 15:33:56 -080088 mLastTimestampIndex = next(mLastTimestampIndex);
89 mTimestamps[mLastTimestampIndex] = timestamp;
Kevin DuBois1678e2c2019-08-22 12:26:24 -070090 }
91
Ady Abraham92fa2f42020-02-11 15:33:56 -080092 if (mTimestamps.size() < kMinimumSamplesForPrediction) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -070093 mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
Kevin DuBois02d5ed92020-01-27 11:05:46 -080094 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -070095 }
96
97 // This is a 'simple linear regression' calculation of Y over X, with Y being the
98 // vsync timestamps, and X being the ordinal of vsync count.
99 // The calculated slope is the vsync period.
100 // Formula for reference:
101 // Sigma_i: means sum over all timestamps.
102 // mean(variable): statistical mean of variable.
103 // X: snapped ordinal of the timestamp
104 // Y: vsync timestamp
105 //
106 // Sigma_i( (X_i - mean(X)) * (Y_i - mean(Y) )
107 // slope = -------------------------------------------
108 // Sigma_i ( X_i - mean(X) ) ^ 2
109 //
110 // intercept = mean(Y) - slope * mean(X)
111 //
Ady Abraham92fa2f42020-02-11 15:33:56 -0800112 std::vector<nsecs_t> vsyncTS(mTimestamps.size());
113 std::vector<nsecs_t> ordinals(mTimestamps.size());
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700114
115 // normalizing to the oldest timestamp cuts down on error in calculating the intercept.
Ady Abraham92fa2f42020-02-11 15:33:56 -0800116 auto const oldest_ts = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700117 auto it = mRateMap.find(mIdealPeriod);
118 auto const currentPeriod = std::get<0>(it->second);
119 // TODO (b/144707443): its important that there's some precision in the mean of the ordinals
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700120 // for the intercept calculation, so scale the ordinals by 1000 to continue
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700121 // fixed point calculation. Explore expanding
122 // scheduler::utils::calculate_mean to have a fixed point fractional part.
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700123 static constexpr int64_t kScalingFactor = 1000;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700124
Ady Abraham92fa2f42020-02-11 15:33:56 -0800125 for (auto i = 0u; i < mTimestamps.size(); i++) {
126 traceInt64If("VSP-ts", mTimestamps[i]);
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800127
Ady Abraham92fa2f42020-02-11 15:33:56 -0800128 vsyncTS[i] = mTimestamps[i] - oldest_ts;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700129 ordinals[i] = ((vsyncTS[i] + (currentPeriod / 2)) / currentPeriod) * kScalingFactor;
130 }
131
132 auto meanTS = scheduler::calculate_mean(vsyncTS);
133 auto meanOrdinal = scheduler::calculate_mean(ordinals);
134 for (auto i = 0; i < vsyncTS.size(); i++) {
135 vsyncTS[i] -= meanTS;
136 ordinals[i] -= meanOrdinal;
137 }
138
139 auto top = 0ll;
140 auto bottom = 0ll;
141 for (auto i = 0; i < vsyncTS.size(); i++) {
142 top += vsyncTS[i] * ordinals[i];
143 bottom += ordinals[i] * ordinals[i];
144 }
145
146 if (CC_UNLIKELY(bottom == 0)) {
147 it->second = {mIdealPeriod, 0};
Ady Abraham92fa2f42020-02-11 15:33:56 -0800148 clearTimestamps();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800149 return false;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700150 }
151
Kevin DuBois0049f8b2020-03-11 10:30:11 -0700152 nsecs_t const anticipatedPeriod = top * kScalingFactor / bottom;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700153 nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
154
Ady Abraham92fa2f42020-02-11 15:33:56 -0800155 auto const percent = std::abs(anticipatedPeriod - mIdealPeriod) * kMaxPercent / mIdealPeriod;
156 if (percent >= kOutlierTolerancePercent) {
157 it->second = {mIdealPeriod, 0};
158 clearTimestamps();
159 return false;
160 }
161
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800162 traceInt64If("VSP-period", anticipatedPeriod);
163 traceInt64If("VSP-intercept", intercept);
164
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700165 it->second = {anticipatedPeriod, intercept};
166
167 ALOGV("model update ts: %" PRId64 " slope: %" PRId64 " intercept: %" PRId64, timestamp,
168 anticipatedPeriod, intercept);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800169 return true;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700170}
171
172nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint) const {
173 std::lock_guard<std::mutex> lk(mMutex);
174
175 auto const [slope, intercept] = getVSyncPredictionModel(lk);
176
Ady Abraham92fa2f42020-02-11 15:33:56 -0800177 if (mTimestamps.empty()) {
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800178 traceInt64If("VSP-mode", 1);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700179 auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
180 auto const numPeriodsOut = ((timePoint - knownTimestamp) / mIdealPeriod) + 1;
181 return knownTimestamp + numPeriodsOut * mIdealPeriod;
182 }
183
Ady Abraham92fa2f42020-02-11 15:33:56 -0800184 auto const oldest = *std::min_element(mTimestamps.begin(), mTimestamps.end());
Kevin DuBois127a2d92019-12-04 13:52:52 -0800185
186 // See b/145667109, the ordinal calculation must take into account the intercept.
187 auto const zeroPoint = oldest + intercept;
188 auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700189 auto const prediction = (ordinalRequest * slope) + intercept + oldest;
190
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800191 traceInt64If("VSP-mode", 0);
192 traceInt64If("VSP-timePoint", timePoint);
193 traceInt64If("VSP-prediction", prediction);
194
Kevin DuBois127a2d92019-12-04 13:52:52 -0800195 auto const printer = [&, slope = slope, intercept = intercept] {
196 std::stringstream str;
197 str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
198 << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
199 << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
200 return str.str();
201 };
202
203 ALOGV("%s", printer().c_str());
204 LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
205 printer().c_str());
206
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700207 return prediction;
208}
209
210std::tuple<nsecs_t, nsecs_t> VSyncPredictor::getVSyncPredictionModel() const {
211 std::lock_guard<std::mutex> lk(mMutex);
212 return VSyncPredictor::getVSyncPredictionModel(lk);
213}
214
215std::tuple<nsecs_t, nsecs_t> VSyncPredictor::getVSyncPredictionModel(
216 std::lock_guard<std::mutex> const&) const {
217 return mRateMap.find(mIdealPeriod)->second;
218}
219
220void VSyncPredictor::setPeriod(nsecs_t period) {
221 ATRACE_CALL();
222
223 std::lock_guard<std::mutex> lk(mMutex);
224 static constexpr size_t kSizeLimit = 30;
225 if (CC_UNLIKELY(mRateMap.size() == kSizeLimit)) {
226 mRateMap.erase(mRateMap.begin());
227 }
228
229 mIdealPeriod = period;
230 if (mRateMap.find(period) == mRateMap.end()) {
231 mRateMap[mIdealPeriod] = {period, 0};
232 }
233
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800234 clearTimestamps();
235}
236
237void VSyncPredictor::clearTimestamps() {
Ady Abraham92fa2f42020-02-11 15:33:56 -0800238 if (!mTimestamps.empty()) {
239 mKnownTimestamp = *std::max_element(mTimestamps.begin(), mTimestamps.end());
240 mTimestamps.clear();
241 mLastTimestampIndex = 0;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700242 }
243}
244
245bool VSyncPredictor::needsMoreSamples(nsecs_t now) const {
246 using namespace std::literals::chrono_literals;
247 std::lock_guard<std::mutex> lk(mMutex);
248 bool needsMoreSamples = true;
Ady Abraham92fa2f42020-02-11 15:33:56 -0800249 if (mTimestamps.size() >= kMinimumSamplesForPrediction) {
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700250 nsecs_t constexpr aLongTime =
251 std::chrono::duration_cast<std::chrono::nanoseconds>(500ms).count();
Ady Abraham92fa2f42020-02-11 15:33:56 -0800252 if (!(mLastTimestampIndex < 0 || mTimestamps.empty())) {
253 auto const lastTimestamp = mTimestamps[mLastTimestampIndex];
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700254 needsMoreSamples = !((lastTimestamp + aLongTime) > now);
255 }
256 }
257
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800258 ATRACE_INT("VSP-moreSamples", needsMoreSamples);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700259 return needsMoreSamples;
260}
261
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800262void VSyncPredictor::resetModel() {
263 std::lock_guard<std::mutex> lk(mMutex);
264 mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
265 clearTimestamps();
266}
267
Ady Abraham5e7371c2020-03-24 14:47:24 -0700268void VSyncPredictor::dump(std::string& result) const {
269 std::lock_guard<std::mutex> lk(mMutex);
270 StringAppendF(&result, "\tmIdealPeriod=%.2f\n", mIdealPeriod / 1e6f);
271 StringAppendF(&result, "\tRefresh Rate Map:\n");
272 for (const auto& [idealPeriod, periodInterceptTuple] : mRateMap) {
273 StringAppendF(&result,
274 "\t\tFor ideal period %.2fms: period = %.2fms, intercept = %" PRId64 "\n",
275 idealPeriod / 1e6f, std::get<0>(periodInterceptTuple) / 1e6f,
276 std::get<1>(periodInterceptTuple));
277 }
278}
279
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700280} // namespace android::scheduler
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800281
282// TODO(b/129481165): remove the #pragma below and fix conversion issues
283#pragma clang diagnostic pop // ignored "-Wconversion"