blob: cee5f459db1711bdc9c708830a59c719a57ba0cd [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 DuBoisecb1f0d2019-12-12 10:47:41 -080041 : mTraceOn(property_get_bool("debug.sf.vsp_trace", false)),
42 kHistorySize(historySize),
Kevin DuBois1678e2c2019-08-22 12:26:24 -070043 kMinimumSamplesForPrediction(minimumSamplesForPrediction),
44 kOutlierTolerancePercent(std::min(outlierTolerancePercent, kMaxPercent)),
45 mIdealPeriod(idealPeriod) {
46 mRateMap[mIdealPeriod] = {idealPeriod, 0};
47}
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 {
56 return (i + 1) % timestamps.size();
57}
58
59bool VSyncPredictor::validate(nsecs_t timestamp) const {
60 if (lastTimestampIndex < 0 || timestamps.empty()) {
61 return true;
62 }
63
64 auto const aValidTimestamp = timestamps[lastTimestampIndex];
65 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 DuBois1678e2c2019-08-22 12:26:24 -070074void VSyncPredictor::addVsyncTimestamp(nsecs_t timestamp) {
75 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 DuBois1678e2c2019-08-22 12:26:24 -070079 return;
80 }
81
82 if (timestamps.size() != kHistorySize) {
83 timestamps.push_back(timestamp);
84 lastTimestampIndex = next(lastTimestampIndex);
85 } else {
86 lastTimestampIndex = next(lastTimestampIndex);
87 timestamps[lastTimestampIndex] = timestamp;
88 }
89
90 if (timestamps.size() < kMinimumSamplesForPrediction) {
91 mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
92 return;
93 }
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 //
110 std::vector<nsecs_t> vsyncTS(timestamps.size());
111 std::vector<nsecs_t> ordinals(timestamps.size());
112
113 // normalizing to the oldest timestamp cuts down on error in calculating the intercept.
114 auto const oldest_ts = *std::min_element(timestamps.begin(), timestamps.end());
115 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
123 for (auto i = 0u; i < timestamps.size(); i++) {
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800124 traceInt64If("VSP-ts", timestamps[i]);
125
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700126 vsyncTS[i] = timestamps[i] - oldest_ts;
127 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};
146 return;
147 }
148
149 nsecs_t const anticipatedPeriod = top / bottom * kScalingFactor;
150 nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
151
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800152 traceInt64If("VSP-period", anticipatedPeriod);
153 traceInt64If("VSP-intercept", intercept);
154
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700155 it->second = {anticipatedPeriod, intercept};
156
157 ALOGV("model update ts: %" PRId64 " slope: %" PRId64 " intercept: %" PRId64, timestamp,
158 anticipatedPeriod, intercept);
159}
160
161nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint) const {
162 std::lock_guard<std::mutex> lk(mMutex);
163
164 auto const [slope, intercept] = getVSyncPredictionModel(lk);
165
166 if (timestamps.empty()) {
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800167 traceInt64If("VSP-mode", 1);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700168 auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
169 auto const numPeriodsOut = ((timePoint - knownTimestamp) / mIdealPeriod) + 1;
170 return knownTimestamp + numPeriodsOut * mIdealPeriod;
171 }
172
173 auto const oldest = *std::min_element(timestamps.begin(), timestamps.end());
Kevin DuBois127a2d92019-12-04 13:52:52 -0800174
175 // See b/145667109, the ordinal calculation must take into account the intercept.
176 auto const zeroPoint = oldest + intercept;
177 auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700178 auto const prediction = (ordinalRequest * slope) + intercept + oldest;
179
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800180 traceInt64If("VSP-mode", 0);
181 traceInt64If("VSP-timePoint", timePoint);
182 traceInt64If("VSP-prediction", prediction);
183
Kevin DuBois127a2d92019-12-04 13:52:52 -0800184 auto const printer = [&, slope = slope, intercept = intercept] {
185 std::stringstream str;
186 str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
187 << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
188 << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
189 return str.str();
190 };
191
192 ALOGV("%s", printer().c_str());
193 LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
194 printer().c_str());
195
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700196 return prediction;
197}
198
199std::tuple<nsecs_t, nsecs_t> VSyncPredictor::getVSyncPredictionModel() const {
200 std::lock_guard<std::mutex> lk(mMutex);
201 return VSyncPredictor::getVSyncPredictionModel(lk);
202}
203
204std::tuple<nsecs_t, nsecs_t> VSyncPredictor::getVSyncPredictionModel(
205 std::lock_guard<std::mutex> const&) const {
206 return mRateMap.find(mIdealPeriod)->second;
207}
208
209void VSyncPredictor::setPeriod(nsecs_t period) {
210 ATRACE_CALL();
211
212 std::lock_guard<std::mutex> lk(mMutex);
213 static constexpr size_t kSizeLimit = 30;
214 if (CC_UNLIKELY(mRateMap.size() == kSizeLimit)) {
215 mRateMap.erase(mRateMap.begin());
216 }
217
218 mIdealPeriod = period;
219 if (mRateMap.find(period) == mRateMap.end()) {
220 mRateMap[mIdealPeriod] = {period, 0};
221 }
222
223 if (!timestamps.empty()) {
224 mKnownTimestamp = *std::max_element(timestamps.begin(), timestamps.end());
225 timestamps.clear();
226 lastTimestampIndex = 0;
227 }
228}
229
230bool VSyncPredictor::needsMoreSamples(nsecs_t now) const {
231 using namespace std::literals::chrono_literals;
232 std::lock_guard<std::mutex> lk(mMutex);
233 bool needsMoreSamples = true;
234 if (timestamps.size() >= kMinimumSamplesForPrediction) {
235 nsecs_t constexpr aLongTime =
236 std::chrono::duration_cast<std::chrono::nanoseconds>(500ms).count();
237 if (!(lastTimestampIndex < 0 || timestamps.empty())) {
238 auto const lastTimestamp = timestamps[lastTimestampIndex];
239 needsMoreSamples = !((lastTimestamp + aLongTime) > now);
240 }
241 }
242
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800243 ATRACE_INT("VSP-moreSamples", needsMoreSamples);
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700244 return needsMoreSamples;
245}
246
247} // namespace android::scheduler
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800248
249// TODO(b/129481165): remove the #pragma below and fix conversion issues
250#pragma clang diagnostic pop // ignored "-Wconversion"