blob: 7a44c4e845cc94d290cb58a4ebacd849d653a535 [file] [log] [blame]
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001/*
2 * Copyright (C) 2013 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
Tim Murray4a4e4a22016-04-19 16:29:23 +000018//#define LOG_NDEBUG 0
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070019
20// This is needed for stdint.h to define INT64_MAX in C++
21#define __STDC_LIMIT_MACROS
22
23#include <math.h>
24
Mark Salyzyna5e161b2016-09-29 08:08:05 -070025#include <algorithm>
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070026
Yiwei Zhang5434a782018-12-05 18:06:32 -080027#include <android-base/stringprintf.h>
David Sodman1afa8b02018-10-15 11:20:48 -070028#include <cutils/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080029#include <log/log.h>
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070030#include <utils/Thread.h>
31#include <utils/Trace.h>
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070032
Brian Andersonfbc80ae2017-05-26 16:23:54 -070033#include <ui/FenceTime.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070034
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070035#include "DispSync.h"
36#include "EventLog/EventLog.h"
Lloyd Pique78ce4182018-01-31 16:39:51 -080037#include "SurfaceFlinger.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070038
Yiwei Zhang5434a782018-12-05 18:06:32 -080039using android::base::StringAppendF;
Tim Murray4a4e4a22016-04-19 16:29:23 +000040using std::max;
41using std::min;
42
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070043namespace android {
44
Lloyd Pique41be5d22018-06-21 13:11:48 -070045DispSync::~DispSync() = default;
Kevin DuBois7b743be2019-02-27 10:05:48 -080046DispSync::Callback::~Callback() = default;
Lloyd Pique41be5d22018-06-21 13:11:48 -070047
48namespace impl {
49
Tim Murray4a4e4a22016-04-19 16:29:23 +000050// Setting this to true adds a zero-phase tracer for correlating with hardware
51// vsync events
52static const bool kEnableZeroPhaseTracer = false;
53
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070054// This is the threshold used to determine when hardware vsync events are
55// needed to re-synchronize the software vsync model with the hardware. The
56// error metric used is the mean of the squared difference between each
57// present time and the nearest software-predicted vsync.
Lloyd Pique78ce4182018-01-31 16:39:51 -080058static const nsecs_t kErrorThreshold = 160000000000; // 400 usec squared
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070059
Tim Murray4a4e4a22016-04-19 16:29:23 +000060#undef LOG_TAG
61#define LOG_TAG "DispSyncThread"
Lloyd Pique78ce4182018-01-31 16:39:51 -080062class DispSyncThread : public Thread {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070063public:
Ana Krulec064a82f2018-09-11 16:03:03 -070064 DispSyncThread(const char* name, bool showTraceDetailedInfo)
Lloyd Pique78ce4182018-01-31 16:39:51 -080065 : mName(name),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070066 mStop(false),
Alec Mouri016b8dd2019-04-24 15:16:05 -070067 mModelLocked(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068 mPeriod(0),
69 mPhase(0),
Haixia Shi676b1f62015-10-28 16:19:01 -070070 mReferenceTime(0),
Tim Murray4a4e4a22016-04-19 16:29:23 +000071 mWakeupLatency(0),
Ana Krulec064a82f2018-09-11 16:03:03 -070072 mFrameNumber(0),
73 mTraceDetailedInfo(showTraceDetailedInfo) {}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070074
75 virtual ~DispSyncThread() {}
76
Haixia Shi676b1f62015-10-28 16:19:01 -070077 void updateModel(nsecs_t period, nsecs_t phase, nsecs_t referenceTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -070078 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070079 Mutex::Autolock lock(mMutex);
Alec Mouri75b0b622019-03-12 18:56:00 +000080
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070081 mPhase = phase;
Alec Mouri1f534ab2019-05-21 00:51:01 -070082 const bool referenceTimeChanged = mReferenceTime != referenceTime;
Haixia Shi676b1f62015-10-28 16:19:01 -070083 mReferenceTime = referenceTime;
Alec Mouri75b0b622019-03-12 18:56:00 +000084 if (mPeriod != 0 && mPeriod != period && mReferenceTime != 0) {
85 // Inflate the reference time to be the most recent predicted
86 // vsync before the current time.
87 const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
88 const nsecs_t baseTime = now - mReferenceTime;
89 const nsecs_t numOldPeriods = baseTime / mPeriod;
90 mReferenceTime = mReferenceTime + (numOldPeriods)*mPeriod;
91 }
92 mPeriod = period;
Alec Mouri1f534ab2019-05-21 00:51:01 -070093 if (!mModelLocked && referenceTimeChanged) {
94 for (auto& eventListener : mEventListeners) {
95 eventListener.mHasFired = false;
96 eventListener.mLastEventTime =
97 mReferenceTime - mPeriod + mPhase + eventListener.mPhase;
98 }
99 }
Alec Mourif5fe85c2019-02-22 13:40:36 -0800100 if (mTraceDetailedInfo) {
101 ATRACE_INT64("DispSync:Period", mPeriod);
102 ATRACE_INT64("DispSync:Phase", mPhase + mPeriod / 2);
103 ATRACE_INT64("DispSync:Reference Time", mReferenceTime);
104 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000105 ALOGV("[%s] updateModel: mPeriod = %" PRId64 ", mPhase = %" PRId64
Lloyd Pique78ce4182018-01-31 16:39:51 -0800106 " mReferenceTime = %" PRId64,
107 mName, ns2us(mPeriod), ns2us(mPhase), ns2us(mReferenceTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108 mCond.signal();
109 }
110
111 void stop() {
Ana Krulec064a82f2018-09-11 16:03:03 -0700112 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700113 Mutex::Autolock lock(mMutex);
114 mStop = true;
115 mCond.signal();
116 }
117
Alec Mouri016b8dd2019-04-24 15:16:05 -0700118 void lockModel() {
119 Mutex::Autolock lock(mMutex);
120 mModelLocked = true;
121 }
122
123 void unlockModel() {
124 Mutex::Autolock lock(mMutex);
Alec Mouri1f534ab2019-05-21 00:51:01 -0700125 if (mModelLocked) {
126 for (auto& eventListener : mEventListeners) {
127 if (eventListener.mLastEventTime > mReferenceTime) {
128 eventListener.mHasFired = true;
129 }
130 }
131 }
Alec Mouri016b8dd2019-04-24 15:16:05 -0700132 mModelLocked = false;
133 }
134
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700135 virtual bool threadLoop() {
136 status_t err;
137 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700138
139 while (true) {
Ana Krulec9a52b192018-07-12 18:18:47 -0400140 std::vector<CallbackInvocation> callbackInvocations;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700141
142 nsecs_t targetTime = 0;
143
144 { // Scope for lock
145 Mutex::Autolock lock(mMutex);
146
Ana Krulec064a82f2018-09-11 16:03:03 -0700147 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000148 ATRACE_INT64("DispSync:Frame", mFrameNumber);
149 }
150 ALOGV("[%s] Frame %" PRId64, mName, mFrameNumber);
151 ++mFrameNumber;
152
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700153 if (mStop) {
154 return false;
155 }
156
157 if (mPeriod == 0) {
158 err = mCond.wait(mMutex);
159 if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800160 ALOGE("error waiting for new events: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700161 return false;
162 }
163 continue;
164 }
165
Dan Stoza8f8374d2016-04-19 10:03:46 -0700166 targetTime = computeNextEventTimeLocked(now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700167
168 bool isWakeup = false;
169
170 if (now < targetTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700171 if (mTraceDetailedInfo) ATRACE_NAME("DispSync waiting");
Dan Stoza8f8374d2016-04-19 10:03:46 -0700172
173 if (targetTime == INT64_MAX) {
174 ALOGV("[%s] Waiting forever", mName);
175 err = mCond.wait(mMutex);
176 } else {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800177 ALOGV("[%s] Waiting until %" PRId64, mName, ns2us(targetTime));
Dan Stoza8f8374d2016-04-19 10:03:46 -0700178 err = mCond.waitRelative(mMutex, targetTime - now);
179 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700180
181 if (err == TIMED_OUT) {
182 isWakeup = true;
183 } else if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800184 ALOGE("error waiting for next event: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700185 return false;
186 }
187 }
188
189 now = systemTime(SYSTEM_TIME_MONOTONIC);
190
Tim Murray4a4e4a22016-04-19 16:29:23 +0000191 // Don't correct by more than 1.5 ms
192 static const nsecs_t kMaxWakeupLatency = us2ns(1500);
193
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700194 if (isWakeup) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800195 mWakeupLatency = ((mWakeupLatency * 63) + (now - targetTime)) / 64;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000196 mWakeupLatency = min(mWakeupLatency, kMaxWakeupLatency);
Ana Krulec064a82f2018-09-11 16:03:03 -0700197 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000198 ATRACE_INT64("DispSync:WakeupLat", now - targetTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700199 ATRACE_INT64("DispSync:AvgWakeupLat", mWakeupLatency);
200 }
201 }
202
203 callbackInvocations = gatherCallbackInvocationsLocked(now);
204 }
205
206 if (callbackInvocations.size() > 0) {
Andy McFadden645b1f72014-06-10 14:43:32 -0700207 fireCallbackInvocations(callbackInvocations);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700208 }
209 }
210
211 return false;
212 }
213
Alec Mouri7355eb22019-03-05 14:19:10 -0800214 status_t addEventListener(const char* name, nsecs_t phase, DispSync::Callback* callback,
215 nsecs_t lastCallbackTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700216 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700217 Mutex::Autolock lock(mMutex);
218
219 for (size_t i = 0; i < mEventListeners.size(); i++) {
220 if (mEventListeners[i].mCallback == callback) {
221 return BAD_VALUE;
222 }
223 }
224
225 EventListener listener;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000226 listener.mName = name;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700227 listener.mPhase = phase;
228 listener.mCallback = callback;
Jamie Gennis629b9872013-10-29 13:36:12 -0700229
230 // We want to allow the firstmost future event to fire without
Alec Mouri81835982019-02-27 13:40:44 -0800231 // allowing any past events to fire. To do this extrapolate from
232 // mReferenceTime the most recent hardware vsync, and pin the
233 // last event time there.
234 const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
235 if (mPeriod != 0) {
236 const nsecs_t baseTime = now - mReferenceTime;
237 const nsecs_t numPeriodsSinceReference = baseTime / mPeriod;
238 const nsecs_t predictedReference = mReferenceTime + numPeriodsSinceReference * mPeriod;
Alec Mouridf3d2e12019-05-02 17:58:46 +0000239 const nsecs_t phaseCorrection = mPhase + listener.mPhase;
240 const nsecs_t predictedLastEventTime = predictedReference + phaseCorrection;
241 if (predictedLastEventTime >= now) {
242 // Make sure that the last event time does not exceed the current time.
243 // If it would, then back the last event time by a period.
244 listener.mLastEventTime = predictedLastEventTime - mPeriod;
245 } else {
246 listener.mLastEventTime = predictedLastEventTime;
Alec Mouri81835982019-02-27 13:40:44 -0800247 }
248 } else {
249 listener.mLastEventTime = now + mPhase - mWakeupLatency;
250 }
Jamie Gennis629b9872013-10-29 13:36:12 -0700251
Alec Mouri7355eb22019-03-05 14:19:10 -0800252 if (lastCallbackTime <= 0) {
253 // If there is no prior callback time, try to infer one based on the
254 // logical last event time.
255 listener.mLastCallbackTime = listener.mLastEventTime + mWakeupLatency;
256 } else {
257 listener.mLastCallbackTime = lastCallbackTime;
258 }
259
Alec Mouri1f534ab2019-05-21 00:51:01 -0700260 if (!mModelLocked && listener.mLastEventTime > mReferenceTime) {
261 listener.mHasFired = true;
262 }
263
Ana Krulec9a52b192018-07-12 18:18:47 -0400264 mEventListeners.push_back(listener);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700265
266 mCond.signal();
267
268 return NO_ERROR;
269 }
270
Alec Mouri7355eb22019-03-05 14:19:10 -0800271 status_t removeEventListener(DispSync::Callback* callback, nsecs_t* outLastCallback) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700272 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700273 Mutex::Autolock lock(mMutex);
274
Ana Krulec9a52b192018-07-12 18:18:47 -0400275 for (std::vector<EventListener>::iterator it = mEventListeners.begin();
276 it != mEventListeners.end(); ++it) {
277 if (it->mCallback == callback) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800278 *outLastCallback = it->mLastCallbackTime;
Ana Krulec9a52b192018-07-12 18:18:47 -0400279 mEventListeners.erase(it);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700280 mCond.signal();
281 return NO_ERROR;
282 }
283 }
284
285 return BAD_VALUE;
286 }
287
Dan Stoza84d619e2018-03-28 17:07:36 -0700288 status_t changePhaseOffset(DispSync::Callback* callback, nsecs_t phase) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700289 if (mTraceDetailedInfo) ATRACE_CALL();
Dan Stoza84d619e2018-03-28 17:07:36 -0700290 Mutex::Autolock lock(mMutex);
291
Ana Krulec9a52b192018-07-12 18:18:47 -0400292 for (auto& eventListener : mEventListeners) {
293 if (eventListener.mCallback == callback) {
294 const nsecs_t oldPhase = eventListener.mPhase;
295 eventListener.mPhase = phase;
Dan Stoza84d619e2018-03-28 17:07:36 -0700296
297 // Pretend that the last time this event was handled at the same frame but with the
298 // new offset to allow for a seamless offset change without double-firing or
299 // skipping.
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200300 nsecs_t diff = oldPhase - phase;
301 if (diff > mPeriod / 2) {
302 diff -= mPeriod;
303 } else if (diff < -mPeriod / 2) {
304 diff += mPeriod;
305 }
Ana Krulec9a52b192018-07-12 18:18:47 -0400306 eventListener.mLastEventTime -= diff;
Dan Stoza84d619e2018-03-28 17:07:36 -0700307 mCond.signal();
308 return NO_ERROR;
309 }
310 }
Dan Stoza84d619e2018-03-28 17:07:36 -0700311 return BAD_VALUE;
312 }
313
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700314private:
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700315 struct EventListener {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000316 const char* mName;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700317 nsecs_t mPhase;
318 nsecs_t mLastEventTime;
Alec Mouri7355eb22019-03-05 14:19:10 -0800319 nsecs_t mLastCallbackTime;
Lloyd Piquee83f9312018-02-01 12:53:17 -0800320 DispSync::Callback* mCallback;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700321 bool mHasFired = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700322 };
323
324 struct CallbackInvocation {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800325 DispSync::Callback* mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700326 nsecs_t mEventTime;
327 };
328
329 nsecs_t computeNextEventTimeLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700330 if (mTraceDetailedInfo) ATRACE_CALL();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000331 ALOGV("[%s] computeNextEventTimeLocked", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700332 nsecs_t nextEventTime = INT64_MAX;
333 for (size_t i = 0; i < mEventListeners.size(); i++) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800334 nsecs_t t = computeListenerNextEventTimeLocked(mEventListeners[i], now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700335
336 if (t < nextEventTime) {
337 nextEventTime = t;
338 }
339 }
340
Tim Murray4a4e4a22016-04-19 16:29:23 +0000341 ALOGV("[%s] nextEventTime = %" PRId64, mName, ns2us(nextEventTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700342 return nextEventTime;
343 }
344
Alec Mouri7355eb22019-03-05 14:19:10 -0800345 // Sanity check that the duration is close enough in length to a period without
346 // falling into double-rate vsyncs.
Alec Mouridf3d2e12019-05-02 17:58:46 +0000347 bool isCloseToPeriod(nsecs_t duration) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800348 // Ratio of 3/5 is arbitrary, but it must be greater than 1/2.
349 return duration < (3 * mPeriod) / 5;
350 }
351
Ana Krulec9a52b192018-07-12 18:18:47 -0400352 std::vector<CallbackInvocation> gatherCallbackInvocationsLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700353 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800354 ALOGV("[%s] gatherCallbackInvocationsLocked @ %" PRId64, mName, ns2us(now));
Tim Murray4a4e4a22016-04-19 16:29:23 +0000355
Ana Krulec9a52b192018-07-12 18:18:47 -0400356 std::vector<CallbackInvocation> callbackInvocations;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000357 nsecs_t onePeriodAgo = now - mPeriod;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700358
Ana Krulec9a52b192018-07-12 18:18:47 -0400359 for (auto& eventListener : mEventListeners) {
360 nsecs_t t = computeListenerNextEventTimeLocked(eventListener, onePeriodAgo);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700361
Jamie Gennis0d5c60e2013-10-09 17:49:37 -0700362 if (t < now) {
Alec Mouridf3d2e12019-05-02 17:58:46 +0000363 if (isCloseToPeriod(now - eventListener.mLastCallbackTime)) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800364 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800365 ALOGV("[%s] [%s] Skipping event due to model error", mName,
366 eventListener.mName);
367 continue;
368 }
Alec Mouri016b8dd2019-04-24 15:16:05 -0700369 if (eventListener.mHasFired && !mModelLocked) {
370 eventListener.mLastEventTime = t;
371 ALOGV("[%s] [%s] Skipping event due to already firing", mName,
372 eventListener.mName);
373 continue;
374 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700375 CallbackInvocation ci;
Ana Krulec9a52b192018-07-12 18:18:47 -0400376 ci.mCallback = eventListener.mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700377 ci.mEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800378 ALOGV("[%s] [%s] Preparing to fire, latency: %" PRId64, mName, eventListener.mName,
379 t - eventListener.mLastEventTime);
Ana Krulec9a52b192018-07-12 18:18:47 -0400380 callbackInvocations.push_back(ci);
381 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800382 eventListener.mLastCallbackTime = now;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700383 eventListener.mHasFired = true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700384 }
385 }
386
387 return callbackInvocations;
388 }
389
Lloyd Pique78ce4182018-01-31 16:39:51 -0800390 nsecs_t computeListenerNextEventTimeLocked(const EventListener& listener, nsecs_t baseTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700391 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800392 ALOGV("[%s] [%s] computeListenerNextEventTimeLocked(%" PRId64 ")", mName, listener.mName,
393 ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700394
Tim Murray4a4e4a22016-04-19 16:29:23 +0000395 nsecs_t lastEventTime = listener.mLastEventTime + mWakeupLatency;
396 ALOGV("[%s] lastEventTime: %" PRId64, mName, ns2us(lastEventTime));
397 if (baseTime < lastEventTime) {
398 baseTime = lastEventTime;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800399 ALOGV("[%s] Clamping baseTime to lastEventTime -> %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700400 }
401
Tim Murray4a4e4a22016-04-19 16:29:23 +0000402 baseTime -= mReferenceTime;
403 ALOGV("[%s] Relative baseTime = %" PRId64, mName, ns2us(baseTime));
404 nsecs_t phase = mPhase + listener.mPhase;
405 ALOGV("[%s] Phase = %" PRId64, mName, ns2us(phase));
406 baseTime -= phase;
407 ALOGV("[%s] baseTime - phase = %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700408
Tim Murray4a4e4a22016-04-19 16:29:23 +0000409 // If our previous time is before the reference (because the reference
410 // has since been updated), the division by mPeriod will truncate
411 // towards zero instead of computing the floor. Since in all cases
412 // before the reference we want the next time to be effectively now, we
413 // set baseTime to -mPeriod so that numPeriods will be -1.
414 // When we add 1 and the phase, we will be at the correct event time for
415 // this period.
416 if (baseTime < 0) {
417 ALOGV("[%s] Correcting negative baseTime", mName);
418 baseTime = -mPeriod;
419 }
420
421 nsecs_t numPeriods = baseTime / mPeriod;
422 ALOGV("[%s] numPeriods = %" PRId64, mName, numPeriods);
423 nsecs_t t = (numPeriods + 1) * mPeriod + phase;
424 ALOGV("[%s] t = %" PRId64, mName, ns2us(t));
425 t += mReferenceTime;
426 ALOGV("[%s] Absolute t = %" PRId64, mName, ns2us(t));
427
428 // Check that it's been slightly more than half a period since the last
429 // event so that we don't accidentally fall into double-rate vsyncs
Alec Mouridf3d2e12019-05-02 17:58:46 +0000430 if (isCloseToPeriod(t - listener.mLastEventTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 t += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000432 ALOGV("[%s] Modifying t -> %" PRId64, mName, ns2us(t));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700433 }
434
Tim Murray4a4e4a22016-04-19 16:29:23 +0000435 t -= mWakeupLatency;
436 ALOGV("[%s] Corrected for wakeup latency -> %" PRId64, mName, ns2us(t));
437
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 return t;
439 }
440
Ana Krulec9a52b192018-07-12 18:18:47 -0400441 void fireCallbackInvocations(const std::vector<CallbackInvocation>& callbacks) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700442 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443 for (size_t i = 0; i < callbacks.size(); i++) {
444 callbacks[i].mCallback->onDispSyncEvent(callbacks[i].mEventTime);
445 }
446 }
447
Tim Murray4a4e4a22016-04-19 16:29:23 +0000448 const char* const mName;
449
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700450 bool mStop;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700451 bool mModelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452
453 nsecs_t mPeriod;
454 nsecs_t mPhase;
Haixia Shi676b1f62015-10-28 16:19:01 -0700455 nsecs_t mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700456 nsecs_t mWakeupLatency;
457
Tim Murray4a4e4a22016-04-19 16:29:23 +0000458 int64_t mFrameNumber;
459
Ana Krulec9a52b192018-07-12 18:18:47 -0400460 std::vector<EventListener> mEventListeners;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461
462 Mutex mMutex;
463 Condition mCond;
Ana Krulec064a82f2018-09-11 16:03:03 -0700464
465 // Flag to turn on logging in systrace.
466 const bool mTraceDetailedInfo;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467};
468
Tim Murray4a4e4a22016-04-19 16:29:23 +0000469#undef LOG_TAG
470#define LOG_TAG "DispSync"
471
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700472class ZeroPhaseTracer : public DispSync::Callback {
473public:
474 ZeroPhaseTracer() : mParity(false) {}
475
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700476 virtual void onDispSyncEvent(nsecs_t /*when*/) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700477 mParity = !mParity;
478 ATRACE_INT("ZERO_PHASE_VSYNC", mParity ? 1 : 0);
479 }
480
481private:
482 bool mParity;
483};
484
Ana Krulec064a82f2018-09-11 16:03:03 -0700485DispSync::DispSync(const char* name) : mName(name), mRefreshSkipCount(0) {
486 // This flag offers the ability to turn on systrace logging from the shell.
487 char value[PROPERTY_VALUE_MAX];
488 property_get("debug.sf.dispsync_trace_detailed_info", value, "0");
489 mTraceDetailedInfo = atoi(value);
490 mThread = new DispSyncThread(name, mTraceDetailedInfo);
491}
Andy McFadden645b1f72014-06-10 14:43:32 -0700492
Ady Abraham50c202a2019-03-14 11:44:38 -0700493DispSync::~DispSync() {
494 mThread->stop();
495 mThread->requestExitAndWait();
496}
Saurabh Shahf4174532017-07-13 10:45:07 -0700497
498void DispSync::init(bool hasSyncFramework, int64_t dispSyncPresentTimeOffset) {
499 mIgnorePresentFences = !hasSyncFramework;
500 mPresentTimeOffset = dispSyncPresentTimeOffset;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 mThread->run("DispSync", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
Saurabh Shahf4174532017-07-13 10:45:07 -0700502
Tim Murrayacff43d2016-07-29 13:57:24 -0700503 // set DispSync to SCHED_FIFO to minimize jitter
504 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700505 param.sched_priority = 2;
Tim Murrayacff43d2016-07-29 13:57:24 -0700506 if (sched_setscheduler(mThread->getTid(), SCHED_FIFO, &param) != 0) {
507 ALOGE("Couldn't set SCHED_FIFO for DispSyncThread");
508 }
509
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510 reset();
511 beginResync();
512
Ana Krulec064a82f2018-09-11 16:03:03 -0700513 if (mTraceDetailedInfo && kEnableZeroPhaseTracer) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700514 mZeroPhaseTracer = std::make_unique<ZeroPhaseTracer>();
Alec Mouri7355eb22019-03-05 14:19:10 -0800515 addEventListener("ZeroPhaseTracer", 0, mZeroPhaseTracer.get(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 }
517}
518
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700519void DispSync::reset() {
520 Mutex::Autolock lock(mMutex);
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700521 resetLocked();
522}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700524void DispSync::resetLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700525 mPhase = 0;
Alec Mouri75b0b622019-03-12 18:56:00 +0000526 const size_t lastSampleIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
527 // Keep the most recent sample, when we resync to hardware we'll overwrite this
528 // with a more accurate signal
529 if (mResyncSamples[lastSampleIdx] != 0) {
530 mReferenceTime = mResyncSamples[lastSampleIdx];
531 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700532 mModelUpdated = false;
Alec Mouri75b0b622019-03-12 18:56:00 +0000533 for (size_t i = 0; i < MAX_RESYNC_SAMPLES; i++) {
534 mResyncSamples[i] = 0;
535 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536 mNumResyncSamples = 0;
537 mFirstResyncSample = 0;
538 mNumResyncSamplesSincePresent = 0;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700539 mThread->unlockModel();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540 resetErrorLocked();
541}
542
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700543bool DispSync::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544 Mutex::Autolock lock(mMutex);
545
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700546 if (mIgnorePresentFences) {
547 return true;
548 }
549
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700550 mPresentFences[mPresentSampleOffset] = fenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700551 mPresentSampleOffset = (mPresentSampleOffset + 1) % NUM_PRESENT_SAMPLES;
552 mNumResyncSamplesSincePresent = 0;
553
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700554 updateErrorLocked();
555
Haixia Shi676b1f62015-10-28 16:19:01 -0700556 return !mModelUpdated || mError > kErrorThreshold;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700557}
558
559void DispSync::beginResync() {
560 Mutex::Autolock lock(mMutex);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000561 ALOGV("[%s] beginResync", mName);
Alec Mouri016b8dd2019-04-24 15:16:05 -0700562 mThread->unlockModel();
Haixia Shi676b1f62015-10-28 16:19:01 -0700563 mModelUpdated = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700564 mNumResyncSamples = 0;
565}
566
Alec Mouri754c98a2019-03-18 18:53:42 -0700567bool DispSync::addResyncSample(nsecs_t timestamp, bool* periodChanged) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568 Mutex::Autolock lock(mMutex);
569
Tim Murray4a4e4a22016-04-19 16:29:23 +0000570 ALOGV("[%s] addResyncSample(%" PRId64 ")", mName, ns2us(timestamp));
571
Alec Mouri754c98a2019-03-18 18:53:42 -0700572 *periodChanged = false;
573 const size_t idx = (mFirstResyncSample + mNumResyncSamples) % MAX_RESYNC_SAMPLES;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574 mResyncSamples[idx] = timestamp;
Haixia Shi664339a2015-10-28 13:22:22 -0700575 if (mNumResyncSamples == 0) {
Haixia Shi676b1f62015-10-28 16:19:01 -0700576 mPhase = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000577 ALOGV("[%s] First resync sample: mPeriod = %" PRId64 ", mPhase = 0, "
Lloyd Pique78ce4182018-01-31 16:39:51 -0800578 "mReferenceTime = %" PRId64,
Alec Mouri754c98a2019-03-18 18:53:42 -0700579 mName, ns2us(mPeriod), ns2us(timestamp));
580 } else if (mPendingPeriod > 0) {
581 // mNumResyncSamples > 0, so priorIdx won't overflow
582 const size_t priorIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
583 const nsecs_t lastTimestamp = mResyncSamples[priorIdx];
584
585 const nsecs_t observedVsync = std::abs(timestamp - lastTimestamp);
586 if (std::abs(observedVsync - mPendingPeriod) < std::abs(observedVsync - mPeriod)) {
587 // Observed vsync is closer to the pending period, so reset the
588 // model and flush the pending period.
589 resetLocked();
590 mPeriod = mPendingPeriod;
591 mPendingPeriod = 0;
592 if (mTraceDetailedInfo) {
593 ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
594 }
595 *periodChanged = true;
596 }
Haixia Shi664339a2015-10-28 13:22:22 -0700597 }
Alec Mouri754c98a2019-03-18 18:53:42 -0700598 // Always update the reference time with the most recent timestamp.
599 mReferenceTime = timestamp;
600 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700601
602 if (mNumResyncSamples < MAX_RESYNC_SAMPLES) {
603 mNumResyncSamples++;
604 } else {
605 mFirstResyncSample = (mFirstResyncSample + 1) % MAX_RESYNC_SAMPLES;
606 }
607
608 updateModelLocked();
609
610 if (mNumResyncSamplesSincePresent++ > MAX_RESYNC_SAMPLES_WITHOUT_PRESENT) {
611 resetErrorLocked();
612 }
613
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800614 if (mIgnorePresentFences) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700615 // If we're ignoring the present fences we have no way to know whether
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700616 // or not we're synchronized with the HW vsyncs, so we just request
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700617 // that the HW vsync events be turned on.
618 return true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700619 }
620
Tim Murray4a4e4a22016-04-19 16:29:23 +0000621 // Check against kErrorThreshold / 2 to add some hysteresis before having to
622 // resync again
Alec Mouri754c98a2019-03-18 18:53:42 -0700623 bool modelLocked = mModelUpdated && mError < (kErrorThreshold / 2) && mPendingPeriod == 0;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800624 ALOGV("[%s] addResyncSample returning %s", mName, modelLocked ? "locked" : "unlocked");
Alec Mouri016b8dd2019-04-24 15:16:05 -0700625 if (modelLocked) {
626 mThread->lockModel();
627 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000628 return !modelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700629}
630
Alec Mouri016b8dd2019-04-24 15:16:05 -0700631void DispSync::endResync() {
632 mThread->lockModel();
633}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700634
Alec Mouri7355eb22019-03-05 14:19:10 -0800635status_t DispSync::addEventListener(const char* name, nsecs_t phase, Callback* callback,
636 nsecs_t lastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700637 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800638 return mThread->addEventListener(name, phase, callback, lastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700639}
640
Andy McFadden645b1f72014-06-10 14:43:32 -0700641void DispSync::setRefreshSkipCount(int count) {
642 Mutex::Autolock lock(mMutex);
643 ALOGD("setRefreshSkipCount(%d)", count);
644 mRefreshSkipCount = count;
645 updateModelLocked();
Ruchi Kandoif52b3c82014-04-24 16:42:35 -0700646}
647
Alec Mouri7355eb22019-03-05 14:19:10 -0800648status_t DispSync::removeEventListener(Callback* callback, nsecs_t* outLastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700649 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800650 return mThread->removeEventListener(callback, outLastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700651}
652
Dan Stoza84d619e2018-03-28 17:07:36 -0700653status_t DispSync::changePhaseOffset(Callback* callback, nsecs_t phase) {
654 Mutex::Autolock lock(mMutex);
655 return mThread->changePhaseOffset(callback, phase);
656}
657
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700658void DispSync::setPeriod(nsecs_t period) {
659 Mutex::Autolock lock(mMutex);
Alec Mouri754c98a2019-03-18 18:53:42 -0700660 if (mTraceDetailedInfo) {
661 ATRACE_INT("DispSync:PendingPeriod", period);
662 }
663 mPendingPeriod = period;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700664}
665
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700666nsecs_t DispSync::getPeriod() {
667 // lock mutex as mPeriod changes multiple times in updateModelLocked
668 Mutex::Autolock lock(mMutex);
669 return mPeriod;
670}
671
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700672void DispSync::updateModelLocked() {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000673 ALOGV("[%s] updateModelLocked %zu", mName, mNumResyncSamples);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700674 if (mNumResyncSamples >= MIN_RESYNC_SAMPLES_FOR_UPDATE) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000675 ALOGV("[%s] Computing...", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700676 nsecs_t durationSum = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000677 nsecs_t minDuration = INT64_MAX;
678 nsecs_t maxDuration = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700679 for (size_t i = 1; i < mNumResyncSamples; i++) {
680 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
681 size_t prev = (idx + MAX_RESYNC_SAMPLES - 1) % MAX_RESYNC_SAMPLES;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000682 nsecs_t duration = mResyncSamples[idx] - mResyncSamples[prev];
683 durationSum += duration;
684 minDuration = min(minDuration, duration);
685 maxDuration = max(maxDuration, duration);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700686 }
687
Tim Murray4a4e4a22016-04-19 16:29:23 +0000688 // Exclude the min and max from the average
689 durationSum -= minDuration + maxDuration;
David Sodman1afa8b02018-10-15 11:20:48 -0700690 mPeriod = durationSum / (mNumResyncSamples - 3);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000691
692 ALOGV("[%s] mPeriod = %" PRId64, mName, ns2us(mPeriod));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700693
694 double sampleAvgX = 0;
695 double sampleAvgY = 0;
696 double scale = 2.0 * M_PI / double(mPeriod);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000697 // Intentionally skip the first sample
698 for (size_t i = 1; i < mNumResyncSamples; i++) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700699 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
Haixia Shi676b1f62015-10-28 16:19:01 -0700700 nsecs_t sample = mResyncSamples[idx] - mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700701 double samplePhase = double(sample % mPeriod) * scale;
702 sampleAvgX += cos(samplePhase);
703 sampleAvgY += sin(samplePhase);
704 }
705
Tim Murray4a4e4a22016-04-19 16:29:23 +0000706 sampleAvgX /= double(mNumResyncSamples - 1);
707 sampleAvgY /= double(mNumResyncSamples - 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700708
709 mPhase = nsecs_t(atan2(sampleAvgY, sampleAvgX) / scale);
710
Tim Murray4a4e4a22016-04-19 16:29:23 +0000711 ALOGV("[%s] mPhase = %" PRId64, mName, ns2us(mPhase));
712
713 if (mPhase < -(mPeriod / 2)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700714 mPhase += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000715 ALOGV("[%s] Adjusting mPhase -> %" PRId64, mName, ns2us(mPhase));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700716 }
717
Andy McFadden645b1f72014-06-10 14:43:32 -0700718 // Artificially inflate the period if requested.
719 mPeriod += mPeriod * mRefreshSkipCount;
720
Haixia Shi676b1f62015-10-28 16:19:01 -0700721 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
722 mModelUpdated = true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700723 }
724}
725
726void DispSync::updateErrorLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700727 if (!mModelUpdated) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700728 return;
729 }
730
Andy McFadden645b1f72014-06-10 14:43:32 -0700731 // Need to compare present fences against the un-adjusted refresh period,
732 // since they might arrive between two events.
733 nsecs_t period = mPeriod / (1 + mRefreshSkipCount);
734
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700735 int numErrSamples = 0;
736 nsecs_t sqErrSum = 0;
737
738 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700739 // Only check for the cached value of signal time to avoid unecessary
740 // syscalls. It is the responsibility of the DispSync owner to
741 // call getSignalTime() periodically so the cache is updated when the
742 // fence signals.
743 nsecs_t time = mPresentFences[i]->getCachedSignalTime();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800744 if (time == Fence::SIGNAL_TIME_PENDING || time == Fence::SIGNAL_TIME_INVALID) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700745 continue;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700746 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700747
748 nsecs_t sample = time - mReferenceTime;
749 if (sample <= mPhase) {
750 continue;
751 }
752
753 nsecs_t sampleErr = (sample - mPhase) % period;
754 if (sampleErr > period / 2) {
755 sampleErr -= period;
756 }
757 sqErrSum += sampleErr * sampleErr;
758 numErrSamples++;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700759 }
760
761 if (numErrSamples > 0) {
762 mError = sqErrSum / numErrSamples;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700763 mZeroErrSamplesCount = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700764 } else {
765 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700766 // Use mod ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT to avoid log spam.
767 mZeroErrSamplesCount++;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800768 ALOGE_IF((mZeroErrSamplesCount % ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT) == 0,
769 "No present times for model error.");
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700770 }
771
Ana Krulec064a82f2018-09-11 16:03:03 -0700772 if (mTraceDetailedInfo) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700773 ATRACE_INT64("DispSync:Error", mError);
774 }
775}
776
777void DispSync::resetErrorLocked() {
778 mPresentSampleOffset = 0;
779 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700780 mZeroErrSamplesCount = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700781 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700782 mPresentFences[i] = FenceTime::NO_FENCE;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700783 }
784}
785
Andy McFadden41d67d72014-04-25 16:58:34 -0700786nsecs_t DispSync::computeNextRefresh(int periodOffset) const {
Andy McFadden150ecd82014-05-08 14:56:50 -0700787 Mutex::Autolock lock(mMutex);
Andy McFadden41d67d72014-04-25 16:58:34 -0700788 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Haixia Shi676b1f62015-10-28 16:19:01 -0700789 nsecs_t phase = mReferenceTime + mPhase;
Marissa Wall17b4e452018-12-26 16:32:34 -0800790 if (mPeriod == 0) {
791 return 0;
792 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700793 return (((now - phase) / mPeriod) + periodOffset + 1) * mPeriod + phase;
Andy McFadden41d67d72014-04-25 16:58:34 -0700794}
795
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700796void DispSync::setIgnorePresentFences(bool ignore) {
797 Mutex::Autolock lock(mMutex);
798 if (mIgnorePresentFences != ignore) {
799 mIgnorePresentFences = ignore;
800 resetLocked();
801 }
802}
803
Yiwei Zhang5434a782018-12-05 18:06:32 -0800804void DispSync::dump(std::string& result) const {
Andy McFaddenc751e922014-05-08 14:53:26 -0700805 Mutex::Autolock lock(mMutex);
Yiwei Zhang5434a782018-12-05 18:06:32 -0800806 StringAppendF(&result, "present fences are %s\n", mIgnorePresentFences ? "ignored" : "used");
807 StringAppendF(&result, "mPeriod: %" PRId64 " ns (%.3f fps; skipCount=%d)\n", mPeriod,
808 1000000000.0 / mPeriod, mRefreshSkipCount);
809 StringAppendF(&result, "mPhase: %" PRId64 " ns\n", mPhase);
810 StringAppendF(&result, "mError: %" PRId64 " ns (sqrt=%.1f)\n", mError, sqrt(mError));
811 StringAppendF(&result, "mNumResyncSamplesSincePresent: %d (limit %d)\n",
812 mNumResyncSamplesSincePresent, MAX_RESYNC_SAMPLES_WITHOUT_PRESENT);
813 StringAppendF(&result, "mNumResyncSamples: %zd (max %d)\n", mNumResyncSamples,
814 MAX_RESYNC_SAMPLES);
Andy McFaddenc751e922014-05-08 14:53:26 -0700815
Yiwei Zhang5434a782018-12-05 18:06:32 -0800816 result.append("mResyncSamples:\n");
Andy McFaddenc751e922014-05-08 14:53:26 -0700817 nsecs_t previous = -1;
818 for (size_t i = 0; i < mNumResyncSamples; i++) {
819 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
820 nsecs_t sampleTime = mResyncSamples[idx];
821 if (i == 0) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800822 StringAppendF(&result, " %" PRId64 "\n", sampleTime);
Andy McFaddenc751e922014-05-08 14:53:26 -0700823 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800824 StringAppendF(&result, " %" PRId64 " (+%" PRId64 ")\n", sampleTime,
825 sampleTime - previous);
Andy McFaddenc751e922014-05-08 14:53:26 -0700826 }
827 previous = sampleTime;
828 }
829
Yiwei Zhang5434a782018-12-05 18:06:32 -0800830 StringAppendF(&result, "mPresentFences [%d]:\n", NUM_PRESENT_SAMPLES);
Andy McFadden5167ec62014-05-22 13:08:43 -0700831 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700832 previous = Fence::SIGNAL_TIME_INVALID;
Andy McFaddenc751e922014-05-08 14:53:26 -0700833 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
834 size_t idx = (i + mPresentSampleOffset) % NUM_PRESENT_SAMPLES;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700835 nsecs_t presentTime = mPresentFences[idx]->getSignalTime();
836 if (presentTime == Fence::SIGNAL_TIME_PENDING) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800837 StringAppendF(&result, " [unsignaled fence]\n");
Lloyd Pique78ce4182018-01-31 16:39:51 -0800838 } else if (presentTime == Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800839 StringAppendF(&result, " [invalid fence]\n");
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700840 } else if (previous == Fence::SIGNAL_TIME_PENDING ||
Lloyd Pique78ce4182018-01-31 16:39:51 -0800841 previous == Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800842 StringAppendF(&result, " %" PRId64 " (%.3f ms ago)\n", presentTime,
843 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700844 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800845 StringAppendF(&result, " %" PRId64 " (+%" PRId64 " / %.3f) (%.3f ms ago)\n",
846 presentTime, presentTime - previous,
847 (presentTime - previous) / (double)mPeriod,
848 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700849 }
850 previous = presentTime;
851 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700852
Yiwei Zhang5434a782018-12-05 18:06:32 -0800853 StringAppendF(&result, "current monotonic time: %" PRId64 "\n", now);
Andy McFaddenc751e922014-05-08 14:53:26 -0700854}
855
Ana Krulec010d2192018-10-08 06:29:54 -0700856nsecs_t DispSync::expectedPresentTime() {
857 // The HWC doesn't currently have a way to report additional latency.
858 // Assume that whatever we submit now will appear right after the flip.
859 // For a smart panel this might be 1. This is expressed in frames,
860 // rather than time, because we expect to have a constant frame delay
861 // regardless of the refresh rate.
862 const uint32_t hwcLatency = 0;
863
864 // Ask DispSync when the next refresh will be (CLOCK_MONOTONIC).
Ana Krulec757f63a2019-01-25 10:46:18 -0800865 return computeNextRefresh(hwcLatency);
Ana Krulec010d2192018-10-08 06:29:54 -0700866}
867
Lloyd Pique41be5d22018-06-21 13:11:48 -0700868} // namespace impl
869
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700870} // namespace android