blob: e59d459242125f78e697676a469b3503a7052115 [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 Mouric3a482d2019-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 Mouric3a482d2019-05-21 00:51:01 -070093 if (!mModelLocked && referenceTimeChanged) {
94 for (auto& eventListener : mEventListeners) {
Alec Mouric3a482d2019-05-21 00:51:01 -070095 eventListener.mLastEventTime =
96 mReferenceTime - mPeriod + mPhase + eventListener.mPhase;
97 }
98 }
Alec Mourif5fe85c2019-02-22 13:40:36 -080099 if (mTraceDetailedInfo) {
100 ATRACE_INT64("DispSync:Period", mPeriod);
101 ATRACE_INT64("DispSync:Phase", mPhase + mPeriod / 2);
102 ATRACE_INT64("DispSync:Reference Time", mReferenceTime);
103 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000104 ALOGV("[%s] updateModel: mPeriod = %" PRId64 ", mPhase = %" PRId64
Lloyd Pique78ce4182018-01-31 16:39:51 -0800105 " mReferenceTime = %" PRId64,
106 mName, ns2us(mPeriod), ns2us(mPhase), ns2us(mReferenceTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107 mCond.signal();
108 }
109
110 void stop() {
Ana Krulec064a82f2018-09-11 16:03:03 -0700111 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700112 Mutex::Autolock lock(mMutex);
113 mStop = true;
114 mCond.signal();
115 }
116
Alec Mouri016b8dd2019-04-24 15:16:05 -0700117 void lockModel() {
118 Mutex::Autolock lock(mMutex);
119 mModelLocked = true;
Alec Mourif8e689c2019-05-20 18:32:22 -0700120 ATRACE_INT("DispSync:ModelLocked", mModelLocked);
Alec Mouri016b8dd2019-04-24 15:16:05 -0700121 }
122
123 void unlockModel() {
124 Mutex::Autolock lock(mMutex);
125 mModelLocked = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700126 ATRACE_INT("DispSync:ModelLocked", mModelLocked);
Alec Mouri016b8dd2019-04-24 15:16:05 -0700127 }
128
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700129 virtual bool threadLoop() {
130 status_t err;
131 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700132
133 while (true) {
Ana Krulec9a52b192018-07-12 18:18:47 -0400134 std::vector<CallbackInvocation> callbackInvocations;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700135
136 nsecs_t targetTime = 0;
137
138 { // Scope for lock
139 Mutex::Autolock lock(mMutex);
140
Ana Krulec064a82f2018-09-11 16:03:03 -0700141 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000142 ATRACE_INT64("DispSync:Frame", mFrameNumber);
143 }
144 ALOGV("[%s] Frame %" PRId64, mName, mFrameNumber);
145 ++mFrameNumber;
146
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700147 if (mStop) {
148 return false;
149 }
150
151 if (mPeriod == 0) {
152 err = mCond.wait(mMutex);
153 if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800154 ALOGE("error waiting for new events: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700155 return false;
156 }
157 continue;
158 }
159
Dan Stoza8f8374d2016-04-19 10:03:46 -0700160 targetTime = computeNextEventTimeLocked(now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700161
162 bool isWakeup = false;
163
164 if (now < targetTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700165 if (mTraceDetailedInfo) ATRACE_NAME("DispSync waiting");
Dan Stoza8f8374d2016-04-19 10:03:46 -0700166
167 if (targetTime == INT64_MAX) {
168 ALOGV("[%s] Waiting forever", mName);
169 err = mCond.wait(mMutex);
170 } else {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800171 ALOGV("[%s] Waiting until %" PRId64, mName, ns2us(targetTime));
Dan Stoza8f8374d2016-04-19 10:03:46 -0700172 err = mCond.waitRelative(mMutex, targetTime - now);
173 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700174
175 if (err == TIMED_OUT) {
176 isWakeup = true;
177 } else if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800178 ALOGE("error waiting for next event: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700179 return false;
180 }
181 }
182
183 now = systemTime(SYSTEM_TIME_MONOTONIC);
184
Tim Murray4a4e4a22016-04-19 16:29:23 +0000185 // Don't correct by more than 1.5 ms
186 static const nsecs_t kMaxWakeupLatency = us2ns(1500);
187
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700188 if (isWakeup) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800189 mWakeupLatency = ((mWakeupLatency * 63) + (now - targetTime)) / 64;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000190 mWakeupLatency = min(mWakeupLatency, kMaxWakeupLatency);
Ana Krulec064a82f2018-09-11 16:03:03 -0700191 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000192 ATRACE_INT64("DispSync:WakeupLat", now - targetTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700193 ATRACE_INT64("DispSync:AvgWakeupLat", mWakeupLatency);
194 }
195 }
196
197 callbackInvocations = gatherCallbackInvocationsLocked(now);
198 }
199
200 if (callbackInvocations.size() > 0) {
Andy McFadden645b1f72014-06-10 14:43:32 -0700201 fireCallbackInvocations(callbackInvocations);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700202 }
203 }
204
205 return false;
206 }
207
Alec Mouri7355eb22019-03-05 14:19:10 -0800208 status_t addEventListener(const char* name, nsecs_t phase, DispSync::Callback* callback,
209 nsecs_t lastCallbackTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700210 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700211 Mutex::Autolock lock(mMutex);
212
213 for (size_t i = 0; i < mEventListeners.size(); i++) {
214 if (mEventListeners[i].mCallback == callback) {
215 return BAD_VALUE;
216 }
217 }
218
219 EventListener listener;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000220 listener.mName = name;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700221 listener.mPhase = phase;
222 listener.mCallback = callback;
Jamie Gennis629b9872013-10-29 13:36:12 -0700223
224 // We want to allow the firstmost future event to fire without
Alec Mouri81835982019-02-27 13:40:44 -0800225 // allowing any past events to fire. To do this extrapolate from
226 // mReferenceTime the most recent hardware vsync, and pin the
227 // last event time there.
228 const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
229 if (mPeriod != 0) {
230 const nsecs_t baseTime = now - mReferenceTime;
231 const nsecs_t numPeriodsSinceReference = baseTime / mPeriod;
232 const nsecs_t predictedReference = mReferenceTime + numPeriodsSinceReference * mPeriod;
Alec Mouridf3d2e12019-05-02 17:58:46 +0000233 const nsecs_t phaseCorrection = mPhase + listener.mPhase;
234 const nsecs_t predictedLastEventTime = predictedReference + phaseCorrection;
235 if (predictedLastEventTime >= now) {
236 // Make sure that the last event time does not exceed the current time.
237 // If it would, then back the last event time by a period.
238 listener.mLastEventTime = predictedLastEventTime - mPeriod;
239 } else {
240 listener.mLastEventTime = predictedLastEventTime;
Alec Mouri81835982019-02-27 13:40:44 -0800241 }
242 } else {
243 listener.mLastEventTime = now + mPhase - mWakeupLatency;
244 }
Jamie Gennis629b9872013-10-29 13:36:12 -0700245
Alec Mouri7355eb22019-03-05 14:19:10 -0800246 if (lastCallbackTime <= 0) {
247 // If there is no prior callback time, try to infer one based on the
248 // logical last event time.
249 listener.mLastCallbackTime = listener.mLastEventTime + mWakeupLatency;
250 } else {
251 listener.mLastCallbackTime = lastCallbackTime;
252 }
253
Ana Krulec9a52b192018-07-12 18:18:47 -0400254 mEventListeners.push_back(listener);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700255
256 mCond.signal();
257
258 return NO_ERROR;
259 }
260
Alec Mouri7355eb22019-03-05 14:19:10 -0800261 status_t removeEventListener(DispSync::Callback* callback, nsecs_t* outLastCallback) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700262 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700263 Mutex::Autolock lock(mMutex);
264
Ana Krulec9a52b192018-07-12 18:18:47 -0400265 for (std::vector<EventListener>::iterator it = mEventListeners.begin();
266 it != mEventListeners.end(); ++it) {
267 if (it->mCallback == callback) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800268 *outLastCallback = it->mLastCallbackTime;
Ana Krulec9a52b192018-07-12 18:18:47 -0400269 mEventListeners.erase(it);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700270 mCond.signal();
271 return NO_ERROR;
272 }
273 }
274
275 return BAD_VALUE;
276 }
277
Dan Stoza84d619e2018-03-28 17:07:36 -0700278 status_t changePhaseOffset(DispSync::Callback* callback, nsecs_t phase) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700279 if (mTraceDetailedInfo) ATRACE_CALL();
Dan Stoza84d619e2018-03-28 17:07:36 -0700280 Mutex::Autolock lock(mMutex);
281
Ana Krulec9a52b192018-07-12 18:18:47 -0400282 for (auto& eventListener : mEventListeners) {
283 if (eventListener.mCallback == callback) {
284 const nsecs_t oldPhase = eventListener.mPhase;
285 eventListener.mPhase = phase;
Dan Stoza84d619e2018-03-28 17:07:36 -0700286
287 // Pretend that the last time this event was handled at the same frame but with the
288 // new offset to allow for a seamless offset change without double-firing or
289 // skipping.
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200290 nsecs_t diff = oldPhase - phase;
291 if (diff > mPeriod / 2) {
292 diff -= mPeriod;
293 } else if (diff < -mPeriod / 2) {
294 diff += mPeriod;
295 }
Ady Abraham45e4e362019-06-07 18:20:51 -0700296
297 if (phase < 0 && oldPhase > 0) {
298 diff += mPeriod;
299 } else if (phase > 0 && oldPhase < 0) {
300 diff -= mPeriod;
301 }
Ana Krulec9a52b192018-07-12 18:18:47 -0400302 eventListener.mLastEventTime -= diff;
Ady Abraham45e4e362019-06-07 18:20:51 -0700303 eventListener.mLastCallbackTime -= diff;
Dan Stoza84d619e2018-03-28 17:07:36 -0700304 mCond.signal();
305 return NO_ERROR;
306 }
307 }
Dan Stoza84d619e2018-03-28 17:07:36 -0700308 return BAD_VALUE;
309 }
310
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700311private:
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700312 struct EventListener {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000313 const char* mName;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700314 nsecs_t mPhase;
315 nsecs_t mLastEventTime;
Alec Mouri7355eb22019-03-05 14:19:10 -0800316 nsecs_t mLastCallbackTime;
Lloyd Piquee83f9312018-02-01 12:53:17 -0800317 DispSync::Callback* mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700318 };
319
320 struct CallbackInvocation {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800321 DispSync::Callback* mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700322 nsecs_t mEventTime;
323 };
324
325 nsecs_t computeNextEventTimeLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700326 if (mTraceDetailedInfo) ATRACE_CALL();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000327 ALOGV("[%s] computeNextEventTimeLocked", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700328 nsecs_t nextEventTime = INT64_MAX;
329 for (size_t i = 0; i < mEventListeners.size(); i++) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800330 nsecs_t t = computeListenerNextEventTimeLocked(mEventListeners[i], now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700331
332 if (t < nextEventTime) {
333 nextEventTime = t;
334 }
335 }
336
Tim Murray4a4e4a22016-04-19 16:29:23 +0000337 ALOGV("[%s] nextEventTime = %" PRId64, mName, ns2us(nextEventTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700338 return nextEventTime;
339 }
340
Alec Mouri7355eb22019-03-05 14:19:10 -0800341 // Sanity check that the duration is close enough in length to a period without
342 // falling into double-rate vsyncs.
Alec Mouridf3d2e12019-05-02 17:58:46 +0000343 bool isCloseToPeriod(nsecs_t duration) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800344 // Ratio of 3/5 is arbitrary, but it must be greater than 1/2.
345 return duration < (3 * mPeriod) / 5;
346 }
347
Ana Krulec9a52b192018-07-12 18:18:47 -0400348 std::vector<CallbackInvocation> gatherCallbackInvocationsLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700349 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800350 ALOGV("[%s] gatherCallbackInvocationsLocked @ %" PRId64, mName, ns2us(now));
Tim Murray4a4e4a22016-04-19 16:29:23 +0000351
Ana Krulec9a52b192018-07-12 18:18:47 -0400352 std::vector<CallbackInvocation> callbackInvocations;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000353 nsecs_t onePeriodAgo = now - mPeriod;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700354
Ana Krulec9a52b192018-07-12 18:18:47 -0400355 for (auto& eventListener : mEventListeners) {
356 nsecs_t t = computeListenerNextEventTimeLocked(eventListener, onePeriodAgo);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700357
Jamie Gennis0d5c60e2013-10-09 17:49:37 -0700358 if (t < now) {
Alec Mouridf3d2e12019-05-02 17:58:46 +0000359 if (isCloseToPeriod(now - eventListener.mLastCallbackTime)) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800360 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800361 ALOGV("[%s] [%s] Skipping event due to model error", mName,
362 eventListener.mName);
363 continue;
364 }
Ady Abraham45e4e362019-06-07 18:20:51 -0700365
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700366 CallbackInvocation ci;
Ana Krulec9a52b192018-07-12 18:18:47 -0400367 ci.mCallback = eventListener.mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700368 ci.mEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800369 ALOGV("[%s] [%s] Preparing to fire, latency: %" PRId64, mName, eventListener.mName,
370 t - eventListener.mLastEventTime);
Ana Krulec9a52b192018-07-12 18:18:47 -0400371 callbackInvocations.push_back(ci);
372 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800373 eventListener.mLastCallbackTime = now;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700374 }
375 }
376
377 return callbackInvocations;
378 }
379
Lloyd Pique78ce4182018-01-31 16:39:51 -0800380 nsecs_t computeListenerNextEventTimeLocked(const EventListener& listener, nsecs_t baseTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700381 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800382 ALOGV("[%s] [%s] computeListenerNextEventTimeLocked(%" PRId64 ")", mName, listener.mName,
383 ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700384
Tim Murray4a4e4a22016-04-19 16:29:23 +0000385 nsecs_t lastEventTime = listener.mLastEventTime + mWakeupLatency;
386 ALOGV("[%s] lastEventTime: %" PRId64, mName, ns2us(lastEventTime));
387 if (baseTime < lastEventTime) {
388 baseTime = lastEventTime;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800389 ALOGV("[%s] Clamping baseTime to lastEventTime -> %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700390 }
391
Tim Murray4a4e4a22016-04-19 16:29:23 +0000392 baseTime -= mReferenceTime;
393 ALOGV("[%s] Relative baseTime = %" PRId64, mName, ns2us(baseTime));
394 nsecs_t phase = mPhase + listener.mPhase;
395 ALOGV("[%s] Phase = %" PRId64, mName, ns2us(phase));
396 baseTime -= phase;
397 ALOGV("[%s] baseTime - phase = %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700398
Tim Murray4a4e4a22016-04-19 16:29:23 +0000399 // If our previous time is before the reference (because the reference
400 // has since been updated), the division by mPeriod will truncate
401 // towards zero instead of computing the floor. Since in all cases
402 // before the reference we want the next time to be effectively now, we
403 // set baseTime to -mPeriod so that numPeriods will be -1.
404 // When we add 1 and the phase, we will be at the correct event time for
405 // this period.
406 if (baseTime < 0) {
407 ALOGV("[%s] Correcting negative baseTime", mName);
408 baseTime = -mPeriod;
409 }
410
411 nsecs_t numPeriods = baseTime / mPeriod;
412 ALOGV("[%s] numPeriods = %" PRId64, mName, numPeriods);
413 nsecs_t t = (numPeriods + 1) * mPeriod + phase;
414 ALOGV("[%s] t = %" PRId64, mName, ns2us(t));
415 t += mReferenceTime;
416 ALOGV("[%s] Absolute t = %" PRId64, mName, ns2us(t));
417
418 // Check that it's been slightly more than half a period since the last
419 // event so that we don't accidentally fall into double-rate vsyncs
Alec Mouridf3d2e12019-05-02 17:58:46 +0000420 if (isCloseToPeriod(t - listener.mLastEventTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 t += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000422 ALOGV("[%s] Modifying t -> %" PRId64, mName, ns2us(t));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423 }
424
Tim Murray4a4e4a22016-04-19 16:29:23 +0000425 t -= mWakeupLatency;
426 ALOGV("[%s] Corrected for wakeup latency -> %" PRId64, mName, ns2us(t));
427
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700428 return t;
429 }
430
Ana Krulec9a52b192018-07-12 18:18:47 -0400431 void fireCallbackInvocations(const std::vector<CallbackInvocation>& callbacks) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700432 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700433 for (size_t i = 0; i < callbacks.size(); i++) {
434 callbacks[i].mCallback->onDispSyncEvent(callbacks[i].mEventTime);
435 }
436 }
437
Tim Murray4a4e4a22016-04-19 16:29:23 +0000438 const char* const mName;
439
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700440 bool mStop;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700441 bool mModelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442
443 nsecs_t mPeriod;
444 nsecs_t mPhase;
Haixia Shi676b1f62015-10-28 16:19:01 -0700445 nsecs_t mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446 nsecs_t mWakeupLatency;
447
Tim Murray4a4e4a22016-04-19 16:29:23 +0000448 int64_t mFrameNumber;
449
Ana Krulec9a52b192018-07-12 18:18:47 -0400450 std::vector<EventListener> mEventListeners;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700451
452 Mutex mMutex;
453 Condition mCond;
Ana Krulec064a82f2018-09-11 16:03:03 -0700454
455 // Flag to turn on logging in systrace.
456 const bool mTraceDetailedInfo;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700457};
458
Tim Murray4a4e4a22016-04-19 16:29:23 +0000459#undef LOG_TAG
460#define LOG_TAG "DispSync"
461
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462class ZeroPhaseTracer : public DispSync::Callback {
463public:
464 ZeroPhaseTracer() : mParity(false) {}
465
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700466 virtual void onDispSyncEvent(nsecs_t /*when*/) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467 mParity = !mParity;
468 ATRACE_INT("ZERO_PHASE_VSYNC", mParity ? 1 : 0);
469 }
470
471private:
472 bool mParity;
473};
474
Ana Krulec064a82f2018-09-11 16:03:03 -0700475DispSync::DispSync(const char* name) : mName(name), mRefreshSkipCount(0) {
476 // This flag offers the ability to turn on systrace logging from the shell.
477 char value[PROPERTY_VALUE_MAX];
478 property_get("debug.sf.dispsync_trace_detailed_info", value, "0");
479 mTraceDetailedInfo = atoi(value);
480 mThread = new DispSyncThread(name, mTraceDetailedInfo);
481}
Andy McFadden645b1f72014-06-10 14:43:32 -0700482
Ady Abraham50c202a2019-03-14 11:44:38 -0700483DispSync::~DispSync() {
484 mThread->stop();
485 mThread->requestExitAndWait();
486}
Saurabh Shahf4174532017-07-13 10:45:07 -0700487
488void DispSync::init(bool hasSyncFramework, int64_t dispSyncPresentTimeOffset) {
489 mIgnorePresentFences = !hasSyncFramework;
490 mPresentTimeOffset = dispSyncPresentTimeOffset;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700491 mThread->run("DispSync", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
Saurabh Shahf4174532017-07-13 10:45:07 -0700492
Tim Murrayacff43d2016-07-29 13:57:24 -0700493 // set DispSync to SCHED_FIFO to minimize jitter
494 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700495 param.sched_priority = 2;
Tim Murrayacff43d2016-07-29 13:57:24 -0700496 if (sched_setscheduler(mThread->getTid(), SCHED_FIFO, &param) != 0) {
497 ALOGE("Couldn't set SCHED_FIFO for DispSyncThread");
498 }
499
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700500 beginResync();
501
Ana Krulec064a82f2018-09-11 16:03:03 -0700502 if (mTraceDetailedInfo && kEnableZeroPhaseTracer) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700503 mZeroPhaseTracer = std::make_unique<ZeroPhaseTracer>();
Alec Mouri7355eb22019-03-05 14:19:10 -0800504 addEventListener("ZeroPhaseTracer", 0, mZeroPhaseTracer.get(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505 }
506}
507
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700508void DispSync::reset() {
509 Mutex::Autolock lock(mMutex);
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700510 resetLocked();
511}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700513void DispSync::resetLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700514 mPhase = 0;
Alec Mouri75b0b622019-03-12 18:56:00 +0000515 const size_t lastSampleIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
516 // Keep the most recent sample, when we resync to hardware we'll overwrite this
517 // with a more accurate signal
518 if (mResyncSamples[lastSampleIdx] != 0) {
519 mReferenceTime = mResyncSamples[lastSampleIdx];
520 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700521 mModelUpdated = false;
Alec Mouri75b0b622019-03-12 18:56:00 +0000522 for (size_t i = 0; i < MAX_RESYNC_SAMPLES; i++) {
523 mResyncSamples[i] = 0;
524 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 mNumResyncSamples = 0;
526 mFirstResyncSample = 0;
527 mNumResyncSamplesSincePresent = 0;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700528 mThread->unlockModel();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700529 resetErrorLocked();
530}
531
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700532bool DispSync::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 Mutex::Autolock lock(mMutex);
534
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700535 if (mIgnorePresentFences) {
536 return true;
537 }
538
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700539 mPresentFences[mPresentSampleOffset] = fenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540 mPresentSampleOffset = (mPresentSampleOffset + 1) % NUM_PRESENT_SAMPLES;
541 mNumResyncSamplesSincePresent = 0;
542
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700543 updateErrorLocked();
544
Haixia Shi676b1f62015-10-28 16:19:01 -0700545 return !mModelUpdated || mError > kErrorThreshold;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700546}
547
548void DispSync::beginResync() {
549 Mutex::Autolock lock(mMutex);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000550 ALOGV("[%s] beginResync", mName);
Alec Mourif8e689c2019-05-20 18:32:22 -0700551 resetLocked();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552}
553
Alec Mourif8e689c2019-05-20 18:32:22 -0700554bool DispSync::addResyncSample(nsecs_t timestamp, bool* periodFlushed) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700555 Mutex::Autolock lock(mMutex);
556
Tim Murray4a4e4a22016-04-19 16:29:23 +0000557 ALOGV("[%s] addResyncSample(%" PRId64 ")", mName, ns2us(timestamp));
558
Alec Mourif8e689c2019-05-20 18:32:22 -0700559 *periodFlushed = false;
Alec Mouri754c98a2019-03-18 18:53:42 -0700560 const size_t idx = (mFirstResyncSample + mNumResyncSamples) % MAX_RESYNC_SAMPLES;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700561 mResyncSamples[idx] = timestamp;
Haixia Shi664339a2015-10-28 13:22:22 -0700562 if (mNumResyncSamples == 0) {
Haixia Shi676b1f62015-10-28 16:19:01 -0700563 mPhase = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000564 ALOGV("[%s] First resync sample: mPeriod = %" PRId64 ", mPhase = 0, "
Lloyd Pique78ce4182018-01-31 16:39:51 -0800565 "mReferenceTime = %" PRId64,
Alec Mouri754c98a2019-03-18 18:53:42 -0700566 mName, ns2us(mPeriod), ns2us(timestamp));
567 } else if (mPendingPeriod > 0) {
568 // mNumResyncSamples > 0, so priorIdx won't overflow
569 const size_t priorIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
570 const nsecs_t lastTimestamp = mResyncSamples[priorIdx];
571
572 const nsecs_t observedVsync = std::abs(timestamp - lastTimestamp);
Alec Mourif8e689c2019-05-20 18:32:22 -0700573 if (std::abs(observedVsync - mPendingPeriod) <= std::abs(observedVsync - mIntendedPeriod)) {
574 // Either the observed vsync is closer to the pending period, (and
575 // thus we detected a period change), or the period change will
576 // no-op. In either case, reset the model and flush the pending
577 // period.
Alec Mouri754c98a2019-03-18 18:53:42 -0700578 resetLocked();
Alec Mourif8e689c2019-05-20 18:32:22 -0700579 mIntendedPeriod = mPendingPeriod;
Alec Mouri754c98a2019-03-18 18:53:42 -0700580 mPeriod = mPendingPeriod;
581 mPendingPeriod = 0;
582 if (mTraceDetailedInfo) {
583 ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
Alec Mourif8e689c2019-05-20 18:32:22 -0700584 ATRACE_INT("DispSync:IntendedPeriod", mIntendedPeriod);
Alec Mouri754c98a2019-03-18 18:53:42 -0700585 }
Alec Mourif8e689c2019-05-20 18:32:22 -0700586 *periodFlushed = true;
Alec Mouri754c98a2019-03-18 18:53:42 -0700587 }
Haixia Shi664339a2015-10-28 13:22:22 -0700588 }
Alec Mouri754c98a2019-03-18 18:53:42 -0700589 // Always update the reference time with the most recent timestamp.
590 mReferenceTime = timestamp;
591 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700592
593 if (mNumResyncSamples < MAX_RESYNC_SAMPLES) {
594 mNumResyncSamples++;
595 } else {
596 mFirstResyncSample = (mFirstResyncSample + 1) % MAX_RESYNC_SAMPLES;
597 }
598
599 updateModelLocked();
600
601 if (mNumResyncSamplesSincePresent++ > MAX_RESYNC_SAMPLES_WITHOUT_PRESENT) {
602 resetErrorLocked();
603 }
604
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800605 if (mIgnorePresentFences) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700606 // If we're ignoring the present fences we have no way to know whether
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700607 // or not we're synchronized with the HW vsyncs, so we just request
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700608 // that the HW vsync events be turned on.
609 return true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700610 }
611
Tim Murray4a4e4a22016-04-19 16:29:23 +0000612 // Check against kErrorThreshold / 2 to add some hysteresis before having to
613 // resync again
Alec Mouri754c98a2019-03-18 18:53:42 -0700614 bool modelLocked = mModelUpdated && mError < (kErrorThreshold / 2) && mPendingPeriod == 0;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800615 ALOGV("[%s] addResyncSample returning %s", mName, modelLocked ? "locked" : "unlocked");
Alec Mouri016b8dd2019-04-24 15:16:05 -0700616 if (modelLocked) {
Alec Mourif8e689c2019-05-20 18:32:22 -0700617 *periodFlushed = true;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700618 mThread->lockModel();
619 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000620 return !modelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700621}
622
Alec Mouri016b8dd2019-04-24 15:16:05 -0700623void DispSync::endResync() {
624 mThread->lockModel();
625}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700626
Alec Mouri7355eb22019-03-05 14:19:10 -0800627status_t DispSync::addEventListener(const char* name, nsecs_t phase, Callback* callback,
628 nsecs_t lastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700629 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800630 return mThread->addEventListener(name, phase, callback, lastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700631}
632
Andy McFadden645b1f72014-06-10 14:43:32 -0700633void DispSync::setRefreshSkipCount(int count) {
634 Mutex::Autolock lock(mMutex);
635 ALOGD("setRefreshSkipCount(%d)", count);
636 mRefreshSkipCount = count;
637 updateModelLocked();
Ruchi Kandoif52b3c82014-04-24 16:42:35 -0700638}
639
Alec Mouri7355eb22019-03-05 14:19:10 -0800640status_t DispSync::removeEventListener(Callback* callback, nsecs_t* outLastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700641 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800642 return mThread->removeEventListener(callback, outLastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700643}
644
Dan Stoza84d619e2018-03-28 17:07:36 -0700645status_t DispSync::changePhaseOffset(Callback* callback, nsecs_t phase) {
646 Mutex::Autolock lock(mMutex);
647 return mThread->changePhaseOffset(callback, phase);
648}
649
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700650void DispSync::setPeriod(nsecs_t period) {
651 Mutex::Autolock lock(mMutex);
Alec Mourif8e689c2019-05-20 18:32:22 -0700652
653 const bool pendingPeriodShouldChange =
654 period != mIntendedPeriod || (period == mIntendedPeriod && mPendingPeriod != 0);
655
656 if (pendingPeriodShouldChange) {
657 mPendingPeriod = period;
Alec Mouri754c98a2019-03-18 18:53:42 -0700658 }
Alec Mourif8e689c2019-05-20 18:32:22 -0700659 if (mTraceDetailedInfo) {
660 ATRACE_INT("DispSync:IntendedPeriod", mIntendedPeriod);
661 ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
662 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700663}
664
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700665nsecs_t DispSync::getPeriod() {
666 // lock mutex as mPeriod changes multiple times in updateModelLocked
667 Mutex::Autolock lock(mMutex);
668 return mPeriod;
669}
670
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700671void DispSync::updateModelLocked() {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000672 ALOGV("[%s] updateModelLocked %zu", mName, mNumResyncSamples);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700673 if (mNumResyncSamples >= MIN_RESYNC_SAMPLES_FOR_UPDATE) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000674 ALOGV("[%s] Computing...", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700675 nsecs_t durationSum = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000676 nsecs_t minDuration = INT64_MAX;
677 nsecs_t maxDuration = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700678 for (size_t i = 1; i < mNumResyncSamples; i++) {
679 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
680 size_t prev = (idx + MAX_RESYNC_SAMPLES - 1) % MAX_RESYNC_SAMPLES;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000681 nsecs_t duration = mResyncSamples[idx] - mResyncSamples[prev];
682 durationSum += duration;
683 minDuration = min(minDuration, duration);
684 maxDuration = max(maxDuration, duration);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700685 }
686
Tim Murray4a4e4a22016-04-19 16:29:23 +0000687 // Exclude the min and max from the average
688 durationSum -= minDuration + maxDuration;
David Sodman1afa8b02018-10-15 11:20:48 -0700689 mPeriod = durationSum / (mNumResyncSamples - 3);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000690
691 ALOGV("[%s] mPeriod = %" PRId64, mName, ns2us(mPeriod));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700692
693 double sampleAvgX = 0;
694 double sampleAvgY = 0;
695 double scale = 2.0 * M_PI / double(mPeriod);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000696 // Intentionally skip the first sample
697 for (size_t i = 1; i < mNumResyncSamples; i++) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700698 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
Haixia Shi676b1f62015-10-28 16:19:01 -0700699 nsecs_t sample = mResyncSamples[idx] - mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700700 double samplePhase = double(sample % mPeriod) * scale;
701 sampleAvgX += cos(samplePhase);
702 sampleAvgY += sin(samplePhase);
703 }
704
Tim Murray4a4e4a22016-04-19 16:29:23 +0000705 sampleAvgX /= double(mNumResyncSamples - 1);
706 sampleAvgY /= double(mNumResyncSamples - 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700707
708 mPhase = nsecs_t(atan2(sampleAvgY, sampleAvgX) / scale);
709
Tim Murray4a4e4a22016-04-19 16:29:23 +0000710 ALOGV("[%s] mPhase = %" PRId64, mName, ns2us(mPhase));
711
712 if (mPhase < -(mPeriod / 2)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700713 mPhase += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000714 ALOGV("[%s] Adjusting mPhase -> %" PRId64, mName, ns2us(mPhase));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700715 }
716
Andy McFadden645b1f72014-06-10 14:43:32 -0700717 // Artificially inflate the period if requested.
718 mPeriod += mPeriod * mRefreshSkipCount;
719
Haixia Shi676b1f62015-10-28 16:19:01 -0700720 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
721 mModelUpdated = true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700722 }
723}
724
725void DispSync::updateErrorLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700726 if (!mModelUpdated) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700727 return;
728 }
729
Andy McFadden645b1f72014-06-10 14:43:32 -0700730 // Need to compare present fences against the un-adjusted refresh period,
731 // since they might arrive between two events.
732 nsecs_t period = mPeriod / (1 + mRefreshSkipCount);
733
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700734 int numErrSamples = 0;
735 nsecs_t sqErrSum = 0;
736
737 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700738 // Only check for the cached value of signal time to avoid unecessary
739 // syscalls. It is the responsibility of the DispSync owner to
740 // call getSignalTime() periodically so the cache is updated when the
741 // fence signals.
742 nsecs_t time = mPresentFences[i]->getCachedSignalTime();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800743 if (time == Fence::SIGNAL_TIME_PENDING || time == Fence::SIGNAL_TIME_INVALID) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700744 continue;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700745 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700746
747 nsecs_t sample = time - mReferenceTime;
748 if (sample <= mPhase) {
749 continue;
750 }
751
752 nsecs_t sampleErr = (sample - mPhase) % period;
753 if (sampleErr > period / 2) {
754 sampleErr -= period;
755 }
756 sqErrSum += sampleErr * sampleErr;
757 numErrSamples++;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700758 }
759
760 if (numErrSamples > 0) {
761 mError = sqErrSum / numErrSamples;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700762 mZeroErrSamplesCount = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700763 } else {
764 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700765 // Use mod ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT to avoid log spam.
766 mZeroErrSamplesCount++;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800767 ALOGE_IF((mZeroErrSamplesCount % ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT) == 0,
768 "No present times for model error.");
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700769 }
770
Ana Krulec064a82f2018-09-11 16:03:03 -0700771 if (mTraceDetailedInfo) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700772 ATRACE_INT64("DispSync:Error", mError);
773 }
774}
775
776void DispSync::resetErrorLocked() {
777 mPresentSampleOffset = 0;
778 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700779 mZeroErrSamplesCount = 0;
Alec Mourif8e689c2019-05-20 18:32:22 -0700780 if (mTraceDetailedInfo) {
781 ATRACE_INT64("DispSync:Error", mError);
782 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700783 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700784 mPresentFences[i] = FenceTime::NO_FENCE;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700785 }
786}
787
Andy McFadden41d67d72014-04-25 16:58:34 -0700788nsecs_t DispSync::computeNextRefresh(int periodOffset) const {
Andy McFadden150ecd82014-05-08 14:56:50 -0700789 Mutex::Autolock lock(mMutex);
Andy McFadden41d67d72014-04-25 16:58:34 -0700790 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Haixia Shi676b1f62015-10-28 16:19:01 -0700791 nsecs_t phase = mReferenceTime + mPhase;
Marissa Wall17b4e452018-12-26 16:32:34 -0800792 if (mPeriod == 0) {
793 return 0;
794 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700795 return (((now - phase) / mPeriod) + periodOffset + 1) * mPeriod + phase;
Andy McFadden41d67d72014-04-25 16:58:34 -0700796}
797
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700798void DispSync::setIgnorePresentFences(bool ignore) {
799 Mutex::Autolock lock(mMutex);
800 if (mIgnorePresentFences != ignore) {
801 mIgnorePresentFences = ignore;
802 resetLocked();
803 }
804}
805
Yiwei Zhang5434a782018-12-05 18:06:32 -0800806void DispSync::dump(std::string& result) const {
Andy McFaddenc751e922014-05-08 14:53:26 -0700807 Mutex::Autolock lock(mMutex);
Yiwei Zhang5434a782018-12-05 18:06:32 -0800808 StringAppendF(&result, "present fences are %s\n", mIgnorePresentFences ? "ignored" : "used");
809 StringAppendF(&result, "mPeriod: %" PRId64 " ns (%.3f fps; skipCount=%d)\n", mPeriod,
810 1000000000.0 / mPeriod, mRefreshSkipCount);
811 StringAppendF(&result, "mPhase: %" PRId64 " ns\n", mPhase);
812 StringAppendF(&result, "mError: %" PRId64 " ns (sqrt=%.1f)\n", mError, sqrt(mError));
813 StringAppendF(&result, "mNumResyncSamplesSincePresent: %d (limit %d)\n",
814 mNumResyncSamplesSincePresent, MAX_RESYNC_SAMPLES_WITHOUT_PRESENT);
815 StringAppendF(&result, "mNumResyncSamples: %zd (max %d)\n", mNumResyncSamples,
816 MAX_RESYNC_SAMPLES);
Andy McFaddenc751e922014-05-08 14:53:26 -0700817
Yiwei Zhang5434a782018-12-05 18:06:32 -0800818 result.append("mResyncSamples:\n");
Andy McFaddenc751e922014-05-08 14:53:26 -0700819 nsecs_t previous = -1;
820 for (size_t i = 0; i < mNumResyncSamples; i++) {
821 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
822 nsecs_t sampleTime = mResyncSamples[idx];
823 if (i == 0) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800824 StringAppendF(&result, " %" PRId64 "\n", sampleTime);
Andy McFaddenc751e922014-05-08 14:53:26 -0700825 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800826 StringAppendF(&result, " %" PRId64 " (+%" PRId64 ")\n", sampleTime,
827 sampleTime - previous);
Andy McFaddenc751e922014-05-08 14:53:26 -0700828 }
829 previous = sampleTime;
830 }
831
Yiwei Zhang5434a782018-12-05 18:06:32 -0800832 StringAppendF(&result, "mPresentFences [%d]:\n", NUM_PRESENT_SAMPLES);
Andy McFadden5167ec62014-05-22 13:08:43 -0700833 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700834 previous = Fence::SIGNAL_TIME_INVALID;
Andy McFaddenc751e922014-05-08 14:53:26 -0700835 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
836 size_t idx = (i + mPresentSampleOffset) % NUM_PRESENT_SAMPLES;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700837 nsecs_t presentTime = mPresentFences[idx]->getSignalTime();
838 if (presentTime == Fence::SIGNAL_TIME_PENDING) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800839 StringAppendF(&result, " [unsignaled fence]\n");
Lloyd Pique78ce4182018-01-31 16:39:51 -0800840 } else if (presentTime == Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800841 StringAppendF(&result, " [invalid fence]\n");
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700842 } else if (previous == Fence::SIGNAL_TIME_PENDING ||
Lloyd Pique78ce4182018-01-31 16:39:51 -0800843 previous == Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800844 StringAppendF(&result, " %" PRId64 " (%.3f ms ago)\n", presentTime,
845 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700846 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800847 StringAppendF(&result, " %" PRId64 " (+%" PRId64 " / %.3f) (%.3f ms ago)\n",
848 presentTime, presentTime - previous,
849 (presentTime - previous) / (double)mPeriod,
850 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700851 }
852 previous = presentTime;
853 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700854
Yiwei Zhang5434a782018-12-05 18:06:32 -0800855 StringAppendF(&result, "current monotonic time: %" PRId64 "\n", now);
Andy McFaddenc751e922014-05-08 14:53:26 -0700856}
857
Ana Krulec010d2192018-10-08 06:29:54 -0700858nsecs_t DispSync::expectedPresentTime() {
859 // The HWC doesn't currently have a way to report additional latency.
860 // Assume that whatever we submit now will appear right after the flip.
861 // For a smart panel this might be 1. This is expressed in frames,
862 // rather than time, because we expect to have a constant frame delay
863 // regardless of the refresh rate.
864 const uint32_t hwcLatency = 0;
865
866 // Ask DispSync when the next refresh will be (CLOCK_MONOTONIC).
Ana Krulec757f63a2019-01-25 10:46:18 -0800867 return computeNextRefresh(hwcLatency);
Ana Krulec010d2192018-10-08 06:29:54 -0700868}
869
Lloyd Pique41be5d22018-06-21 13:11:48 -0700870} // namespace impl
871
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700872} // namespace android