blob: 915419154f7bed8ff86b68c235d816e63e527132 [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>
26#include <utils/Log.h>
27#include <utils/Trace.h>
28#include <algorithm>
29#include <chrono>
Kevin DuBois127a2d92019-12-04 13:52:52 -080030#include <sstream>
Kevin DuBois1678e2c2019-08-22 12:26:24 -070031#include "SchedulerUtils.h"
32
33namespace android::scheduler {
34static auto constexpr kNeedsSamplesTag = "SamplesRequested";
35static auto constexpr kMaxPercent = 100u;
36
37VSyncPredictor::~VSyncPredictor() = default;
38
39VSyncPredictor::VSyncPredictor(nsecs_t idealPeriod, size_t historySize,
40 size_t minimumSamplesForPrediction, uint32_t outlierTolerancePercent)
41 : kHistorySize(historySize),
42 kMinimumSamplesForPrediction(minimumSamplesForPrediction),
43 kOutlierTolerancePercent(std::min(outlierTolerancePercent, kMaxPercent)),
44 mIdealPeriod(idealPeriod) {
45 mRateMap[mIdealPeriod] = {idealPeriod, 0};
46}
47
48inline size_t VSyncPredictor::next(int i) const {
49 return (i + 1) % timestamps.size();
50}
51
52bool VSyncPredictor::validate(nsecs_t timestamp) const {
53 if (lastTimestampIndex < 0 || timestamps.empty()) {
54 return true;
55 }
56
57 auto const aValidTimestamp = timestamps[lastTimestampIndex];
58 auto const percent = (timestamp - aValidTimestamp) % mIdealPeriod * kMaxPercent / mIdealPeriod;
59 return percent < kOutlierTolerancePercent || percent > (kMaxPercent - kOutlierTolerancePercent);
60}
61
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080062nsecs_t VSyncPredictor::currentPeriod() const {
63 std::lock_guard<std::mutex> lk(mMutex);
64 return std::get<0>(mRateMap.find(mIdealPeriod)->second);
65}
66
Kevin DuBois1678e2c2019-08-22 12:26:24 -070067void VSyncPredictor::addVsyncTimestamp(nsecs_t timestamp) {
68 std::lock_guard<std::mutex> lk(mMutex);
69
70 if (!validate(timestamp)) {
71 ALOGW("timestamp was too far off the last known timestamp");
72 return;
73 }
74
75 if (timestamps.size() != kHistorySize) {
76 timestamps.push_back(timestamp);
77 lastTimestampIndex = next(lastTimestampIndex);
78 } else {
79 lastTimestampIndex = next(lastTimestampIndex);
80 timestamps[lastTimestampIndex] = timestamp;
81 }
82
83 if (timestamps.size() < kMinimumSamplesForPrediction) {
84 mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
85 return;
86 }
87
88 // This is a 'simple linear regression' calculation of Y over X, with Y being the
89 // vsync timestamps, and X being the ordinal of vsync count.
90 // The calculated slope is the vsync period.
91 // Formula for reference:
92 // Sigma_i: means sum over all timestamps.
93 // mean(variable): statistical mean of variable.
94 // X: snapped ordinal of the timestamp
95 // Y: vsync timestamp
96 //
97 // Sigma_i( (X_i - mean(X)) * (Y_i - mean(Y) )
98 // slope = -------------------------------------------
99 // Sigma_i ( X_i - mean(X) ) ^ 2
100 //
101 // intercept = mean(Y) - slope * mean(X)
102 //
103 std::vector<nsecs_t> vsyncTS(timestamps.size());
104 std::vector<nsecs_t> ordinals(timestamps.size());
105
106 // normalizing to the oldest timestamp cuts down on error in calculating the intercept.
107 auto const oldest_ts = *std::min_element(timestamps.begin(), timestamps.end());
108 auto it = mRateMap.find(mIdealPeriod);
109 auto const currentPeriod = std::get<0>(it->second);
110 // TODO (b/144707443): its important that there's some precision in the mean of the ordinals
111 // for the intercept calculation, so scale the ordinals by 10 to continue
112 // fixed point calculation. Explore expanding
113 // scheduler::utils::calculate_mean to have a fixed point fractional part.
114 static constexpr int kScalingFactor = 10;
115
116 for (auto i = 0u; i < timestamps.size(); i++) {
117 vsyncTS[i] = timestamps[i] - oldest_ts;
118 ordinals[i] = ((vsyncTS[i] + (currentPeriod / 2)) / currentPeriod) * kScalingFactor;
119 }
120
121 auto meanTS = scheduler::calculate_mean(vsyncTS);
122 auto meanOrdinal = scheduler::calculate_mean(ordinals);
123 for (auto i = 0; i < vsyncTS.size(); i++) {
124 vsyncTS[i] -= meanTS;
125 ordinals[i] -= meanOrdinal;
126 }
127
128 auto top = 0ll;
129 auto bottom = 0ll;
130 for (auto i = 0; i < vsyncTS.size(); i++) {
131 top += vsyncTS[i] * ordinals[i];
132 bottom += ordinals[i] * ordinals[i];
133 }
134
135 if (CC_UNLIKELY(bottom == 0)) {
136 it->second = {mIdealPeriod, 0};
137 return;
138 }
139
140 nsecs_t const anticipatedPeriod = top / bottom * kScalingFactor;
141 nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
142
143 it->second = {anticipatedPeriod, intercept};
144
145 ALOGV("model update ts: %" PRId64 " slope: %" PRId64 " intercept: %" PRId64, timestamp,
146 anticipatedPeriod, intercept);
147}
148
149nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint) const {
150 std::lock_guard<std::mutex> lk(mMutex);
151
152 auto const [slope, intercept] = getVSyncPredictionModel(lk);
153
154 if (timestamps.empty()) {
155 auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
156 auto const numPeriodsOut = ((timePoint - knownTimestamp) / mIdealPeriod) + 1;
157 return knownTimestamp + numPeriodsOut * mIdealPeriod;
158 }
159
160 auto const oldest = *std::min_element(timestamps.begin(), timestamps.end());
Kevin DuBois127a2d92019-12-04 13:52:52 -0800161
162 // See b/145667109, the ordinal calculation must take into account the intercept.
163 auto const zeroPoint = oldest + intercept;
164 auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700165 auto const prediction = (ordinalRequest * slope) + intercept + oldest;
166
Kevin DuBois127a2d92019-12-04 13:52:52 -0800167 auto const printer = [&, slope = slope, intercept = intercept] {
168 std::stringstream str;
169 str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
170 << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
171 << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
172 return str.str();
173 };
174
175 ALOGV("%s", printer().c_str());
176 LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
177 printer().c_str());
178
Kevin DuBois1678e2c2019-08-22 12:26:24 -0700179 return prediction;
180}
181
182std::tuple<nsecs_t, nsecs_t> VSyncPredictor::getVSyncPredictionModel() const {
183 std::lock_guard<std::mutex> lk(mMutex);
184 return VSyncPredictor::getVSyncPredictionModel(lk);
185}
186
187std::tuple<nsecs_t, nsecs_t> VSyncPredictor::getVSyncPredictionModel(
188 std::lock_guard<std::mutex> const&) const {
189 return mRateMap.find(mIdealPeriod)->second;
190}
191
192void VSyncPredictor::setPeriod(nsecs_t period) {
193 ATRACE_CALL();
194
195 std::lock_guard<std::mutex> lk(mMutex);
196 static constexpr size_t kSizeLimit = 30;
197 if (CC_UNLIKELY(mRateMap.size() == kSizeLimit)) {
198 mRateMap.erase(mRateMap.begin());
199 }
200
201 mIdealPeriod = period;
202 if (mRateMap.find(period) == mRateMap.end()) {
203 mRateMap[mIdealPeriod] = {period, 0};
204 }
205
206 if (!timestamps.empty()) {
207 mKnownTimestamp = *std::max_element(timestamps.begin(), timestamps.end());
208 timestamps.clear();
209 lastTimestampIndex = 0;
210 }
211}
212
213bool VSyncPredictor::needsMoreSamples(nsecs_t now) const {
214 using namespace std::literals::chrono_literals;
215 std::lock_guard<std::mutex> lk(mMutex);
216 bool needsMoreSamples = true;
217 if (timestamps.size() >= kMinimumSamplesForPrediction) {
218 nsecs_t constexpr aLongTime =
219 std::chrono::duration_cast<std::chrono::nanoseconds>(500ms).count();
220 if (!(lastTimestampIndex < 0 || timestamps.empty())) {
221 auto const lastTimestamp = timestamps[lastTimestampIndex];
222 needsMoreSamples = !((lastTimestamp + aLongTime) > now);
223 }
224 }
225
226 ATRACE_INT(kNeedsSamplesTag, needsMoreSamples);
227 return needsMoreSamples;
228}
229
230} // namespace android::scheduler
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800231
232// TODO(b/129481165): remove the #pragma below and fix conversion issues
233#pragma clang diagnostic pop // ignored "-Wconversion"