blob: ae776a012a473feb6027eccf9cf3532c7a89a7ae [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),
Ady Abraham50204dd2019-07-19 15:47:11 -070067 mModelLocked("DispSync:ModelLocked", 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) {
Ady Abraham81ca00f2019-06-19 17:01:57 -070095 eventListener.mLastEventTime = mReferenceTime + mPhase + eventListener.mPhase;
96 // If mLastEventTime is after mReferenceTime (can happen when positive phase offsets
97 // are used) we treat it as like it happened in previous period.
98 if (eventListener.mLastEventTime > mReferenceTime) {
99 eventListener.mLastEventTime -= mPeriod;
100 }
Alec Mouric3a482d2019-05-21 00:51:01 -0700101 }
102 }
Alec Mourif5fe85c2019-02-22 13:40:36 -0800103 if (mTraceDetailedInfo) {
104 ATRACE_INT64("DispSync:Period", mPeriod);
105 ATRACE_INT64("DispSync:Phase", mPhase + mPeriod / 2);
106 ATRACE_INT64("DispSync:Reference Time", mReferenceTime);
107 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000108 ALOGV("[%s] updateModel: mPeriod = %" PRId64 ", mPhase = %" PRId64
Lloyd Pique78ce4182018-01-31 16:39:51 -0800109 " mReferenceTime = %" PRId64,
110 mName, ns2us(mPeriod), ns2us(mPhase), ns2us(mReferenceTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111 mCond.signal();
112 }
113
114 void stop() {
Ana Krulec064a82f2018-09-11 16:03:03 -0700115 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700116 Mutex::Autolock lock(mMutex);
117 mStop = true;
118 mCond.signal();
119 }
120
Alec Mouri016b8dd2019-04-24 15:16:05 -0700121 void lockModel() {
122 Mutex::Autolock lock(mMutex);
123 mModelLocked = true;
124 }
125
126 void unlockModel() {
127 Mutex::Autolock lock(mMutex);
128 mModelLocked = false;
129 }
130
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700131 virtual bool threadLoop() {
132 status_t err;
133 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700134
135 while (true) {
Ana Krulec9a52b192018-07-12 18:18:47 -0400136 std::vector<CallbackInvocation> callbackInvocations;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700137
138 nsecs_t targetTime = 0;
139
140 { // Scope for lock
141 Mutex::Autolock lock(mMutex);
142
Ana Krulec064a82f2018-09-11 16:03:03 -0700143 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000144 ATRACE_INT64("DispSync:Frame", mFrameNumber);
145 }
146 ALOGV("[%s] Frame %" PRId64, mName, mFrameNumber);
147 ++mFrameNumber;
148
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700149 if (mStop) {
150 return false;
151 }
152
153 if (mPeriod == 0) {
154 err = mCond.wait(mMutex);
155 if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800156 ALOGE("error waiting for new events: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700157 return false;
158 }
159 continue;
160 }
161
Dan Stoza8f8374d2016-04-19 10:03:46 -0700162 targetTime = computeNextEventTimeLocked(now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700163
164 bool isWakeup = false;
165
166 if (now < targetTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700167 if (mTraceDetailedInfo) ATRACE_NAME("DispSync waiting");
Dan Stoza8f8374d2016-04-19 10:03:46 -0700168
169 if (targetTime == INT64_MAX) {
170 ALOGV("[%s] Waiting forever", mName);
171 err = mCond.wait(mMutex);
172 } else {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800173 ALOGV("[%s] Waiting until %" PRId64, mName, ns2us(targetTime));
Dan Stoza8f8374d2016-04-19 10:03:46 -0700174 err = mCond.waitRelative(mMutex, targetTime - now);
175 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700176
177 if (err == TIMED_OUT) {
178 isWakeup = true;
179 } else if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800180 ALOGE("error waiting for next event: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700181 return false;
182 }
183 }
184
185 now = systemTime(SYSTEM_TIME_MONOTONIC);
186
Tim Murray4a4e4a22016-04-19 16:29:23 +0000187 // Don't correct by more than 1.5 ms
188 static const nsecs_t kMaxWakeupLatency = us2ns(1500);
189
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700190 if (isWakeup) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800191 mWakeupLatency = ((mWakeupLatency * 63) + (now - targetTime)) / 64;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000192 mWakeupLatency = min(mWakeupLatency, kMaxWakeupLatency);
Ana Krulec064a82f2018-09-11 16:03:03 -0700193 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000194 ATRACE_INT64("DispSync:WakeupLat", now - targetTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700195 ATRACE_INT64("DispSync:AvgWakeupLat", mWakeupLatency);
196 }
197 }
198
199 callbackInvocations = gatherCallbackInvocationsLocked(now);
200 }
201
202 if (callbackInvocations.size() > 0) {
Andy McFadden645b1f72014-06-10 14:43:32 -0700203 fireCallbackInvocations(callbackInvocations);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700204 }
205 }
206
207 return false;
208 }
209
Alec Mouri7355eb22019-03-05 14:19:10 -0800210 status_t addEventListener(const char* name, nsecs_t phase, DispSync::Callback* callback,
211 nsecs_t lastCallbackTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700212 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700213 Mutex::Autolock lock(mMutex);
214
215 for (size_t i = 0; i < mEventListeners.size(); i++) {
216 if (mEventListeners[i].mCallback == callback) {
217 return BAD_VALUE;
218 }
219 }
220
221 EventListener listener;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000222 listener.mName = name;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700223 listener.mPhase = phase;
224 listener.mCallback = callback;
Jamie Gennis629b9872013-10-29 13:36:12 -0700225
226 // We want to allow the firstmost future event to fire without
Alec Mouri81835982019-02-27 13:40:44 -0800227 // allowing any past events to fire. To do this extrapolate from
228 // mReferenceTime the most recent hardware vsync, and pin the
229 // last event time there.
230 const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
231 if (mPeriod != 0) {
232 const nsecs_t baseTime = now - mReferenceTime;
233 const nsecs_t numPeriodsSinceReference = baseTime / mPeriod;
234 const nsecs_t predictedReference = mReferenceTime + numPeriodsSinceReference * mPeriod;
Alec Mouridf3d2e12019-05-02 17:58:46 +0000235 const nsecs_t phaseCorrection = mPhase + listener.mPhase;
236 const nsecs_t predictedLastEventTime = predictedReference + phaseCorrection;
237 if (predictedLastEventTime >= now) {
238 // Make sure that the last event time does not exceed the current time.
239 // If it would, then back the last event time by a period.
240 listener.mLastEventTime = predictedLastEventTime - mPeriod;
241 } else {
242 listener.mLastEventTime = predictedLastEventTime;
Alec Mouri81835982019-02-27 13:40:44 -0800243 }
244 } else {
245 listener.mLastEventTime = now + mPhase - mWakeupLatency;
246 }
Jamie Gennis629b9872013-10-29 13:36:12 -0700247
Alec Mouri7355eb22019-03-05 14:19:10 -0800248 if (lastCallbackTime <= 0) {
249 // If there is no prior callback time, try to infer one based on the
250 // logical last event time.
251 listener.mLastCallbackTime = listener.mLastEventTime + mWakeupLatency;
252 } else {
253 listener.mLastCallbackTime = lastCallbackTime;
254 }
255
Ana Krulec9a52b192018-07-12 18:18:47 -0400256 mEventListeners.push_back(listener);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700257
258 mCond.signal();
259
260 return NO_ERROR;
261 }
262
Alec Mouri7355eb22019-03-05 14:19:10 -0800263 status_t removeEventListener(DispSync::Callback* callback, nsecs_t* outLastCallback) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700264 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700265 Mutex::Autolock lock(mMutex);
266
Ana Krulec9a52b192018-07-12 18:18:47 -0400267 for (std::vector<EventListener>::iterator it = mEventListeners.begin();
268 it != mEventListeners.end(); ++it) {
269 if (it->mCallback == callback) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800270 *outLastCallback = it->mLastCallbackTime;
Ana Krulec9a52b192018-07-12 18:18:47 -0400271 mEventListeners.erase(it);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700272 mCond.signal();
273 return NO_ERROR;
274 }
275 }
276
277 return BAD_VALUE;
278 }
279
Dan Stoza84d619e2018-03-28 17:07:36 -0700280 status_t changePhaseOffset(DispSync::Callback* callback, nsecs_t phase) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700281 if (mTraceDetailedInfo) ATRACE_CALL();
Dan Stoza84d619e2018-03-28 17:07:36 -0700282 Mutex::Autolock lock(mMutex);
283
Ana Krulec9a52b192018-07-12 18:18:47 -0400284 for (auto& eventListener : mEventListeners) {
285 if (eventListener.mCallback == callback) {
286 const nsecs_t oldPhase = eventListener.mPhase;
287 eventListener.mPhase = phase;
Dan Stoza84d619e2018-03-28 17:07:36 -0700288
289 // Pretend that the last time this event was handled at the same frame but with the
290 // new offset to allow for a seamless offset change without double-firing or
291 // skipping.
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200292 nsecs_t diff = oldPhase - phase;
Ana Krulec9a52b192018-07-12 18:18:47 -0400293 eventListener.mLastEventTime -= diff;
Ady Abraham45e4e362019-06-07 18:20:51 -0700294 eventListener.mLastCallbackTime -= diff;
Dan Stoza84d619e2018-03-28 17:07:36 -0700295 mCond.signal();
296 return NO_ERROR;
297 }
298 }
Dan Stoza84d619e2018-03-28 17:07:36 -0700299 return BAD_VALUE;
300 }
301
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700302private:
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700303 struct EventListener {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000304 const char* mName;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700305 nsecs_t mPhase;
306 nsecs_t mLastEventTime;
Alec Mouri7355eb22019-03-05 14:19:10 -0800307 nsecs_t mLastCallbackTime;
Lloyd Piquee83f9312018-02-01 12:53:17 -0800308 DispSync::Callback* mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700309 };
310
311 struct CallbackInvocation {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800312 DispSync::Callback* mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700313 nsecs_t mEventTime;
314 };
315
316 nsecs_t computeNextEventTimeLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700317 if (mTraceDetailedInfo) ATRACE_CALL();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000318 ALOGV("[%s] computeNextEventTimeLocked", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700319 nsecs_t nextEventTime = INT64_MAX;
320 for (size_t i = 0; i < mEventListeners.size(); i++) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800321 nsecs_t t = computeListenerNextEventTimeLocked(mEventListeners[i], now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700322
323 if (t < nextEventTime) {
324 nextEventTime = t;
325 }
326 }
327
Tim Murray4a4e4a22016-04-19 16:29:23 +0000328 ALOGV("[%s] nextEventTime = %" PRId64, mName, ns2us(nextEventTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700329 return nextEventTime;
330 }
331
Alec Mouri7355eb22019-03-05 14:19:10 -0800332 // Sanity check that the duration is close enough in length to a period without
333 // falling into double-rate vsyncs.
Alec Mouridf3d2e12019-05-02 17:58:46 +0000334 bool isCloseToPeriod(nsecs_t duration) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800335 // Ratio of 3/5 is arbitrary, but it must be greater than 1/2.
336 return duration < (3 * mPeriod) / 5;
337 }
338
Ana Krulec9a52b192018-07-12 18:18:47 -0400339 std::vector<CallbackInvocation> gatherCallbackInvocationsLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700340 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800341 ALOGV("[%s] gatherCallbackInvocationsLocked @ %" PRId64, mName, ns2us(now));
Tim Murray4a4e4a22016-04-19 16:29:23 +0000342
Ana Krulec9a52b192018-07-12 18:18:47 -0400343 std::vector<CallbackInvocation> callbackInvocations;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000344 nsecs_t onePeriodAgo = now - mPeriod;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700345
Ana Krulec9a52b192018-07-12 18:18:47 -0400346 for (auto& eventListener : mEventListeners) {
347 nsecs_t t = computeListenerNextEventTimeLocked(eventListener, onePeriodAgo);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700348
Jamie Gennis0d5c60e2013-10-09 17:49:37 -0700349 if (t < now) {
Alec Mouridf3d2e12019-05-02 17:58:46 +0000350 if (isCloseToPeriod(now - eventListener.mLastCallbackTime)) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800351 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800352 ALOGV("[%s] [%s] Skipping event due to model error", mName,
353 eventListener.mName);
354 continue;
355 }
Ady Abraham45e4e362019-06-07 18:20:51 -0700356
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700357 CallbackInvocation ci;
Ana Krulec9a52b192018-07-12 18:18:47 -0400358 ci.mCallback = eventListener.mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700359 ci.mEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800360 ALOGV("[%s] [%s] Preparing to fire, latency: %" PRId64, mName, eventListener.mName,
361 t - eventListener.mLastEventTime);
Ana Krulec9a52b192018-07-12 18:18:47 -0400362 callbackInvocations.push_back(ci);
363 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800364 eventListener.mLastCallbackTime = now;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700365 }
366 }
367
368 return callbackInvocations;
369 }
370
Lloyd Pique78ce4182018-01-31 16:39:51 -0800371 nsecs_t computeListenerNextEventTimeLocked(const EventListener& listener, nsecs_t baseTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700372 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800373 ALOGV("[%s] [%s] computeListenerNextEventTimeLocked(%" PRId64 ")", mName, listener.mName,
374 ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700375
Tim Murray4a4e4a22016-04-19 16:29:23 +0000376 nsecs_t lastEventTime = listener.mLastEventTime + mWakeupLatency;
377 ALOGV("[%s] lastEventTime: %" PRId64, mName, ns2us(lastEventTime));
378 if (baseTime < lastEventTime) {
379 baseTime = lastEventTime;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800380 ALOGV("[%s] Clamping baseTime to lastEventTime -> %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700381 }
382
Tim Murray4a4e4a22016-04-19 16:29:23 +0000383 baseTime -= mReferenceTime;
384 ALOGV("[%s] Relative baseTime = %" PRId64, mName, ns2us(baseTime));
385 nsecs_t phase = mPhase + listener.mPhase;
386 ALOGV("[%s] Phase = %" PRId64, mName, ns2us(phase));
387 baseTime -= phase;
388 ALOGV("[%s] baseTime - phase = %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700389
Tim Murray4a4e4a22016-04-19 16:29:23 +0000390 // If our previous time is before the reference (because the reference
391 // has since been updated), the division by mPeriod will truncate
392 // towards zero instead of computing the floor. Since in all cases
393 // before the reference we want the next time to be effectively now, we
394 // set baseTime to -mPeriod so that numPeriods will be -1.
395 // When we add 1 and the phase, we will be at the correct event time for
396 // this period.
397 if (baseTime < 0) {
398 ALOGV("[%s] Correcting negative baseTime", mName);
399 baseTime = -mPeriod;
400 }
401
402 nsecs_t numPeriods = baseTime / mPeriod;
403 ALOGV("[%s] numPeriods = %" PRId64, mName, numPeriods);
404 nsecs_t t = (numPeriods + 1) * mPeriod + phase;
405 ALOGV("[%s] t = %" PRId64, mName, ns2us(t));
406 t += mReferenceTime;
407 ALOGV("[%s] Absolute t = %" PRId64, mName, ns2us(t));
408
409 // Check that it's been slightly more than half a period since the last
410 // event so that we don't accidentally fall into double-rate vsyncs
Alec Mouridf3d2e12019-05-02 17:58:46 +0000411 if (isCloseToPeriod(t - listener.mLastEventTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412 t += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000413 ALOGV("[%s] Modifying t -> %" PRId64, mName, ns2us(t));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700414 }
415
Tim Murray4a4e4a22016-04-19 16:29:23 +0000416 t -= mWakeupLatency;
417 ALOGV("[%s] Corrected for wakeup latency -> %" PRId64, mName, ns2us(t));
418
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700419 return t;
420 }
421
Ana Krulec9a52b192018-07-12 18:18:47 -0400422 void fireCallbackInvocations(const std::vector<CallbackInvocation>& callbacks) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700423 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 for (size_t i = 0; i < callbacks.size(); i++) {
425 callbacks[i].mCallback->onDispSyncEvent(callbacks[i].mEventTime);
426 }
427 }
428
Tim Murray4a4e4a22016-04-19 16:29:23 +0000429 const char* const mName;
430
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 bool mStop;
Ady Abraham50204dd2019-07-19 15:47:11 -0700432 TracedOrdinal<bool> mModelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700433
434 nsecs_t mPeriod;
435 nsecs_t mPhase;
Haixia Shi676b1f62015-10-28 16:19:01 -0700436 nsecs_t mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700437 nsecs_t mWakeupLatency;
438
Tim Murray4a4e4a22016-04-19 16:29:23 +0000439 int64_t mFrameNumber;
440
Ana Krulec9a52b192018-07-12 18:18:47 -0400441 std::vector<EventListener> mEventListeners;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442
443 Mutex mMutex;
444 Condition mCond;
Ana Krulec064a82f2018-09-11 16:03:03 -0700445
446 // Flag to turn on logging in systrace.
447 const bool mTraceDetailedInfo;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700448};
449
Tim Murray4a4e4a22016-04-19 16:29:23 +0000450#undef LOG_TAG
451#define LOG_TAG "DispSync"
452
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700453class ZeroPhaseTracer : public DispSync::Callback {
454public:
Ady Abraham50204dd2019-07-19 15:47:11 -0700455 ZeroPhaseTracer() : mParity("ZERO_PHASE_VSYNC", false) {}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700456
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700457 virtual void onDispSyncEvent(nsecs_t /*when*/) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 mParity = !mParity;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700459 }
460
461private:
Ady Abraham50204dd2019-07-19 15:47:11 -0700462 TracedOrdinal<bool> mParity;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463};
464
Dominik Laskowski98041832019-08-01 18:35:59 -0700465DispSync::DispSync(const char* name, bool hasSyncFramework)
466 : mName(name), mIgnorePresentFences(!hasSyncFramework) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700467 // This flag offers the ability to turn on systrace logging from the shell.
468 char value[PROPERTY_VALUE_MAX];
469 property_get("debug.sf.dispsync_trace_detailed_info", value, "0");
470 mTraceDetailedInfo = atoi(value);
Dominik Laskowski98041832019-08-01 18:35:59 -0700471
Ana Krulec064a82f2018-09-11 16:03:03 -0700472 mThread = new DispSyncThread(name, mTraceDetailedInfo);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700473 mThread->run("DispSync", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
Saurabh Shahf4174532017-07-13 10:45:07 -0700474
Tim Murrayacff43d2016-07-29 13:57:24 -0700475 // set DispSync to SCHED_FIFO to minimize jitter
476 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700477 param.sched_priority = 2;
Tim Murrayacff43d2016-07-29 13:57:24 -0700478 if (sched_setscheduler(mThread->getTid(), SCHED_FIFO, &param) != 0) {
479 ALOGE("Couldn't set SCHED_FIFO for DispSyncThread");
480 }
481
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700482 beginResync();
483
Ana Krulec064a82f2018-09-11 16:03:03 -0700484 if (mTraceDetailedInfo && kEnableZeroPhaseTracer) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700485 mZeroPhaseTracer = std::make_unique<ZeroPhaseTracer>();
Alec Mouri7355eb22019-03-05 14:19:10 -0800486 addEventListener("ZeroPhaseTracer", 0, mZeroPhaseTracer.get(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 }
488}
489
Dominik Laskowski98041832019-08-01 18:35:59 -0700490DispSync::~DispSync() {
491 mThread->stop();
492 mThread->requestExitAndWait();
493}
494
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700495void DispSync::reset() {
496 Mutex::Autolock lock(mMutex);
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700497 resetLocked();
498}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700499
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700500void DispSync::resetLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700501 mPhase = 0;
Alec Mouri75b0b622019-03-12 18:56:00 +0000502 const size_t lastSampleIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
503 // Keep the most recent sample, when we resync to hardware we'll overwrite this
504 // with a more accurate signal
505 if (mResyncSamples[lastSampleIdx] != 0) {
506 mReferenceTime = mResyncSamples[lastSampleIdx];
507 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700508 mModelUpdated = false;
Alec Mouri75b0b622019-03-12 18:56:00 +0000509 for (size_t i = 0; i < MAX_RESYNC_SAMPLES; i++) {
510 mResyncSamples[i] = 0;
511 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512 mNumResyncSamples = 0;
513 mFirstResyncSample = 0;
514 mNumResyncSamplesSincePresent = 0;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700515 mThread->unlockModel();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 resetErrorLocked();
517}
518
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700519bool DispSync::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520 Mutex::Autolock lock(mMutex);
521
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700522 if (mIgnorePresentFences) {
523 return true;
524 }
525
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700526 mPresentFences[mPresentSampleOffset] = fenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 mPresentSampleOffset = (mPresentSampleOffset + 1) % NUM_PRESENT_SAMPLES;
528 mNumResyncSamplesSincePresent = 0;
529
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530 updateErrorLocked();
531
Haixia Shi676b1f62015-10-28 16:19:01 -0700532 return !mModelUpdated || mError > kErrorThreshold;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533}
534
535void DispSync::beginResync() {
536 Mutex::Autolock lock(mMutex);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000537 ALOGV("[%s] beginResync", mName);
Alec Mourif8e689c2019-05-20 18:32:22 -0700538 resetLocked();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539}
540
Alec Mourif8e689c2019-05-20 18:32:22 -0700541bool DispSync::addResyncSample(nsecs_t timestamp, bool* periodFlushed) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 Mutex::Autolock lock(mMutex);
543
Tim Murray4a4e4a22016-04-19 16:29:23 +0000544 ALOGV("[%s] addResyncSample(%" PRId64 ")", mName, ns2us(timestamp));
545
Alec Mourif8e689c2019-05-20 18:32:22 -0700546 *periodFlushed = false;
Alec Mouri754c98a2019-03-18 18:53:42 -0700547 const size_t idx = (mFirstResyncSample + mNumResyncSamples) % MAX_RESYNC_SAMPLES;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548 mResyncSamples[idx] = timestamp;
Haixia Shi664339a2015-10-28 13:22:22 -0700549 if (mNumResyncSamples == 0) {
Haixia Shi676b1f62015-10-28 16:19:01 -0700550 mPhase = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000551 ALOGV("[%s] First resync sample: mPeriod = %" PRId64 ", mPhase = 0, "
Lloyd Pique78ce4182018-01-31 16:39:51 -0800552 "mReferenceTime = %" PRId64,
Alec Mouri754c98a2019-03-18 18:53:42 -0700553 mName, ns2us(mPeriod), ns2us(timestamp));
554 } else if (mPendingPeriod > 0) {
555 // mNumResyncSamples > 0, so priorIdx won't overflow
556 const size_t priorIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
557 const nsecs_t lastTimestamp = mResyncSamples[priorIdx];
558
559 const nsecs_t observedVsync = std::abs(timestamp - lastTimestamp);
Alec Mourif8e689c2019-05-20 18:32:22 -0700560 if (std::abs(observedVsync - mPendingPeriod) <= std::abs(observedVsync - mIntendedPeriod)) {
561 // Either the observed vsync is closer to the pending period, (and
562 // thus we detected a period change), or the period change will
563 // no-op. In either case, reset the model and flush the pending
564 // period.
Alec Mouri754c98a2019-03-18 18:53:42 -0700565 resetLocked();
Alec Mourif8e689c2019-05-20 18:32:22 -0700566 mIntendedPeriod = mPendingPeriod;
Alec Mouri754c98a2019-03-18 18:53:42 -0700567 mPeriod = mPendingPeriod;
568 mPendingPeriod = 0;
569 if (mTraceDetailedInfo) {
570 ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
Alec Mourif8e689c2019-05-20 18:32:22 -0700571 ATRACE_INT("DispSync:IntendedPeriod", mIntendedPeriod);
Alec Mouri754c98a2019-03-18 18:53:42 -0700572 }
Alec Mourif8e689c2019-05-20 18:32:22 -0700573 *periodFlushed = true;
Alec Mouri754c98a2019-03-18 18:53:42 -0700574 }
Haixia Shi664339a2015-10-28 13:22:22 -0700575 }
Alec Mouri754c98a2019-03-18 18:53:42 -0700576 // Always update the reference time with the most recent timestamp.
577 mReferenceTime = timestamp;
578 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700579
580 if (mNumResyncSamples < MAX_RESYNC_SAMPLES) {
581 mNumResyncSamples++;
582 } else {
583 mFirstResyncSample = (mFirstResyncSample + 1) % MAX_RESYNC_SAMPLES;
584 }
585
586 updateModelLocked();
587
588 if (mNumResyncSamplesSincePresent++ > MAX_RESYNC_SAMPLES_WITHOUT_PRESENT) {
589 resetErrorLocked();
590 }
591
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800592 if (mIgnorePresentFences) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700593 // If we're ignoring the present fences we have no way to know whether
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594 // or not we're synchronized with the HW vsyncs, so we just request
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700595 // that the HW vsync events be turned on.
596 return true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700597 }
598
Tim Murray4a4e4a22016-04-19 16:29:23 +0000599 // Check against kErrorThreshold / 2 to add some hysteresis before having to
600 // resync again
Alec Mouri754c98a2019-03-18 18:53:42 -0700601 bool modelLocked = mModelUpdated && mError < (kErrorThreshold / 2) && mPendingPeriod == 0;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800602 ALOGV("[%s] addResyncSample returning %s", mName, modelLocked ? "locked" : "unlocked");
Alec Mouri016b8dd2019-04-24 15:16:05 -0700603 if (modelLocked) {
Alec Mourif8e689c2019-05-20 18:32:22 -0700604 *periodFlushed = true;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700605 mThread->lockModel();
606 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000607 return !modelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700608}
609
Alec Mouri016b8dd2019-04-24 15:16:05 -0700610void DispSync::endResync() {
611 mThread->lockModel();
612}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700613
Alec Mouri7355eb22019-03-05 14:19:10 -0800614status_t DispSync::addEventListener(const char* name, nsecs_t phase, Callback* callback,
615 nsecs_t lastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700616 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800617 return mThread->addEventListener(name, phase, callback, lastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700618}
619
Andy McFadden645b1f72014-06-10 14:43:32 -0700620void DispSync::setRefreshSkipCount(int count) {
621 Mutex::Autolock lock(mMutex);
622 ALOGD("setRefreshSkipCount(%d)", count);
623 mRefreshSkipCount = count;
624 updateModelLocked();
Ruchi Kandoif52b3c82014-04-24 16:42:35 -0700625}
626
Alec Mouri7355eb22019-03-05 14:19:10 -0800627status_t DispSync::removeEventListener(Callback* callback, nsecs_t* outLastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700628 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800629 return mThread->removeEventListener(callback, outLastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700630}
631
Dan Stoza84d619e2018-03-28 17:07:36 -0700632status_t DispSync::changePhaseOffset(Callback* callback, nsecs_t phase) {
633 Mutex::Autolock lock(mMutex);
634 return mThread->changePhaseOffset(callback, phase);
635}
636
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700637void DispSync::setPeriod(nsecs_t period) {
638 Mutex::Autolock lock(mMutex);
Alec Mourif8e689c2019-05-20 18:32:22 -0700639
640 const bool pendingPeriodShouldChange =
641 period != mIntendedPeriod || (period == mIntendedPeriod && mPendingPeriod != 0);
642
643 if (pendingPeriodShouldChange) {
644 mPendingPeriod = period;
Alec Mouri754c98a2019-03-18 18:53:42 -0700645 }
Alec Mourif8e689c2019-05-20 18:32:22 -0700646 if (mTraceDetailedInfo) {
647 ATRACE_INT("DispSync:IntendedPeriod", mIntendedPeriod);
648 ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
649 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700650}
651
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700652nsecs_t DispSync::getPeriod() {
653 // lock mutex as mPeriod changes multiple times in updateModelLocked
654 Mutex::Autolock lock(mMutex);
655 return mPeriod;
656}
657
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700658void DispSync::updateModelLocked() {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000659 ALOGV("[%s] updateModelLocked %zu", mName, mNumResyncSamples);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700660 if (mNumResyncSamples >= MIN_RESYNC_SAMPLES_FOR_UPDATE) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000661 ALOGV("[%s] Computing...", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700662 nsecs_t durationSum = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000663 nsecs_t minDuration = INT64_MAX;
664 nsecs_t maxDuration = 0;
Alec Mouri94390a32019-07-16 13:20:19 -0700665 // We skip the first 2 samples because the first vsync duration on some
666 // devices may be much more inaccurate than on other devices, e.g. due
667 // to delays in ramping up from a power collapse. By doing so this
668 // actually increases the accuracy of the DispSync model even though
669 // we're effectively relying on fewer sample points.
670 static constexpr size_t numSamplesSkipped = 2;
671 for (size_t i = numSamplesSkipped; i < mNumResyncSamples; i++) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700672 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
673 size_t prev = (idx + MAX_RESYNC_SAMPLES - 1) % MAX_RESYNC_SAMPLES;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000674 nsecs_t duration = mResyncSamples[idx] - mResyncSamples[prev];
675 durationSum += duration;
676 minDuration = min(minDuration, duration);
677 maxDuration = max(maxDuration, duration);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700678 }
679
Tim Murray4a4e4a22016-04-19 16:29:23 +0000680 // Exclude the min and max from the average
681 durationSum -= minDuration + maxDuration;
Alec Mouri94390a32019-07-16 13:20:19 -0700682 mPeriod = durationSum / (mNumResyncSamples - numSamplesSkipped - 2);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000683
684 ALOGV("[%s] mPeriod = %" PRId64, mName, ns2us(mPeriod));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700685
686 double sampleAvgX = 0;
687 double sampleAvgY = 0;
688 double scale = 2.0 * M_PI / double(mPeriod);
Alec Mouri94390a32019-07-16 13:20:19 -0700689 for (size_t i = numSamplesSkipped; i < mNumResyncSamples; i++) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700690 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
Haixia Shi676b1f62015-10-28 16:19:01 -0700691 nsecs_t sample = mResyncSamples[idx] - mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700692 double samplePhase = double(sample % mPeriod) * scale;
693 sampleAvgX += cos(samplePhase);
694 sampleAvgY += sin(samplePhase);
695 }
696
Alec Mouri94390a32019-07-16 13:20:19 -0700697 sampleAvgX /= double(mNumResyncSamples - numSamplesSkipped);
698 sampleAvgY /= double(mNumResyncSamples - numSamplesSkipped);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700699
700 mPhase = nsecs_t(atan2(sampleAvgY, sampleAvgX) / scale);
701
Tim Murray4a4e4a22016-04-19 16:29:23 +0000702 ALOGV("[%s] mPhase = %" PRId64, mName, ns2us(mPhase));
703
704 if (mPhase < -(mPeriod / 2)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700705 mPhase += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000706 ALOGV("[%s] Adjusting mPhase -> %" PRId64, mName, ns2us(mPhase));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700707 }
708
Andy McFadden645b1f72014-06-10 14:43:32 -0700709 // Artificially inflate the period if requested.
710 mPeriod += mPeriod * mRefreshSkipCount;
711
Haixia Shi676b1f62015-10-28 16:19:01 -0700712 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
713 mModelUpdated = true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700714 }
715}
716
717void DispSync::updateErrorLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700718 if (!mModelUpdated) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700719 return;
720 }
721
Andy McFadden645b1f72014-06-10 14:43:32 -0700722 // Need to compare present fences against the un-adjusted refresh period,
723 // since they might arrive between two events.
724 nsecs_t period = mPeriod / (1 + mRefreshSkipCount);
725
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700726 int numErrSamples = 0;
727 nsecs_t sqErrSum = 0;
728
729 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700730 // Only check for the cached value of signal time to avoid unecessary
731 // syscalls. It is the responsibility of the DispSync owner to
732 // call getSignalTime() periodically so the cache is updated when the
733 // fence signals.
734 nsecs_t time = mPresentFences[i]->getCachedSignalTime();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800735 if (time == Fence::SIGNAL_TIME_PENDING || time == Fence::SIGNAL_TIME_INVALID) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700736 continue;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700737 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700738
739 nsecs_t sample = time - mReferenceTime;
740 if (sample <= mPhase) {
741 continue;
742 }
743
744 nsecs_t sampleErr = (sample - mPhase) % period;
745 if (sampleErr > period / 2) {
746 sampleErr -= period;
747 }
748 sqErrSum += sampleErr * sampleErr;
749 numErrSamples++;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700750 }
751
752 if (numErrSamples > 0) {
753 mError = sqErrSum / numErrSamples;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700754 mZeroErrSamplesCount = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700755 } else {
756 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700757 // Use mod ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT to avoid log spam.
758 mZeroErrSamplesCount++;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800759 ALOGE_IF((mZeroErrSamplesCount % ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT) == 0,
760 "No present times for model error.");
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700761 }
762
Ana Krulec064a82f2018-09-11 16:03:03 -0700763 if (mTraceDetailedInfo) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700764 ATRACE_INT64("DispSync:Error", mError);
765 }
766}
767
768void DispSync::resetErrorLocked() {
769 mPresentSampleOffset = 0;
770 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700771 mZeroErrSamplesCount = 0;
Alec Mourif8e689c2019-05-20 18:32:22 -0700772 if (mTraceDetailedInfo) {
773 ATRACE_INT64("DispSync:Error", mError);
774 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700775 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700776 mPresentFences[i] = FenceTime::NO_FENCE;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700777 }
778}
779
Andy McFadden41d67d72014-04-25 16:58:34 -0700780nsecs_t DispSync::computeNextRefresh(int periodOffset) const {
Andy McFadden150ecd82014-05-08 14:56:50 -0700781 Mutex::Autolock lock(mMutex);
Andy McFadden41d67d72014-04-25 16:58:34 -0700782 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Haixia Shi676b1f62015-10-28 16:19:01 -0700783 nsecs_t phase = mReferenceTime + mPhase;
Marissa Wall17b4e452018-12-26 16:32:34 -0800784 if (mPeriod == 0) {
785 return 0;
786 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700787 return (((now - phase) / mPeriod) + periodOffset + 1) * mPeriod + phase;
Andy McFadden41d67d72014-04-25 16:58:34 -0700788}
789
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700790void DispSync::setIgnorePresentFences(bool ignore) {
791 Mutex::Autolock lock(mMutex);
792 if (mIgnorePresentFences != ignore) {
793 mIgnorePresentFences = ignore;
794 resetLocked();
795 }
796}
797
Yiwei Zhang5434a782018-12-05 18:06:32 -0800798void DispSync::dump(std::string& result) const {
Andy McFaddenc751e922014-05-08 14:53:26 -0700799 Mutex::Autolock lock(mMutex);
Yiwei Zhang5434a782018-12-05 18:06:32 -0800800 StringAppendF(&result, "present fences are %s\n", mIgnorePresentFences ? "ignored" : "used");
801 StringAppendF(&result, "mPeriod: %" PRId64 " ns (%.3f fps; skipCount=%d)\n", mPeriod,
802 1000000000.0 / mPeriod, mRefreshSkipCount);
803 StringAppendF(&result, "mPhase: %" PRId64 " ns\n", mPhase);
804 StringAppendF(&result, "mError: %" PRId64 " ns (sqrt=%.1f)\n", mError, sqrt(mError));
805 StringAppendF(&result, "mNumResyncSamplesSincePresent: %d (limit %d)\n",
806 mNumResyncSamplesSincePresent, MAX_RESYNC_SAMPLES_WITHOUT_PRESENT);
807 StringAppendF(&result, "mNumResyncSamples: %zd (max %d)\n", mNumResyncSamples,
808 MAX_RESYNC_SAMPLES);
Andy McFaddenc751e922014-05-08 14:53:26 -0700809
Yiwei Zhang5434a782018-12-05 18:06:32 -0800810 result.append("mResyncSamples:\n");
Andy McFaddenc751e922014-05-08 14:53:26 -0700811 nsecs_t previous = -1;
812 for (size_t i = 0; i < mNumResyncSamples; i++) {
813 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
814 nsecs_t sampleTime = mResyncSamples[idx];
815 if (i == 0) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800816 StringAppendF(&result, " %" PRId64 "\n", sampleTime);
Andy McFaddenc751e922014-05-08 14:53:26 -0700817 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800818 StringAppendF(&result, " %" PRId64 " (+%" PRId64 ")\n", sampleTime,
819 sampleTime - previous);
Andy McFaddenc751e922014-05-08 14:53:26 -0700820 }
821 previous = sampleTime;
822 }
823
Yiwei Zhang5434a782018-12-05 18:06:32 -0800824 StringAppendF(&result, "mPresentFences [%d]:\n", NUM_PRESENT_SAMPLES);
Andy McFadden5167ec62014-05-22 13:08:43 -0700825 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700826 previous = Fence::SIGNAL_TIME_INVALID;
Andy McFaddenc751e922014-05-08 14:53:26 -0700827 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
828 size_t idx = (i + mPresentSampleOffset) % NUM_PRESENT_SAMPLES;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700829 nsecs_t presentTime = mPresentFences[idx]->getSignalTime();
830 if (presentTime == Fence::SIGNAL_TIME_PENDING) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800831 StringAppendF(&result, " [unsignaled fence]\n");
Lloyd Pique78ce4182018-01-31 16:39:51 -0800832 } else if (presentTime == Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800833 StringAppendF(&result, " [invalid fence]\n");
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700834 } else if (previous == Fence::SIGNAL_TIME_PENDING ||
Lloyd Pique78ce4182018-01-31 16:39:51 -0800835 previous == Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800836 StringAppendF(&result, " %" PRId64 " (%.3f ms ago)\n", presentTime,
837 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700838 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800839 StringAppendF(&result, " %" PRId64 " (+%" PRId64 " / %.3f) (%.3f ms ago)\n",
840 presentTime, presentTime - previous,
841 (presentTime - previous) / (double)mPeriod,
842 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700843 }
844 previous = presentTime;
845 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700846
Yiwei Zhang5434a782018-12-05 18:06:32 -0800847 StringAppendF(&result, "current monotonic time: %" PRId64 "\n", now);
Andy McFaddenc751e922014-05-08 14:53:26 -0700848}
849
Ana Krulec010d2192018-10-08 06:29:54 -0700850nsecs_t DispSync::expectedPresentTime() {
851 // The HWC doesn't currently have a way to report additional latency.
852 // Assume that whatever we submit now will appear right after the flip.
853 // For a smart panel this might be 1. This is expressed in frames,
854 // rather than time, because we expect to have a constant frame delay
855 // regardless of the refresh rate.
856 const uint32_t hwcLatency = 0;
857
858 // Ask DispSync when the next refresh will be (CLOCK_MONOTONIC).
Ana Krulec757f63a2019-01-25 10:46:18 -0800859 return computeNextRefresh(hwcLatency);
Ana Krulec010d2192018-10-08 06:29:54 -0700860}
861
Lloyd Pique41be5d22018-06-21 13:11:48 -0700862} // namespace impl
863
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700864} // namespace android