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