• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 // TODO(b/129481165): remove the #pragma below and fix conversion issues
18 #pragma clang diagnostic push
19 #pragma clang diagnostic ignored "-Wextra"
20 
21 #undef LOG_TAG
22 #define LOG_TAG "VSyncPredictor"
23 
24 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
25 
26 #include <algorithm>
27 #include <chrono>
28 #include <sstream>
29 
30 #include <android-base/logging.h>
31 #include <android-base/stringprintf.h>
32 #include <cutils/compiler.h>
33 #include <cutils/properties.h>
34 #include <utils/Log.h>
35 #include <utils/Trace.h>
36 
37 #include "RefreshRateConfigs.h"
38 #include "VSyncPredictor.h"
39 
40 namespace android::scheduler {
41 
42 using base::StringAppendF;
43 
44 static auto constexpr kMaxPercent = 100u;
45 
46 VSyncPredictor::~VSyncPredictor() = default;
47 
VSyncPredictor(nsecs_t idealPeriod,size_t historySize,size_t minimumSamplesForPrediction,uint32_t outlierTolerancePercent)48 VSyncPredictor::VSyncPredictor(nsecs_t idealPeriod, size_t historySize,
49                                size_t minimumSamplesForPrediction, uint32_t outlierTolerancePercent)
50       : mTraceOn(property_get_bool("debug.sf.vsp_trace", true)),
51         kHistorySize(historySize),
52         kMinimumSamplesForPrediction(minimumSamplesForPrediction),
53         kOutlierTolerancePercent(std::min(outlierTolerancePercent, kMaxPercent)),
54         mIdealPeriod(idealPeriod) {
55     resetModel();
56 }
57 
traceInt64If(const char * name,int64_t value) const58 inline void VSyncPredictor::traceInt64If(const char* name, int64_t value) const {
59     if (CC_UNLIKELY(mTraceOn)) {
60         ATRACE_INT64(name, value);
61     }
62 }
63 
next(size_t i) const64 inline size_t VSyncPredictor::next(size_t i) const {
65     return (i + 1) % mTimestamps.size();
66 }
67 
validate(nsecs_t timestamp) const68 bool VSyncPredictor::validate(nsecs_t timestamp) const {
69     if (mLastTimestampIndex < 0 || mTimestamps.empty()) {
70         return true;
71     }
72 
73     auto const aValidTimestamp = mTimestamps[mLastTimestampIndex];
74     auto const percent = (timestamp - aValidTimestamp) % mIdealPeriod * kMaxPercent / mIdealPeriod;
75     if (percent >= kOutlierTolerancePercent &&
76         percent <= (kMaxPercent - kOutlierTolerancePercent)) {
77         return false;
78     }
79 
80     const auto iter = std::min_element(mTimestamps.begin(), mTimestamps.end(),
81                                        [timestamp](nsecs_t a, nsecs_t b) {
82                                            return std::abs(timestamp - a) < std::abs(timestamp - b);
83                                        });
84     const auto distancePercent = std::abs(*iter - timestamp) * kMaxPercent / mIdealPeriod;
85     if (distancePercent < kOutlierTolerancePercent) {
86         // duplicate timestamp
87         return false;
88     }
89     return true;
90 }
91 
currentPeriod() const92 nsecs_t VSyncPredictor::currentPeriod() const {
93     std::lock_guard lock(mMutex);
94     return mRateMap.find(mIdealPeriod)->second.slope;
95 }
96 
addVsyncTimestamp(nsecs_t timestamp)97 bool VSyncPredictor::addVsyncTimestamp(nsecs_t timestamp) {
98     std::lock_guard lock(mMutex);
99 
100     if (!validate(timestamp)) {
101         // VSR could elect to ignore the incongruent timestamp or resetModel(). If ts is ignored,
102         // don't insert this ts into mTimestamps ringbuffer. If we are still
103         // in the learning phase we should just clear all timestamps and start
104         // over.
105         if (mTimestamps.size() < kMinimumSamplesForPrediction) {
106             // Add the timestamp to mTimestamps before clearing it so we could
107             // update mKnownTimestamp based on the new timestamp.
108             mTimestamps.push_back(timestamp);
109             clearTimestamps();
110         } else if (!mTimestamps.empty()) {
111             mKnownTimestamp =
112                     std::max(timestamp, *std::max_element(mTimestamps.begin(), mTimestamps.end()));
113         } else {
114             mKnownTimestamp = timestamp;
115         }
116         return false;
117     }
118 
119     if (mTimestamps.size() != kHistorySize) {
120         mTimestamps.push_back(timestamp);
121         mLastTimestampIndex = next(mLastTimestampIndex);
122     } else {
123         mLastTimestampIndex = next(mLastTimestampIndex);
124         mTimestamps[mLastTimestampIndex] = timestamp;
125     }
126 
127     const size_t numSamples = mTimestamps.size();
128     if (numSamples < kMinimumSamplesForPrediction) {
129         mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
130         return true;
131     }
132 
133     // This is a 'simple linear regression' calculation of Y over X, with Y being the
134     // vsync timestamps, and X being the ordinal of vsync count.
135     // The calculated slope is the vsync period.
136     // Formula for reference:
137     // Sigma_i: means sum over all timestamps.
138     // mean(variable): statistical mean of variable.
139     // X: snapped ordinal of the timestamp
140     // Y: vsync timestamp
141     //
142     //         Sigma_i( (X_i - mean(X)) * (Y_i - mean(Y) )
143     // slope = -------------------------------------------
144     //         Sigma_i ( X_i - mean(X) ) ^ 2
145     //
146     // intercept = mean(Y) - slope * mean(X)
147     //
148     std::vector<nsecs_t> vsyncTS(numSamples);
149     std::vector<nsecs_t> ordinals(numSamples);
150 
151     // Normalizing to the oldest timestamp cuts down on error in calculating the intercept.
152     const auto oldestTS = *std::min_element(mTimestamps.begin(), mTimestamps.end());
153     auto it = mRateMap.find(mIdealPeriod);
154     auto const currentPeriod = it->second.slope;
155 
156     // The mean of the ordinals must be precise for the intercept calculation, so scale them up for
157     // fixed-point arithmetic.
158     constexpr int64_t kScalingFactor = 1000;
159 
160     nsecs_t meanTS = 0;
161     nsecs_t meanOrdinal = 0;
162 
163     for (size_t i = 0; i < numSamples; i++) {
164         traceInt64If("VSP-ts", mTimestamps[i]);
165 
166         const auto timestamp = mTimestamps[i] - oldestTS;
167         vsyncTS[i] = timestamp;
168         meanTS += timestamp;
169 
170         const auto ordinal = (vsyncTS[i] + currentPeriod / 2) / currentPeriod * kScalingFactor;
171         ordinals[i] = ordinal;
172         meanOrdinal += ordinal;
173     }
174 
175     meanTS /= numSamples;
176     meanOrdinal /= numSamples;
177 
178     for (size_t i = 0; i < numSamples; i++) {
179         vsyncTS[i] -= meanTS;
180         ordinals[i] -= meanOrdinal;
181     }
182 
183     nsecs_t top = 0;
184     nsecs_t bottom = 0;
185     for (size_t i = 0; i < numSamples; i++) {
186         top += vsyncTS[i] * ordinals[i];
187         bottom += ordinals[i] * ordinals[i];
188     }
189 
190     if (CC_UNLIKELY(bottom == 0)) {
191         it->second = {mIdealPeriod, 0};
192         clearTimestamps();
193         return false;
194     }
195 
196     nsecs_t const anticipatedPeriod = top * kScalingFactor / bottom;
197     nsecs_t const intercept = meanTS - (anticipatedPeriod * meanOrdinal / kScalingFactor);
198 
199     auto const percent = std::abs(anticipatedPeriod - mIdealPeriod) * kMaxPercent / mIdealPeriod;
200     if (percent >= kOutlierTolerancePercent) {
201         it->second = {mIdealPeriod, 0};
202         clearTimestamps();
203         return false;
204     }
205 
206     traceInt64If("VSP-period", anticipatedPeriod);
207     traceInt64If("VSP-intercept", intercept);
208 
209     it->second = {anticipatedPeriod, intercept};
210 
211     ALOGV("model update ts: %" PRId64 " slope: %" PRId64 " intercept: %" PRId64, timestamp,
212           anticipatedPeriod, intercept);
213     return true;
214 }
215 
nextAnticipatedVSyncTimeFromLocked(nsecs_t timePoint) const216 nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFromLocked(nsecs_t timePoint) const {
217     auto const [slope, intercept] = getVSyncPredictionModelLocked();
218 
219     if (mTimestamps.empty()) {
220         traceInt64If("VSP-mode", 1);
221         auto const knownTimestamp = mKnownTimestamp ? *mKnownTimestamp : timePoint;
222         auto const numPeriodsOut = ((timePoint - knownTimestamp) / mIdealPeriod) + 1;
223         return knownTimestamp + numPeriodsOut * mIdealPeriod;
224     }
225 
226     auto const oldest = *std::min_element(mTimestamps.begin(), mTimestamps.end());
227 
228     // See b/145667109, the ordinal calculation must take into account the intercept.
229     auto const zeroPoint = oldest + intercept;
230     auto const ordinalRequest = (timePoint - zeroPoint + slope) / slope;
231     auto const prediction = (ordinalRequest * slope) + intercept + oldest;
232 
233     traceInt64If("VSP-mode", 0);
234     traceInt64If("VSP-timePoint", timePoint);
235     traceInt64If("VSP-prediction", prediction);
236 
237     auto const printer = [&, slope = slope, intercept = intercept] {
238         std::stringstream str;
239         str << "prediction made from: " << timePoint << "prediction: " << prediction << " (+"
240             << prediction - timePoint << ") slope: " << slope << " intercept: " << intercept
241             << "oldestTS: " << oldest << " ordinal: " << ordinalRequest;
242         return str.str();
243     };
244 
245     ALOGV("%s", printer().c_str());
246     LOG_ALWAYS_FATAL_IF(prediction < timePoint, "VSyncPredictor: model miscalculation: %s",
247                         printer().c_str());
248 
249     return prediction;
250 }
251 
nextAnticipatedVSyncTimeFrom(nsecs_t timePoint) const252 nsecs_t VSyncPredictor::nextAnticipatedVSyncTimeFrom(nsecs_t timePoint) const {
253     std::lock_guard lock(mMutex);
254     return nextAnticipatedVSyncTimeFromLocked(timePoint);
255 }
256 
257 /*
258  * Returns whether a given vsync timestamp is in phase with a frame rate.
259  * If the frame rate is not a divisor of the refresh rate, it is always considered in phase.
260  * For example, if the vsync timestamps are (16.6,33.3,50.0,66.6):
261  * isVSyncInPhase(16.6, 30) = true
262  * isVSyncInPhase(33.3, 30) = false
263  * isVSyncInPhase(50.0, 30) = true
264  */
isVSyncInPhase(nsecs_t timePoint,Fps frameRate) const265 bool VSyncPredictor::isVSyncInPhase(nsecs_t timePoint, Fps frameRate) const {
266     struct VsyncError {
267         nsecs_t vsyncTimestamp;
268         float error;
269 
270         bool operator<(const VsyncError& other) const { return error < other.error; }
271     };
272 
273     std::lock_guard lock(mMutex);
274     const auto divisor =
275             RefreshRateConfigs::getFrameRateDivisor(Fps::fromPeriodNsecs(mIdealPeriod), frameRate);
276     if (divisor <= 1 || timePoint == 0) {
277         return true;
278     }
279 
280     const nsecs_t period = mRateMap[mIdealPeriod].slope;
281     const nsecs_t justBeforeTimePoint = timePoint - period / 2;
282     const nsecs_t dividedPeriod = mIdealPeriod / divisor;
283 
284     // If this is the first time we have asked about this divisor with the
285     // current vsync period, it is considered in phase and we store the closest
286     // vsync timestamp
287     const auto knownTimestampIter = mRateDivisorKnownTimestampMap.find(dividedPeriod);
288     if (knownTimestampIter == mRateDivisorKnownTimestampMap.end()) {
289         const auto vsync = nextAnticipatedVSyncTimeFromLocked(justBeforeTimePoint);
290         mRateDivisorKnownTimestampMap[dividedPeriod] = vsync;
291         return true;
292     }
293 
294     // Find the next N vsync timestamp where N is the divisor.
295     // One of these vsyncs will be in phase. We return the one which is
296     // the most aligned with the last known in phase vsync
297     std::vector<VsyncError> vsyncs(static_cast<size_t>(divisor));
298     const nsecs_t knownVsync = knownTimestampIter->second;
299     nsecs_t point = justBeforeTimePoint;
300     for (size_t i = 0; i < divisor; i++) {
301         const nsecs_t vsync = nextAnticipatedVSyncTimeFromLocked(point);
302         const auto numPeriods = static_cast<float>(vsync - knownVsync) / (period * divisor);
303         const auto error = std::abs(std::round(numPeriods) - numPeriods);
304         vsyncs[i] = {vsync, error};
305         point = vsync + 1;
306     }
307 
308     const auto minVsyncError = std::min_element(vsyncs.begin(), vsyncs.end());
309     mRateDivisorKnownTimestampMap[dividedPeriod] = minVsyncError->vsyncTimestamp;
310     return std::abs(minVsyncError->vsyncTimestamp - timePoint) < period / 2;
311 }
312 
getVSyncPredictionModel() const313 VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModel() const {
314     std::lock_guard lock(mMutex);
315     const auto model = VSyncPredictor::getVSyncPredictionModelLocked();
316     return {model.slope, model.intercept};
317 }
318 
getVSyncPredictionModelLocked() const319 VSyncPredictor::Model VSyncPredictor::getVSyncPredictionModelLocked() const {
320     return mRateMap.find(mIdealPeriod)->second;
321 }
322 
setPeriod(nsecs_t period)323 void VSyncPredictor::setPeriod(nsecs_t period) {
324     ATRACE_CALL();
325 
326     std::lock_guard lock(mMutex);
327     static constexpr size_t kSizeLimit = 30;
328     if (CC_UNLIKELY(mRateMap.size() == kSizeLimit)) {
329         mRateMap.erase(mRateMap.begin());
330     }
331 
332     mIdealPeriod = period;
333     if (mRateMap.find(period) == mRateMap.end()) {
334         mRateMap[mIdealPeriod] = {period, 0};
335     }
336 
337     clearTimestamps();
338 }
339 
clearTimestamps()340 void VSyncPredictor::clearTimestamps() {
341     if (!mTimestamps.empty()) {
342         auto const maxRb = *std::max_element(mTimestamps.begin(), mTimestamps.end());
343         if (mKnownTimestamp) {
344             mKnownTimestamp = std::max(*mKnownTimestamp, maxRb);
345         } else {
346             mKnownTimestamp = maxRb;
347         }
348 
349         mTimestamps.clear();
350         mLastTimestampIndex = 0;
351     }
352 }
353 
needsMoreSamples() const354 bool VSyncPredictor::needsMoreSamples() const {
355     std::lock_guard lock(mMutex);
356     return mTimestamps.size() < kMinimumSamplesForPrediction;
357 }
358 
resetModel()359 void VSyncPredictor::resetModel() {
360     std::lock_guard lock(mMutex);
361     mRateMap[mIdealPeriod] = {mIdealPeriod, 0};
362     clearTimestamps();
363 }
364 
dump(std::string & result) const365 void VSyncPredictor::dump(std::string& result) const {
366     std::lock_guard lock(mMutex);
367     StringAppendF(&result, "\tmIdealPeriod=%.2f\n", mIdealPeriod / 1e6f);
368     StringAppendF(&result, "\tRefresh Rate Map:\n");
369     for (const auto& [idealPeriod, periodInterceptTuple] : mRateMap) {
370         StringAppendF(&result,
371                       "\t\tFor ideal period %.2fms: period = %.2fms, intercept = %" PRId64 "\n",
372                       idealPeriod / 1e6f, periodInterceptTuple.slope / 1e6f,
373                       periodInterceptTuple.intercept);
374     }
375 }
376 
377 } // namespace android::scheduler
378 
379 // TODO(b/129481165): remove the #pragma below and fix conversion issues
380 #pragma clang diagnostic pop // ignored "-Wextra"
381