blob: f7a30af8778574cb9e77c8133f76ecba33d3616b [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 Mouri016b8dd2019-04-24 15:16:05 -070082 if (mReferenceTime != referenceTime) {
83 for (auto& eventListener : mEventListeners) {
84 eventListener.mHasFired = false;
85 }
86 }
Haixia Shi676b1f62015-10-28 16:19:01 -070087 mReferenceTime = referenceTime;
Alec Mouri75b0b622019-03-12 18:56:00 +000088 if (mPeriod != 0 && mPeriod != period && mReferenceTime != 0) {
89 // Inflate the reference time to be the most recent predicted
90 // vsync before the current time.
91 const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
92 const nsecs_t baseTime = now - mReferenceTime;
93 const nsecs_t numOldPeriods = baseTime / mPeriod;
94 mReferenceTime = mReferenceTime + (numOldPeriods)*mPeriod;
95 }
96 mPeriod = period;
Alec Mourif5fe85c2019-02-22 13:40:36 -080097 if (mTraceDetailedInfo) {
98 ATRACE_INT64("DispSync:Period", mPeriod);
99 ATRACE_INT64("DispSync:Phase", mPhase + mPeriod / 2);
100 ATRACE_INT64("DispSync:Reference Time", mReferenceTime);
101 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000102 ALOGV("[%s] updateModel: mPeriod = %" PRId64 ", mPhase = %" PRId64
Lloyd Pique78ce4182018-01-31 16:39:51 -0800103 " mReferenceTime = %" PRId64,
104 mName, ns2us(mPeriod), ns2us(mPhase), ns2us(mReferenceTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700105 mCond.signal();
106 }
107
108 void stop() {
Ana Krulec064a82f2018-09-11 16:03:03 -0700109 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700110 Mutex::Autolock lock(mMutex);
111 mStop = true;
112 mCond.signal();
113 }
114
Alec Mouri016b8dd2019-04-24 15:16:05 -0700115 void lockModel() {
116 Mutex::Autolock lock(mMutex);
117 mModelLocked = true;
Alec Mourif8e689c2019-05-20 18:32:22 -0700118 ATRACE_INT("DispSync:ModelLocked", mModelLocked);
Alec Mouri016b8dd2019-04-24 15:16:05 -0700119 }
120
121 void unlockModel() {
122 Mutex::Autolock lock(mMutex);
123 mModelLocked = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700124 ATRACE_INT("DispSync:ModelLocked", mModelLocked);
Alec Mouri016b8dd2019-04-24 15:16:05 -0700125 }
126
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700127 virtual bool threadLoop() {
128 status_t err;
129 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700130
131 while (true) {
Ana Krulec9a52b192018-07-12 18:18:47 -0400132 std::vector<CallbackInvocation> callbackInvocations;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700133
134 nsecs_t targetTime = 0;
135
136 { // Scope for lock
137 Mutex::Autolock lock(mMutex);
138
Ana Krulec064a82f2018-09-11 16:03:03 -0700139 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000140 ATRACE_INT64("DispSync:Frame", mFrameNumber);
141 }
142 ALOGV("[%s] Frame %" PRId64, mName, mFrameNumber);
143 ++mFrameNumber;
144
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700145 if (mStop) {
146 return false;
147 }
148
149 if (mPeriod == 0) {
150 err = mCond.wait(mMutex);
151 if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800152 ALOGE("error waiting for new events: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700153 return false;
154 }
155 continue;
156 }
157
Dan Stoza8f8374d2016-04-19 10:03:46 -0700158 targetTime = computeNextEventTimeLocked(now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700159
160 bool isWakeup = false;
161
162 if (now < targetTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700163 if (mTraceDetailedInfo) ATRACE_NAME("DispSync waiting");
Dan Stoza8f8374d2016-04-19 10:03:46 -0700164
165 if (targetTime == INT64_MAX) {
166 ALOGV("[%s] Waiting forever", mName);
167 err = mCond.wait(mMutex);
168 } else {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800169 ALOGV("[%s] Waiting until %" PRId64, mName, ns2us(targetTime));
Dan Stoza8f8374d2016-04-19 10:03:46 -0700170 err = mCond.waitRelative(mMutex, targetTime - now);
171 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700172
173 if (err == TIMED_OUT) {
174 isWakeup = true;
175 } else if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800176 ALOGE("error waiting for next event: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700177 return false;
178 }
179 }
180
181 now = systemTime(SYSTEM_TIME_MONOTONIC);
182
Tim Murray4a4e4a22016-04-19 16:29:23 +0000183 // Don't correct by more than 1.5 ms
184 static const nsecs_t kMaxWakeupLatency = us2ns(1500);
185
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700186 if (isWakeup) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800187 mWakeupLatency = ((mWakeupLatency * 63) + (now - targetTime)) / 64;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000188 mWakeupLatency = min(mWakeupLatency, kMaxWakeupLatency);
Ana Krulec064a82f2018-09-11 16:03:03 -0700189 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000190 ATRACE_INT64("DispSync:WakeupLat", now - targetTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700191 ATRACE_INT64("DispSync:AvgWakeupLat", mWakeupLatency);
192 }
193 }
194
195 callbackInvocations = gatherCallbackInvocationsLocked(now);
196 }
197
198 if (callbackInvocations.size() > 0) {
Andy McFadden645b1f72014-06-10 14:43:32 -0700199 fireCallbackInvocations(callbackInvocations);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700200 }
201 }
202
203 return false;
204 }
205
Alec Mouri7355eb22019-03-05 14:19:10 -0800206 status_t addEventListener(const char* name, nsecs_t phase, DispSync::Callback* callback,
207 nsecs_t lastCallbackTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700208 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700209 Mutex::Autolock lock(mMutex);
210
211 for (size_t i = 0; i < mEventListeners.size(); i++) {
212 if (mEventListeners[i].mCallback == callback) {
213 return BAD_VALUE;
214 }
215 }
216
217 EventListener listener;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000218 listener.mName = name;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700219 listener.mPhase = phase;
220 listener.mCallback = callback;
Jamie Gennis629b9872013-10-29 13:36:12 -0700221
222 // We want to allow the firstmost future event to fire without
Alec Mouri81835982019-02-27 13:40:44 -0800223 // allowing any past events to fire. To do this extrapolate from
224 // mReferenceTime the most recent hardware vsync, and pin the
225 // last event time there.
226 const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
227 if (mPeriod != 0) {
228 const nsecs_t baseTime = now - mReferenceTime;
229 const nsecs_t numPeriodsSinceReference = baseTime / mPeriod;
230 const nsecs_t predictedReference = mReferenceTime + numPeriodsSinceReference * mPeriod;
Alec Mouridf3d2e12019-05-02 17:58:46 +0000231 const nsecs_t phaseCorrection = mPhase + listener.mPhase;
232 const nsecs_t predictedLastEventTime = predictedReference + phaseCorrection;
233 if (predictedLastEventTime >= now) {
234 // Make sure that the last event time does not exceed the current time.
235 // If it would, then back the last event time by a period.
236 listener.mLastEventTime = predictedLastEventTime - mPeriod;
237 } else {
238 listener.mLastEventTime = predictedLastEventTime;
Alec Mouri81835982019-02-27 13:40:44 -0800239 }
240 } else {
241 listener.mLastEventTime = now + mPhase - mWakeupLatency;
242 }
Jamie Gennis629b9872013-10-29 13:36:12 -0700243
Alec Mouri7355eb22019-03-05 14:19:10 -0800244 if (lastCallbackTime <= 0) {
245 // If there is no prior callback time, try to infer one based on the
246 // logical last event time.
247 listener.mLastCallbackTime = listener.mLastEventTime + mWakeupLatency;
248 } else {
249 listener.mLastCallbackTime = lastCallbackTime;
250 }
251
Ana Krulec9a52b192018-07-12 18:18:47 -0400252 mEventListeners.push_back(listener);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700253
254 mCond.signal();
255
256 return NO_ERROR;
257 }
258
Alec Mouri7355eb22019-03-05 14:19:10 -0800259 status_t removeEventListener(DispSync::Callback* callback, nsecs_t* outLastCallback) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700260 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700261 Mutex::Autolock lock(mMutex);
262
Ana Krulec9a52b192018-07-12 18:18:47 -0400263 for (std::vector<EventListener>::iterator it = mEventListeners.begin();
264 it != mEventListeners.end(); ++it) {
265 if (it->mCallback == callback) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800266 *outLastCallback = it->mLastCallbackTime;
Ana Krulec9a52b192018-07-12 18:18:47 -0400267 mEventListeners.erase(it);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700268 mCond.signal();
269 return NO_ERROR;
270 }
271 }
272
273 return BAD_VALUE;
274 }
275
Dan Stoza84d619e2018-03-28 17:07:36 -0700276 status_t changePhaseOffset(DispSync::Callback* callback, nsecs_t phase) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700277 if (mTraceDetailedInfo) ATRACE_CALL();
Dan Stoza84d619e2018-03-28 17:07:36 -0700278 Mutex::Autolock lock(mMutex);
279
Ana Krulec9a52b192018-07-12 18:18:47 -0400280 for (auto& eventListener : mEventListeners) {
281 if (eventListener.mCallback == callback) {
282 const nsecs_t oldPhase = eventListener.mPhase;
283 eventListener.mPhase = phase;
Dan Stoza84d619e2018-03-28 17:07:36 -0700284
285 // Pretend that the last time this event was handled at the same frame but with the
286 // new offset to allow for a seamless offset change without double-firing or
287 // skipping.
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200288 nsecs_t diff = oldPhase - phase;
289 if (diff > mPeriod / 2) {
290 diff -= mPeriod;
291 } else if (diff < -mPeriod / 2) {
292 diff += mPeriod;
293 }
Ana Krulec9a52b192018-07-12 18:18:47 -0400294 eventListener.mLastEventTime -= 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;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700309 bool mHasFired = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700310 };
311
312 struct CallbackInvocation {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800313 DispSync::Callback* mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700314 nsecs_t mEventTime;
315 };
316
317 nsecs_t computeNextEventTimeLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700318 if (mTraceDetailedInfo) ATRACE_CALL();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000319 ALOGV("[%s] computeNextEventTimeLocked", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700320 nsecs_t nextEventTime = INT64_MAX;
321 for (size_t i = 0; i < mEventListeners.size(); i++) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800322 nsecs_t t = computeListenerNextEventTimeLocked(mEventListeners[i], now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700323
324 if (t < nextEventTime) {
325 nextEventTime = t;
326 }
327 }
328
Tim Murray4a4e4a22016-04-19 16:29:23 +0000329 ALOGV("[%s] nextEventTime = %" PRId64, mName, ns2us(nextEventTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700330 return nextEventTime;
331 }
332
Alec Mouri7355eb22019-03-05 14:19:10 -0800333 // Sanity check that the duration is close enough in length to a period without
334 // falling into double-rate vsyncs.
Alec Mouridf3d2e12019-05-02 17:58:46 +0000335 bool isCloseToPeriod(nsecs_t duration) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800336 // Ratio of 3/5 is arbitrary, but it must be greater than 1/2.
337 return duration < (3 * mPeriod) / 5;
338 }
339
Ana Krulec9a52b192018-07-12 18:18:47 -0400340 std::vector<CallbackInvocation> gatherCallbackInvocationsLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700341 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800342 ALOGV("[%s] gatherCallbackInvocationsLocked @ %" PRId64, mName, ns2us(now));
Tim Murray4a4e4a22016-04-19 16:29:23 +0000343
Ana Krulec9a52b192018-07-12 18:18:47 -0400344 std::vector<CallbackInvocation> callbackInvocations;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000345 nsecs_t onePeriodAgo = now - mPeriod;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700346
Ana Krulec9a52b192018-07-12 18:18:47 -0400347 for (auto& eventListener : mEventListeners) {
348 nsecs_t t = computeListenerNextEventTimeLocked(eventListener, onePeriodAgo);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700349
Jamie Gennis0d5c60e2013-10-09 17:49:37 -0700350 if (t < now) {
Alec Mouridf3d2e12019-05-02 17:58:46 +0000351 if (isCloseToPeriod(now - eventListener.mLastCallbackTime)) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800352 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800353 ALOGV("[%s] [%s] Skipping event due to model error", mName,
354 eventListener.mName);
355 continue;
356 }
Alec Mouri016b8dd2019-04-24 15:16:05 -0700357 if (eventListener.mHasFired && !mModelLocked) {
358 eventListener.mLastEventTime = t;
359 ALOGV("[%s] [%s] Skipping event due to already firing", mName,
360 eventListener.mName);
361 continue;
362 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700363 CallbackInvocation ci;
Ana Krulec9a52b192018-07-12 18:18:47 -0400364 ci.mCallback = eventListener.mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700365 ci.mEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800366 ALOGV("[%s] [%s] Preparing to fire, latency: %" PRId64, mName, eventListener.mName,
367 t - eventListener.mLastEventTime);
Ana Krulec9a52b192018-07-12 18:18:47 -0400368 callbackInvocations.push_back(ci);
369 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800370 eventListener.mLastCallbackTime = now;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700371 eventListener.mHasFired = true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700372 }
373 }
374
375 return callbackInvocations;
376 }
377
Lloyd Pique78ce4182018-01-31 16:39:51 -0800378 nsecs_t computeListenerNextEventTimeLocked(const EventListener& listener, nsecs_t baseTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700379 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800380 ALOGV("[%s] [%s] computeListenerNextEventTimeLocked(%" PRId64 ")", mName, listener.mName,
381 ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700382
Tim Murray4a4e4a22016-04-19 16:29:23 +0000383 nsecs_t lastEventTime = listener.mLastEventTime + mWakeupLatency;
384 ALOGV("[%s] lastEventTime: %" PRId64, mName, ns2us(lastEventTime));
385 if (baseTime < lastEventTime) {
386 baseTime = lastEventTime;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800387 ALOGV("[%s] Clamping baseTime to lastEventTime -> %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700388 }
389
Tim Murray4a4e4a22016-04-19 16:29:23 +0000390 baseTime -= mReferenceTime;
391 ALOGV("[%s] Relative baseTime = %" PRId64, mName, ns2us(baseTime));
392 nsecs_t phase = mPhase + listener.mPhase;
393 ALOGV("[%s] Phase = %" PRId64, mName, ns2us(phase));
394 baseTime -= phase;
395 ALOGV("[%s] baseTime - phase = %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700396
Tim Murray4a4e4a22016-04-19 16:29:23 +0000397 // If our previous time is before the reference (because the reference
398 // has since been updated), the division by mPeriod will truncate
399 // towards zero instead of computing the floor. Since in all cases
400 // before the reference we want the next time to be effectively now, we
401 // set baseTime to -mPeriod so that numPeriods will be -1.
402 // When we add 1 and the phase, we will be at the correct event time for
403 // this period.
404 if (baseTime < 0) {
405 ALOGV("[%s] Correcting negative baseTime", mName);
406 baseTime = -mPeriod;
407 }
408
409 nsecs_t numPeriods = baseTime / mPeriod;
410 ALOGV("[%s] numPeriods = %" PRId64, mName, numPeriods);
411 nsecs_t t = (numPeriods + 1) * mPeriod + phase;
412 ALOGV("[%s] t = %" PRId64, mName, ns2us(t));
413 t += mReferenceTime;
414 ALOGV("[%s] Absolute t = %" PRId64, mName, ns2us(t));
415
416 // Check that it's been slightly more than half a period since the last
417 // event so that we don't accidentally fall into double-rate vsyncs
Alec Mouridf3d2e12019-05-02 17:58:46 +0000418 if (isCloseToPeriod(t - listener.mLastEventTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700419 t += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000420 ALOGV("[%s] Modifying t -> %" PRId64, mName, ns2us(t));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 }
422
Tim Murray4a4e4a22016-04-19 16:29:23 +0000423 t -= mWakeupLatency;
424 ALOGV("[%s] Corrected for wakeup latency -> %" PRId64, mName, ns2us(t));
425
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700426 return t;
427 }
428
Ana Krulec9a52b192018-07-12 18:18:47 -0400429 void fireCallbackInvocations(const std::vector<CallbackInvocation>& callbacks) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700430 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 for (size_t i = 0; i < callbacks.size(); i++) {
432 callbacks[i].mCallback->onDispSyncEvent(callbacks[i].mEventTime);
433 }
434 }
435
Tim Murray4a4e4a22016-04-19 16:29:23 +0000436 const char* const mName;
437
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 bool mStop;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700439 bool mModelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700440
441 nsecs_t mPeriod;
442 nsecs_t mPhase;
Haixia Shi676b1f62015-10-28 16:19:01 -0700443 nsecs_t mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700444 nsecs_t mWakeupLatency;
445
Tim Murray4a4e4a22016-04-19 16:29:23 +0000446 int64_t mFrameNumber;
447
Ana Krulec9a52b192018-07-12 18:18:47 -0400448 std::vector<EventListener> mEventListeners;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700449
450 Mutex mMutex;
451 Condition mCond;
Ana Krulec064a82f2018-09-11 16:03:03 -0700452
453 // Flag to turn on logging in systrace.
454 const bool mTraceDetailedInfo;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700455};
456
Tim Murray4a4e4a22016-04-19 16:29:23 +0000457#undef LOG_TAG
458#define LOG_TAG "DispSync"
459
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700460class ZeroPhaseTracer : public DispSync::Callback {
461public:
462 ZeroPhaseTracer() : mParity(false) {}
463
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700464 virtual void onDispSyncEvent(nsecs_t /*when*/) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700465 mParity = !mParity;
466 ATRACE_INT("ZERO_PHASE_VSYNC", mParity ? 1 : 0);
467 }
468
469private:
470 bool mParity;
471};
472
Ana Krulec064a82f2018-09-11 16:03:03 -0700473DispSync::DispSync(const char* name) : mName(name), mRefreshSkipCount(0) {
474 // This flag offers the ability to turn on systrace logging from the shell.
475 char value[PROPERTY_VALUE_MAX];
476 property_get("debug.sf.dispsync_trace_detailed_info", value, "0");
477 mTraceDetailedInfo = atoi(value);
478 mThread = new DispSyncThread(name, mTraceDetailedInfo);
479}
Andy McFadden645b1f72014-06-10 14:43:32 -0700480
Ady Abraham50c202a2019-03-14 11:44:38 -0700481DispSync::~DispSync() {
482 mThread->stop();
483 mThread->requestExitAndWait();
484}
Saurabh Shahf4174532017-07-13 10:45:07 -0700485
486void DispSync::init(bool hasSyncFramework, int64_t dispSyncPresentTimeOffset) {
487 mIgnorePresentFences = !hasSyncFramework;
488 mPresentTimeOffset = dispSyncPresentTimeOffset;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700489 mThread->run("DispSync", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
Saurabh Shahf4174532017-07-13 10:45:07 -0700490
Tim Murrayacff43d2016-07-29 13:57:24 -0700491 // set DispSync to SCHED_FIFO to minimize jitter
492 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700493 param.sched_priority = 2;
Tim Murrayacff43d2016-07-29 13:57:24 -0700494 if (sched_setscheduler(mThread->getTid(), SCHED_FIFO, &param) != 0) {
495 ALOGE("Couldn't set SCHED_FIFO for DispSyncThread");
496 }
497
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498 beginResync();
499
Ana Krulec064a82f2018-09-11 16:03:03 -0700500 if (mTraceDetailedInfo && kEnableZeroPhaseTracer) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700501 mZeroPhaseTracer = std::make_unique<ZeroPhaseTracer>();
Alec Mouri7355eb22019-03-05 14:19:10 -0800502 addEventListener("ZeroPhaseTracer", 0, mZeroPhaseTracer.get(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700503 }
504}
505
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700506void DispSync::reset() {
507 Mutex::Autolock lock(mMutex);
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700508 resetLocked();
509}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700511void DispSync::resetLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700512 mPhase = 0;
Alec Mouri75b0b622019-03-12 18:56:00 +0000513 const size_t lastSampleIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
514 // Keep the most recent sample, when we resync to hardware we'll overwrite this
515 // with a more accurate signal
516 if (mResyncSamples[lastSampleIdx] != 0) {
517 mReferenceTime = mResyncSamples[lastSampleIdx];
518 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700519 mModelUpdated = false;
Alec Mouri75b0b622019-03-12 18:56:00 +0000520 for (size_t i = 0; i < MAX_RESYNC_SAMPLES; i++) {
521 mResyncSamples[i] = 0;
522 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523 mNumResyncSamples = 0;
524 mFirstResyncSample = 0;
525 mNumResyncSamplesSincePresent = 0;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700526 mThread->unlockModel();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 resetErrorLocked();
528}
529
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700530bool DispSync::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 Mutex::Autolock lock(mMutex);
532
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700533 if (mIgnorePresentFences) {
534 return true;
535 }
536
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700537 mPresentFences[mPresentSampleOffset] = fenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700538 mPresentSampleOffset = (mPresentSampleOffset + 1) % NUM_PRESENT_SAMPLES;
539 mNumResyncSamplesSincePresent = 0;
540
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541 updateErrorLocked();
542
Haixia Shi676b1f62015-10-28 16:19:01 -0700543 return !mModelUpdated || mError > kErrorThreshold;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544}
545
546void DispSync::beginResync() {
547 Mutex::Autolock lock(mMutex);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000548 ALOGV("[%s] beginResync", mName);
Alec Mourif8e689c2019-05-20 18:32:22 -0700549 resetLocked();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550}
551
Alec Mourif8e689c2019-05-20 18:32:22 -0700552bool DispSync::addResyncSample(nsecs_t timestamp, bool* periodFlushed) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700553 Mutex::Autolock lock(mMutex);
554
Tim Murray4a4e4a22016-04-19 16:29:23 +0000555 ALOGV("[%s] addResyncSample(%" PRId64 ")", mName, ns2us(timestamp));
556
Alec Mourif8e689c2019-05-20 18:32:22 -0700557 *periodFlushed = false;
Alec Mouri754c98a2019-03-18 18:53:42 -0700558 const size_t idx = (mFirstResyncSample + mNumResyncSamples) % MAX_RESYNC_SAMPLES;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700559 mResyncSamples[idx] = timestamp;
Haixia Shi664339a2015-10-28 13:22:22 -0700560 if (mNumResyncSamples == 0) {
Haixia Shi676b1f62015-10-28 16:19:01 -0700561 mPhase = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000562 ALOGV("[%s] First resync sample: mPeriod = %" PRId64 ", mPhase = 0, "
Lloyd Pique78ce4182018-01-31 16:39:51 -0800563 "mReferenceTime = %" PRId64,
Alec Mouri754c98a2019-03-18 18:53:42 -0700564 mName, ns2us(mPeriod), ns2us(timestamp));
565 } else if (mPendingPeriod > 0) {
566 // mNumResyncSamples > 0, so priorIdx won't overflow
567 const size_t priorIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
568 const nsecs_t lastTimestamp = mResyncSamples[priorIdx];
569
570 const nsecs_t observedVsync = std::abs(timestamp - lastTimestamp);
Alec Mourif8e689c2019-05-20 18:32:22 -0700571 if (std::abs(observedVsync - mPendingPeriod) <= std::abs(observedVsync - mIntendedPeriod)) {
572 // Either the observed vsync is closer to the pending period, (and
573 // thus we detected a period change), or the period change will
574 // no-op. In either case, reset the model and flush the pending
575 // period.
Alec Mouri754c98a2019-03-18 18:53:42 -0700576 resetLocked();
Alec Mourif8e689c2019-05-20 18:32:22 -0700577 mIntendedPeriod = mPendingPeriod;
Alec Mouri754c98a2019-03-18 18:53:42 -0700578 mPeriod = mPendingPeriod;
579 mPendingPeriod = 0;
580 if (mTraceDetailedInfo) {
581 ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
Alec Mourif8e689c2019-05-20 18:32:22 -0700582 ATRACE_INT("DispSync:IntendedPeriod", mIntendedPeriod);
Alec Mouri754c98a2019-03-18 18:53:42 -0700583 }
Alec Mourif8e689c2019-05-20 18:32:22 -0700584 *periodFlushed = true;
Alec Mouri754c98a2019-03-18 18:53:42 -0700585 }
Haixia Shi664339a2015-10-28 13:22:22 -0700586 }
Alec Mouri754c98a2019-03-18 18:53:42 -0700587 // Always update the reference time with the most recent timestamp.
588 mReferenceTime = timestamp;
589 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700590
591 if (mNumResyncSamples < MAX_RESYNC_SAMPLES) {
592 mNumResyncSamples++;
593 } else {
594 mFirstResyncSample = (mFirstResyncSample + 1) % MAX_RESYNC_SAMPLES;
595 }
596
597 updateModelLocked();
598
599 if (mNumResyncSamplesSincePresent++ > MAX_RESYNC_SAMPLES_WITHOUT_PRESENT) {
600 resetErrorLocked();
601 }
602
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800603 if (mIgnorePresentFences) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700604 // If we're ignoring the present fences we have no way to know whether
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700605 // or not we're synchronized with the HW vsyncs, so we just request
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700606 // that the HW vsync events be turned on.
607 return true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700608 }
609
Tim Murray4a4e4a22016-04-19 16:29:23 +0000610 // Check against kErrorThreshold / 2 to add some hysteresis before having to
611 // resync again
Alec Mouri754c98a2019-03-18 18:53:42 -0700612 bool modelLocked = mModelUpdated && mError < (kErrorThreshold / 2) && mPendingPeriod == 0;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800613 ALOGV("[%s] addResyncSample returning %s", mName, modelLocked ? "locked" : "unlocked");
Alec Mouri016b8dd2019-04-24 15:16:05 -0700614 if (modelLocked) {
Alec Mourif8e689c2019-05-20 18:32:22 -0700615 *periodFlushed = true;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700616 mThread->lockModel();
617 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000618 return !modelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700619}
620
Alec Mouri016b8dd2019-04-24 15:16:05 -0700621void DispSync::endResync() {
622 mThread->lockModel();
623}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700624
Alec Mouri7355eb22019-03-05 14:19:10 -0800625status_t DispSync::addEventListener(const char* name, nsecs_t phase, Callback* callback,
626 nsecs_t lastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700627 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800628 return mThread->addEventListener(name, phase, callback, lastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700629}
630
Andy McFadden645b1f72014-06-10 14:43:32 -0700631void DispSync::setRefreshSkipCount(int count) {
632 Mutex::Autolock lock(mMutex);
633 ALOGD("setRefreshSkipCount(%d)", count);
634 mRefreshSkipCount = count;
635 updateModelLocked();
Ruchi Kandoif52b3c82014-04-24 16:42:35 -0700636}
637
Alec Mouri7355eb22019-03-05 14:19:10 -0800638status_t DispSync::removeEventListener(Callback* callback, nsecs_t* outLastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700639 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800640 return mThread->removeEventListener(callback, outLastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700641}
642
Dan Stoza84d619e2018-03-28 17:07:36 -0700643status_t DispSync::changePhaseOffset(Callback* callback, nsecs_t phase) {
644 Mutex::Autolock lock(mMutex);
645 return mThread->changePhaseOffset(callback, phase);
646}
647
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700648void DispSync::setPeriod(nsecs_t period) {
649 Mutex::Autolock lock(mMutex);
Alec Mourif8e689c2019-05-20 18:32:22 -0700650
651 const bool pendingPeriodShouldChange =
652 period != mIntendedPeriod || (period == mIntendedPeriod && mPendingPeriod != 0);
653
654 if (pendingPeriodShouldChange) {
655 mPendingPeriod = period;
Alec Mouri754c98a2019-03-18 18:53:42 -0700656 }
Alec Mourif8e689c2019-05-20 18:32:22 -0700657 if (mTraceDetailedInfo) {
658 ATRACE_INT("DispSync:IntendedPeriod", mIntendedPeriod);
659 ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
660 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700661}
662
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700663nsecs_t DispSync::getPeriod() {
664 // lock mutex as mPeriod changes multiple times in updateModelLocked
665 Mutex::Autolock lock(mMutex);
666 return mPeriod;
667}
668
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700669void DispSync::updateModelLocked() {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000670 ALOGV("[%s] updateModelLocked %zu", mName, mNumResyncSamples);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700671 if (mNumResyncSamples >= MIN_RESYNC_SAMPLES_FOR_UPDATE) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000672 ALOGV("[%s] Computing...", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700673 nsecs_t durationSum = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000674 nsecs_t minDuration = INT64_MAX;
675 nsecs_t maxDuration = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700676 for (size_t i = 1; i < mNumResyncSamples; i++) {
677 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
678 size_t prev = (idx + MAX_RESYNC_SAMPLES - 1) % MAX_RESYNC_SAMPLES;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000679 nsecs_t duration = mResyncSamples[idx] - mResyncSamples[prev];
680 durationSum += duration;
681 minDuration = min(minDuration, duration);
682 maxDuration = max(maxDuration, duration);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700683 }
684
Tim Murray4a4e4a22016-04-19 16:29:23 +0000685 // Exclude the min and max from the average
686 durationSum -= minDuration + maxDuration;
David Sodman1afa8b02018-10-15 11:20:48 -0700687 mPeriod = durationSum / (mNumResyncSamples - 3);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000688
689 ALOGV("[%s] mPeriod = %" PRId64, mName, ns2us(mPeriod));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700690
691 double sampleAvgX = 0;
692 double sampleAvgY = 0;
693 double scale = 2.0 * M_PI / double(mPeriod);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000694 // Intentionally skip the first sample
695 for (size_t i = 1; i < mNumResyncSamples; i++) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700696 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
Haixia Shi676b1f62015-10-28 16:19:01 -0700697 nsecs_t sample = mResyncSamples[idx] - mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700698 double samplePhase = double(sample % mPeriod) * scale;
699 sampleAvgX += cos(samplePhase);
700 sampleAvgY += sin(samplePhase);
701 }
702
Tim Murray4a4e4a22016-04-19 16:29:23 +0000703 sampleAvgX /= double(mNumResyncSamples - 1);
704 sampleAvgY /= double(mNumResyncSamples - 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700705
706 mPhase = nsecs_t(atan2(sampleAvgY, sampleAvgX) / scale);
707
Tim Murray4a4e4a22016-04-19 16:29:23 +0000708 ALOGV("[%s] mPhase = %" PRId64, mName, ns2us(mPhase));
709
710 if (mPhase < -(mPeriod / 2)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700711 mPhase += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000712 ALOGV("[%s] Adjusting mPhase -> %" PRId64, mName, ns2us(mPhase));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700713 }
714
Andy McFadden645b1f72014-06-10 14:43:32 -0700715 // Artificially inflate the period if requested.
716 mPeriod += mPeriod * mRefreshSkipCount;
717
Haixia Shi676b1f62015-10-28 16:19:01 -0700718 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
719 mModelUpdated = true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700720 }
721}
722
723void DispSync::updateErrorLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700724 if (!mModelUpdated) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700725 return;
726 }
727
Andy McFadden645b1f72014-06-10 14:43:32 -0700728 // Need to compare present fences against the un-adjusted refresh period,
729 // since they might arrive between two events.
730 nsecs_t period = mPeriod / (1 + mRefreshSkipCount);
731
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700732 int numErrSamples = 0;
733 nsecs_t sqErrSum = 0;
734
735 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700736 // Only check for the cached value of signal time to avoid unecessary
737 // syscalls. It is the responsibility of the DispSync owner to
738 // call getSignalTime() periodically so the cache is updated when the
739 // fence signals.
740 nsecs_t time = mPresentFences[i]->getCachedSignalTime();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800741 if (time == Fence::SIGNAL_TIME_PENDING || time == Fence::SIGNAL_TIME_INVALID) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700742 continue;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700743 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700744
745 nsecs_t sample = time - mReferenceTime;
746 if (sample <= mPhase) {
747 continue;
748 }
749
750 nsecs_t sampleErr = (sample - mPhase) % period;
751 if (sampleErr > period / 2) {
752 sampleErr -= period;
753 }
754 sqErrSum += sampleErr * sampleErr;
755 numErrSamples++;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700756 }
757
758 if (numErrSamples > 0) {
759 mError = sqErrSum / numErrSamples;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700760 mZeroErrSamplesCount = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700761 } else {
762 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700763 // Use mod ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT to avoid log spam.
764 mZeroErrSamplesCount++;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800765 ALOGE_IF((mZeroErrSamplesCount % ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT) == 0,
766 "No present times for model error.");
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700767 }
768
Ana Krulec064a82f2018-09-11 16:03:03 -0700769 if (mTraceDetailedInfo) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700770 ATRACE_INT64("DispSync:Error", mError);
771 }
772}
773
774void DispSync::resetErrorLocked() {
775 mPresentSampleOffset = 0;
776 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700777 mZeroErrSamplesCount = 0;
Alec Mourif8e689c2019-05-20 18:32:22 -0700778 if (mTraceDetailedInfo) {
779 ATRACE_INT64("DispSync:Error", mError);
780 }
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