blob: 95ff9d0c736124cc2940bfcc9632be397df801d6 [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) {
95 eventListener.mHasFired = false;
96 eventListener.mLastEventTime =
97 mReferenceTime - mPeriod + mPhase + eventListener.mPhase;
98 }
99 }
Alec Mourif5fe85c2019-02-22 13:40:36 -0800100 if (mTraceDetailedInfo) {
101 ATRACE_INT64("DispSync:Period", mPeriod);
102 ATRACE_INT64("DispSync:Phase", mPhase + mPeriod / 2);
103 ATRACE_INT64("DispSync:Reference Time", mReferenceTime);
104 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000105 ALOGV("[%s] updateModel: mPeriod = %" PRId64 ", mPhase = %" PRId64
Lloyd Pique78ce4182018-01-31 16:39:51 -0800106 " mReferenceTime = %" PRId64,
107 mName, ns2us(mPeriod), ns2us(mPhase), ns2us(mReferenceTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108 mCond.signal();
109 }
110
111 void stop() {
Ana Krulec064a82f2018-09-11 16:03:03 -0700112 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700113 Mutex::Autolock lock(mMutex);
114 mStop = true;
115 mCond.signal();
116 }
117
Alec Mouri016b8dd2019-04-24 15:16:05 -0700118 void lockModel() {
119 Mutex::Autolock lock(mMutex);
120 mModelLocked = true;
Alec Mourif8e689c2019-05-20 18:32:22 -0700121 ATRACE_INT("DispSync:ModelLocked", mModelLocked);
Alec Mouri016b8dd2019-04-24 15:16:05 -0700122 }
123
124 void unlockModel() {
125 Mutex::Autolock lock(mMutex);
Alec Mouric3a482d2019-05-21 00:51:01 -0700126 if (mModelLocked) {
127 for (auto& eventListener : mEventListeners) {
128 if (eventListener.mLastEventTime > mReferenceTime) {
129 eventListener.mHasFired = true;
130 }
131 }
132 }
Alec Mouri016b8dd2019-04-24 15:16:05 -0700133 mModelLocked = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700134 ATRACE_INT("DispSync:ModelLocked", mModelLocked);
Alec Mouri016b8dd2019-04-24 15:16:05 -0700135 }
136
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700137 virtual bool threadLoop() {
138 status_t err;
139 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700140
141 while (true) {
Ana Krulec9a52b192018-07-12 18:18:47 -0400142 std::vector<CallbackInvocation> callbackInvocations;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700143
144 nsecs_t targetTime = 0;
145
146 { // Scope for lock
147 Mutex::Autolock lock(mMutex);
148
Ana Krulec064a82f2018-09-11 16:03:03 -0700149 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000150 ATRACE_INT64("DispSync:Frame", mFrameNumber);
151 }
152 ALOGV("[%s] Frame %" PRId64, mName, mFrameNumber);
153 ++mFrameNumber;
154
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700155 if (mStop) {
156 return false;
157 }
158
159 if (mPeriod == 0) {
160 err = mCond.wait(mMutex);
161 if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800162 ALOGE("error waiting for new events: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700163 return false;
164 }
165 continue;
166 }
167
Dan Stoza8f8374d2016-04-19 10:03:46 -0700168 targetTime = computeNextEventTimeLocked(now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700169
170 bool isWakeup = false;
171
172 if (now < targetTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700173 if (mTraceDetailedInfo) ATRACE_NAME("DispSync waiting");
Dan Stoza8f8374d2016-04-19 10:03:46 -0700174
175 if (targetTime == INT64_MAX) {
176 ALOGV("[%s] Waiting forever", mName);
177 err = mCond.wait(mMutex);
178 } else {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800179 ALOGV("[%s] Waiting until %" PRId64, mName, ns2us(targetTime));
Dan Stoza8f8374d2016-04-19 10:03:46 -0700180 err = mCond.waitRelative(mMutex, targetTime - now);
181 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700182
183 if (err == TIMED_OUT) {
184 isWakeup = true;
185 } else if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800186 ALOGE("error waiting for next event: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700187 return false;
188 }
189 }
190
191 now = systemTime(SYSTEM_TIME_MONOTONIC);
192
Tim Murray4a4e4a22016-04-19 16:29:23 +0000193 // Don't correct by more than 1.5 ms
194 static const nsecs_t kMaxWakeupLatency = us2ns(1500);
195
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700196 if (isWakeup) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800197 mWakeupLatency = ((mWakeupLatency * 63) + (now - targetTime)) / 64;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000198 mWakeupLatency = min(mWakeupLatency, kMaxWakeupLatency);
Ana Krulec064a82f2018-09-11 16:03:03 -0700199 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000200 ATRACE_INT64("DispSync:WakeupLat", now - targetTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700201 ATRACE_INT64("DispSync:AvgWakeupLat", mWakeupLatency);
202 }
203 }
204
205 callbackInvocations = gatherCallbackInvocationsLocked(now);
206 }
207
208 if (callbackInvocations.size() > 0) {
Andy McFadden645b1f72014-06-10 14:43:32 -0700209 fireCallbackInvocations(callbackInvocations);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700210 }
211 }
212
213 return false;
214 }
215
Alec Mouri7355eb22019-03-05 14:19:10 -0800216 status_t addEventListener(const char* name, nsecs_t phase, DispSync::Callback* callback,
217 nsecs_t lastCallbackTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700218 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700219 Mutex::Autolock lock(mMutex);
220
221 for (size_t i = 0; i < mEventListeners.size(); i++) {
222 if (mEventListeners[i].mCallback == callback) {
223 return BAD_VALUE;
224 }
225 }
226
227 EventListener listener;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000228 listener.mName = name;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700229 listener.mPhase = phase;
230 listener.mCallback = callback;
Jamie Gennis629b9872013-10-29 13:36:12 -0700231
232 // We want to allow the firstmost future event to fire without
Alec Mouri81835982019-02-27 13:40:44 -0800233 // allowing any past events to fire. To do this extrapolate from
234 // mReferenceTime the most recent hardware vsync, and pin the
235 // last event time there.
236 const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
237 if (mPeriod != 0) {
238 const nsecs_t baseTime = now - mReferenceTime;
239 const nsecs_t numPeriodsSinceReference = baseTime / mPeriod;
240 const nsecs_t predictedReference = mReferenceTime + numPeriodsSinceReference * mPeriod;
Alec Mouridf3d2e12019-05-02 17:58:46 +0000241 const nsecs_t phaseCorrection = mPhase + listener.mPhase;
242 const nsecs_t predictedLastEventTime = predictedReference + phaseCorrection;
243 if (predictedLastEventTime >= now) {
244 // Make sure that the last event time does not exceed the current time.
245 // If it would, then back the last event time by a period.
246 listener.mLastEventTime = predictedLastEventTime - mPeriod;
247 } else {
248 listener.mLastEventTime = predictedLastEventTime;
Alec Mouri81835982019-02-27 13:40:44 -0800249 }
250 } else {
251 listener.mLastEventTime = now + mPhase - mWakeupLatency;
252 }
Jamie Gennis629b9872013-10-29 13:36:12 -0700253
Alec Mouri7355eb22019-03-05 14:19:10 -0800254 if (lastCallbackTime <= 0) {
255 // If there is no prior callback time, try to infer one based on the
256 // logical last event time.
257 listener.mLastCallbackTime = listener.mLastEventTime + mWakeupLatency;
258 } else {
259 listener.mLastCallbackTime = lastCallbackTime;
260 }
261
Alec Mouric3a482d2019-05-21 00:51:01 -0700262 if (!mModelLocked && listener.mLastEventTime > mReferenceTime) {
263 listener.mHasFired = true;
264 }
265
Ana Krulec9a52b192018-07-12 18:18:47 -0400266 mEventListeners.push_back(listener);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700267
268 mCond.signal();
269
270 return NO_ERROR;
271 }
272
Alec Mouri7355eb22019-03-05 14:19:10 -0800273 status_t removeEventListener(DispSync::Callback* callback, nsecs_t* outLastCallback) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700274 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700275 Mutex::Autolock lock(mMutex);
276
Ana Krulec9a52b192018-07-12 18:18:47 -0400277 for (std::vector<EventListener>::iterator it = mEventListeners.begin();
278 it != mEventListeners.end(); ++it) {
279 if (it->mCallback == callback) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800280 *outLastCallback = it->mLastCallbackTime;
Ana Krulec9a52b192018-07-12 18:18:47 -0400281 mEventListeners.erase(it);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700282 mCond.signal();
283 return NO_ERROR;
284 }
285 }
286
287 return BAD_VALUE;
288 }
289
Dan Stoza84d619e2018-03-28 17:07:36 -0700290 status_t changePhaseOffset(DispSync::Callback* callback, nsecs_t phase) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700291 if (mTraceDetailedInfo) ATRACE_CALL();
Dan Stoza84d619e2018-03-28 17:07:36 -0700292 Mutex::Autolock lock(mMutex);
293
Ana Krulec9a52b192018-07-12 18:18:47 -0400294 for (auto& eventListener : mEventListeners) {
295 if (eventListener.mCallback == callback) {
296 const nsecs_t oldPhase = eventListener.mPhase;
297 eventListener.mPhase = phase;
Dan Stoza84d619e2018-03-28 17:07:36 -0700298
299 // Pretend that the last time this event was handled at the same frame but with the
300 // new offset to allow for a seamless offset change without double-firing or
301 // skipping.
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200302 nsecs_t diff = oldPhase - phase;
303 if (diff > mPeriod / 2) {
304 diff -= mPeriod;
305 } else if (diff < -mPeriod / 2) {
306 diff += mPeriod;
307 }
Ana Krulec9a52b192018-07-12 18:18:47 -0400308 eventListener.mLastEventTime -= diff;
Dan Stoza84d619e2018-03-28 17:07:36 -0700309 mCond.signal();
310 return NO_ERROR;
311 }
312 }
Dan Stoza84d619e2018-03-28 17:07:36 -0700313 return BAD_VALUE;
314 }
315
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700316private:
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700317 struct EventListener {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000318 const char* mName;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700319 nsecs_t mPhase;
320 nsecs_t mLastEventTime;
Alec Mouri7355eb22019-03-05 14:19:10 -0800321 nsecs_t mLastCallbackTime;
Lloyd Piquee83f9312018-02-01 12:53:17 -0800322 DispSync::Callback* mCallback;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700323 bool mHasFired = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700324 };
325
326 struct CallbackInvocation {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800327 DispSync::Callback* mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700328 nsecs_t mEventTime;
329 };
330
331 nsecs_t computeNextEventTimeLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700332 if (mTraceDetailedInfo) ATRACE_CALL();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000333 ALOGV("[%s] computeNextEventTimeLocked", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700334 nsecs_t nextEventTime = INT64_MAX;
335 for (size_t i = 0; i < mEventListeners.size(); i++) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800336 nsecs_t t = computeListenerNextEventTimeLocked(mEventListeners[i], now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700337
338 if (t < nextEventTime) {
339 nextEventTime = t;
340 }
341 }
342
Tim Murray4a4e4a22016-04-19 16:29:23 +0000343 ALOGV("[%s] nextEventTime = %" PRId64, mName, ns2us(nextEventTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700344 return nextEventTime;
345 }
346
Alec Mouri7355eb22019-03-05 14:19:10 -0800347 // Sanity check that the duration is close enough in length to a period without
348 // falling into double-rate vsyncs.
Alec Mouridf3d2e12019-05-02 17:58:46 +0000349 bool isCloseToPeriod(nsecs_t duration) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800350 // Ratio of 3/5 is arbitrary, but it must be greater than 1/2.
351 return duration < (3 * mPeriod) / 5;
352 }
353
Ana Krulec9a52b192018-07-12 18:18:47 -0400354 std::vector<CallbackInvocation> gatherCallbackInvocationsLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700355 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800356 ALOGV("[%s] gatherCallbackInvocationsLocked @ %" PRId64, mName, ns2us(now));
Tim Murray4a4e4a22016-04-19 16:29:23 +0000357
Ana Krulec9a52b192018-07-12 18:18:47 -0400358 std::vector<CallbackInvocation> callbackInvocations;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000359 nsecs_t onePeriodAgo = now - mPeriod;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700360
Ana Krulec9a52b192018-07-12 18:18:47 -0400361 for (auto& eventListener : mEventListeners) {
362 nsecs_t t = computeListenerNextEventTimeLocked(eventListener, onePeriodAgo);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700363
Jamie Gennis0d5c60e2013-10-09 17:49:37 -0700364 if (t < now) {
Alec Mouridf3d2e12019-05-02 17:58:46 +0000365 if (isCloseToPeriod(now - eventListener.mLastCallbackTime)) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800366 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800367 ALOGV("[%s] [%s] Skipping event due to model error", mName,
368 eventListener.mName);
369 continue;
370 }
Alec Mouri016b8dd2019-04-24 15:16:05 -0700371 if (eventListener.mHasFired && !mModelLocked) {
372 eventListener.mLastEventTime = t;
373 ALOGV("[%s] [%s] Skipping event due to already firing", mName,
374 eventListener.mName);
375 continue;
376 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700377 CallbackInvocation ci;
Ana Krulec9a52b192018-07-12 18:18:47 -0400378 ci.mCallback = eventListener.mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700379 ci.mEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800380 ALOGV("[%s] [%s] Preparing to fire, latency: %" PRId64, mName, eventListener.mName,
381 t - eventListener.mLastEventTime);
Ana Krulec9a52b192018-07-12 18:18:47 -0400382 callbackInvocations.push_back(ci);
383 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800384 eventListener.mLastCallbackTime = now;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700385 eventListener.mHasFired = true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700386 }
387 }
388
389 return callbackInvocations;
390 }
391
Lloyd Pique78ce4182018-01-31 16:39:51 -0800392 nsecs_t computeListenerNextEventTimeLocked(const EventListener& listener, nsecs_t baseTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700393 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800394 ALOGV("[%s] [%s] computeListenerNextEventTimeLocked(%" PRId64 ")", mName, listener.mName,
395 ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700396
Tim Murray4a4e4a22016-04-19 16:29:23 +0000397 nsecs_t lastEventTime = listener.mLastEventTime + mWakeupLatency;
398 ALOGV("[%s] lastEventTime: %" PRId64, mName, ns2us(lastEventTime));
399 if (baseTime < lastEventTime) {
400 baseTime = lastEventTime;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800401 ALOGV("[%s] Clamping baseTime to lastEventTime -> %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700402 }
403
Tim Murray4a4e4a22016-04-19 16:29:23 +0000404 baseTime -= mReferenceTime;
405 ALOGV("[%s] Relative baseTime = %" PRId64, mName, ns2us(baseTime));
406 nsecs_t phase = mPhase + listener.mPhase;
407 ALOGV("[%s] Phase = %" PRId64, mName, ns2us(phase));
408 baseTime -= phase;
409 ALOGV("[%s] baseTime - phase = %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700410
Tim Murray4a4e4a22016-04-19 16:29:23 +0000411 // If our previous time is before the reference (because the reference
412 // has since been updated), the division by mPeriod will truncate
413 // towards zero instead of computing the floor. Since in all cases
414 // before the reference we want the next time to be effectively now, we
415 // set baseTime to -mPeriod so that numPeriods will be -1.
416 // When we add 1 and the phase, we will be at the correct event time for
417 // this period.
418 if (baseTime < 0) {
419 ALOGV("[%s] Correcting negative baseTime", mName);
420 baseTime = -mPeriod;
421 }
422
423 nsecs_t numPeriods = baseTime / mPeriod;
424 ALOGV("[%s] numPeriods = %" PRId64, mName, numPeriods);
425 nsecs_t t = (numPeriods + 1) * mPeriod + phase;
426 ALOGV("[%s] t = %" PRId64, mName, ns2us(t));
427 t += mReferenceTime;
428 ALOGV("[%s] Absolute t = %" PRId64, mName, ns2us(t));
429
430 // Check that it's been slightly more than half a period since the last
431 // event so that we don't accidentally fall into double-rate vsyncs
Alec Mouridf3d2e12019-05-02 17:58:46 +0000432 if (isCloseToPeriod(t - listener.mLastEventTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700433 t += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000434 ALOGV("[%s] Modifying t -> %" PRId64, mName, ns2us(t));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700435 }
436
Tim Murray4a4e4a22016-04-19 16:29:23 +0000437 t -= mWakeupLatency;
438 ALOGV("[%s] Corrected for wakeup latency -> %" PRId64, mName, ns2us(t));
439
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700440 return t;
441 }
442
Ana Krulec9a52b192018-07-12 18:18:47 -0400443 void fireCallbackInvocations(const std::vector<CallbackInvocation>& callbacks) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700444 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700445 for (size_t i = 0; i < callbacks.size(); i++) {
446 callbacks[i].mCallback->onDispSyncEvent(callbacks[i].mEventTime);
447 }
448 }
449
Tim Murray4a4e4a22016-04-19 16:29:23 +0000450 const char* const mName;
451
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 bool mStop;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700453 bool mModelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454
455 nsecs_t mPeriod;
456 nsecs_t mPhase;
Haixia Shi676b1f62015-10-28 16:19:01 -0700457 nsecs_t mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 nsecs_t mWakeupLatency;
459
Tim Murray4a4e4a22016-04-19 16:29:23 +0000460 int64_t mFrameNumber;
461
Ana Krulec9a52b192018-07-12 18:18:47 -0400462 std::vector<EventListener> mEventListeners;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463
464 Mutex mMutex;
465 Condition mCond;
Ana Krulec064a82f2018-09-11 16:03:03 -0700466
467 // Flag to turn on logging in systrace.
468 const bool mTraceDetailedInfo;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469};
470
Tim Murray4a4e4a22016-04-19 16:29:23 +0000471#undef LOG_TAG
472#define LOG_TAG "DispSync"
473
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474class ZeroPhaseTracer : public DispSync::Callback {
475public:
476 ZeroPhaseTracer() : mParity(false) {}
477
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700478 virtual void onDispSyncEvent(nsecs_t /*when*/) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479 mParity = !mParity;
480 ATRACE_INT("ZERO_PHASE_VSYNC", mParity ? 1 : 0);
481 }
482
483private:
484 bool mParity;
485};
486
Ana Krulec064a82f2018-09-11 16:03:03 -0700487DispSync::DispSync(const char* name) : mName(name), mRefreshSkipCount(0) {
488 // This flag offers the ability to turn on systrace logging from the shell.
489 char value[PROPERTY_VALUE_MAX];
490 property_get("debug.sf.dispsync_trace_detailed_info", value, "0");
491 mTraceDetailedInfo = atoi(value);
492 mThread = new DispSyncThread(name, mTraceDetailedInfo);
493}
Andy McFadden645b1f72014-06-10 14:43:32 -0700494
Ady Abraham50c202a2019-03-14 11:44:38 -0700495DispSync::~DispSync() {
496 mThread->stop();
497 mThread->requestExitAndWait();
498}
Saurabh Shahf4174532017-07-13 10:45:07 -0700499
500void DispSync::init(bool hasSyncFramework, int64_t dispSyncPresentTimeOffset) {
501 mIgnorePresentFences = !hasSyncFramework;
502 mPresentTimeOffset = dispSyncPresentTimeOffset;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700503 mThread->run("DispSync", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
Saurabh Shahf4174532017-07-13 10:45:07 -0700504
Tim Murrayacff43d2016-07-29 13:57:24 -0700505 // set DispSync to SCHED_FIFO to minimize jitter
506 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700507 param.sched_priority = 2;
Tim Murrayacff43d2016-07-29 13:57:24 -0700508 if (sched_setscheduler(mThread->getTid(), SCHED_FIFO, &param) != 0) {
509 ALOGE("Couldn't set SCHED_FIFO for DispSyncThread");
510 }
511
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512 beginResync();
513
Ana Krulec064a82f2018-09-11 16:03:03 -0700514 if (mTraceDetailedInfo && kEnableZeroPhaseTracer) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700515 mZeroPhaseTracer = std::make_unique<ZeroPhaseTracer>();
Alec Mouri7355eb22019-03-05 14:19:10 -0800516 addEventListener("ZeroPhaseTracer", 0, mZeroPhaseTracer.get(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700517 }
518}
519
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520void DispSync::reset() {
521 Mutex::Autolock lock(mMutex);
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700522 resetLocked();
523}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700524
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700525void DispSync::resetLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700526 mPhase = 0;
Alec Mouri75b0b622019-03-12 18:56:00 +0000527 const size_t lastSampleIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
528 // Keep the most recent sample, when we resync to hardware we'll overwrite this
529 // with a more accurate signal
530 if (mResyncSamples[lastSampleIdx] != 0) {
531 mReferenceTime = mResyncSamples[lastSampleIdx];
532 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700533 mModelUpdated = false;
Alec Mouri75b0b622019-03-12 18:56:00 +0000534 for (size_t i = 0; i < MAX_RESYNC_SAMPLES; i++) {
535 mResyncSamples[i] = 0;
536 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700537 mNumResyncSamples = 0;
538 mFirstResyncSample = 0;
539 mNumResyncSamplesSincePresent = 0;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700540 mThread->unlockModel();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541 resetErrorLocked();
542}
543
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700544bool DispSync::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700545 Mutex::Autolock lock(mMutex);
546
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700547 if (mIgnorePresentFences) {
548 return true;
549 }
550
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700551 mPresentFences[mPresentSampleOffset] = fenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552 mPresentSampleOffset = (mPresentSampleOffset + 1) % NUM_PRESENT_SAMPLES;
553 mNumResyncSamplesSincePresent = 0;
554
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700555 updateErrorLocked();
556
Haixia Shi676b1f62015-10-28 16:19:01 -0700557 return !mModelUpdated || mError > kErrorThreshold;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700558}
559
560void DispSync::beginResync() {
561 Mutex::Autolock lock(mMutex);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000562 ALOGV("[%s] beginResync", mName);
Alec Mourif8e689c2019-05-20 18:32:22 -0700563 resetLocked();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700564}
565
Alec Mourif8e689c2019-05-20 18:32:22 -0700566bool DispSync::addResyncSample(nsecs_t timestamp, bool* periodFlushed) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700567 Mutex::Autolock lock(mMutex);
568
Tim Murray4a4e4a22016-04-19 16:29:23 +0000569 ALOGV("[%s] addResyncSample(%" PRId64 ")", mName, ns2us(timestamp));
570
Alec Mourif8e689c2019-05-20 18:32:22 -0700571 *periodFlushed = false;
Alec Mouri754c98a2019-03-18 18:53:42 -0700572 const size_t idx = (mFirstResyncSample + mNumResyncSamples) % MAX_RESYNC_SAMPLES;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700573 mResyncSamples[idx] = timestamp;
Haixia Shi664339a2015-10-28 13:22:22 -0700574 if (mNumResyncSamples == 0) {
Haixia Shi676b1f62015-10-28 16:19:01 -0700575 mPhase = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000576 ALOGV("[%s] First resync sample: mPeriod = %" PRId64 ", mPhase = 0, "
Lloyd Pique78ce4182018-01-31 16:39:51 -0800577 "mReferenceTime = %" PRId64,
Alec Mouri754c98a2019-03-18 18:53:42 -0700578 mName, ns2us(mPeriod), ns2us(timestamp));
579 } else if (mPendingPeriod > 0) {
580 // mNumResyncSamples > 0, so priorIdx won't overflow
581 const size_t priorIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
582 const nsecs_t lastTimestamp = mResyncSamples[priorIdx];
583
584 const nsecs_t observedVsync = std::abs(timestamp - lastTimestamp);
Alec Mourif8e689c2019-05-20 18:32:22 -0700585 if (std::abs(observedVsync - mPendingPeriod) <= std::abs(observedVsync - mIntendedPeriod)) {
586 // Either the observed vsync is closer to the pending period, (and
587 // thus we detected a period change), or the period change will
588 // no-op. In either case, reset the model and flush the pending
589 // period.
Alec Mouri754c98a2019-03-18 18:53:42 -0700590 resetLocked();
Alec Mourif8e689c2019-05-20 18:32:22 -0700591 mIntendedPeriod = mPendingPeriod;
Alec Mouri754c98a2019-03-18 18:53:42 -0700592 mPeriod = mPendingPeriod;
593 mPendingPeriod = 0;
594 if (mTraceDetailedInfo) {
595 ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
Alec Mourif8e689c2019-05-20 18:32:22 -0700596 ATRACE_INT("DispSync:IntendedPeriod", mIntendedPeriod);
Alec Mouri754c98a2019-03-18 18:53:42 -0700597 }
Alec Mourif8e689c2019-05-20 18:32:22 -0700598 *periodFlushed = true;
Alec Mouri754c98a2019-03-18 18:53:42 -0700599 }
Haixia Shi664339a2015-10-28 13:22:22 -0700600 }
Alec Mouri754c98a2019-03-18 18:53:42 -0700601 // Always update the reference time with the most recent timestamp.
602 mReferenceTime = timestamp;
603 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604
605 if (mNumResyncSamples < MAX_RESYNC_SAMPLES) {
606 mNumResyncSamples++;
607 } else {
608 mFirstResyncSample = (mFirstResyncSample + 1) % MAX_RESYNC_SAMPLES;
609 }
610
611 updateModelLocked();
612
613 if (mNumResyncSamplesSincePresent++ > MAX_RESYNC_SAMPLES_WITHOUT_PRESENT) {
614 resetErrorLocked();
615 }
616
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800617 if (mIgnorePresentFences) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700618 // If we're ignoring the present fences we have no way to know whether
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700619 // or not we're synchronized with the HW vsyncs, so we just request
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700620 // that the HW vsync events be turned on.
621 return true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700622 }
623
Tim Murray4a4e4a22016-04-19 16:29:23 +0000624 // Check against kErrorThreshold / 2 to add some hysteresis before having to
625 // resync again
Alec Mouri754c98a2019-03-18 18:53:42 -0700626 bool modelLocked = mModelUpdated && mError < (kErrorThreshold / 2) && mPendingPeriod == 0;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800627 ALOGV("[%s] addResyncSample returning %s", mName, modelLocked ? "locked" : "unlocked");
Alec Mouri016b8dd2019-04-24 15:16:05 -0700628 if (modelLocked) {
Alec Mourif8e689c2019-05-20 18:32:22 -0700629 *periodFlushed = true;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700630 mThread->lockModel();
631 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000632 return !modelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700633}
634
Alec Mouri016b8dd2019-04-24 15:16:05 -0700635void DispSync::endResync() {
636 mThread->lockModel();
637}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700638
Alec Mouri7355eb22019-03-05 14:19:10 -0800639status_t DispSync::addEventListener(const char* name, nsecs_t phase, Callback* callback,
640 nsecs_t lastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700641 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800642 return mThread->addEventListener(name, phase, callback, lastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700643}
644
Andy McFadden645b1f72014-06-10 14:43:32 -0700645void DispSync::setRefreshSkipCount(int count) {
646 Mutex::Autolock lock(mMutex);
647 ALOGD("setRefreshSkipCount(%d)", count);
648 mRefreshSkipCount = count;
649 updateModelLocked();
Ruchi Kandoif52b3c82014-04-24 16:42:35 -0700650}
651
Alec Mouri7355eb22019-03-05 14:19:10 -0800652status_t DispSync::removeEventListener(Callback* callback, nsecs_t* outLastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700653 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800654 return mThread->removeEventListener(callback, outLastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700655}
656
Dan Stoza84d619e2018-03-28 17:07:36 -0700657status_t DispSync::changePhaseOffset(Callback* callback, nsecs_t phase) {
658 Mutex::Autolock lock(mMutex);
659 return mThread->changePhaseOffset(callback, phase);
660}
661
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700662void DispSync::setPeriod(nsecs_t period) {
663 Mutex::Autolock lock(mMutex);
Alec Mourif8e689c2019-05-20 18:32:22 -0700664
665 const bool pendingPeriodShouldChange =
666 period != mIntendedPeriod || (period == mIntendedPeriod && mPendingPeriod != 0);
667
668 if (pendingPeriodShouldChange) {
669 mPendingPeriod = period;
Alec Mouri754c98a2019-03-18 18:53:42 -0700670 }
Alec Mourif8e689c2019-05-20 18:32:22 -0700671 if (mTraceDetailedInfo) {
672 ATRACE_INT("DispSync:IntendedPeriod", mIntendedPeriod);
673 ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
674 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700675}
676
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700677nsecs_t DispSync::getPeriod() {
678 // lock mutex as mPeriod changes multiple times in updateModelLocked
679 Mutex::Autolock lock(mMutex);
680 return mPeriod;
681}
682
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700683void DispSync::updateModelLocked() {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000684 ALOGV("[%s] updateModelLocked %zu", mName, mNumResyncSamples);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700685 if (mNumResyncSamples >= MIN_RESYNC_SAMPLES_FOR_UPDATE) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000686 ALOGV("[%s] Computing...", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700687 nsecs_t durationSum = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000688 nsecs_t minDuration = INT64_MAX;
689 nsecs_t maxDuration = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700690 for (size_t i = 1; i < mNumResyncSamples; i++) {
691 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
692 size_t prev = (idx + MAX_RESYNC_SAMPLES - 1) % MAX_RESYNC_SAMPLES;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000693 nsecs_t duration = mResyncSamples[idx] - mResyncSamples[prev];
694 durationSum += duration;
695 minDuration = min(minDuration, duration);
696 maxDuration = max(maxDuration, duration);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700697 }
698
Tim Murray4a4e4a22016-04-19 16:29:23 +0000699 // Exclude the min and max from the average
700 durationSum -= minDuration + maxDuration;
David Sodman1afa8b02018-10-15 11:20:48 -0700701 mPeriod = durationSum / (mNumResyncSamples - 3);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000702
703 ALOGV("[%s] mPeriod = %" PRId64, mName, ns2us(mPeriod));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700704
705 double sampleAvgX = 0;
706 double sampleAvgY = 0;
707 double scale = 2.0 * M_PI / double(mPeriod);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000708 // Intentionally skip the first sample
709 for (size_t i = 1; i < mNumResyncSamples; i++) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700710 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
Haixia Shi676b1f62015-10-28 16:19:01 -0700711 nsecs_t sample = mResyncSamples[idx] - mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700712 double samplePhase = double(sample % mPeriod) * scale;
713 sampleAvgX += cos(samplePhase);
714 sampleAvgY += sin(samplePhase);
715 }
716
Tim Murray4a4e4a22016-04-19 16:29:23 +0000717 sampleAvgX /= double(mNumResyncSamples - 1);
718 sampleAvgY /= double(mNumResyncSamples - 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700719
720 mPhase = nsecs_t(atan2(sampleAvgY, sampleAvgX) / scale);
721
Tim Murray4a4e4a22016-04-19 16:29:23 +0000722 ALOGV("[%s] mPhase = %" PRId64, mName, ns2us(mPhase));
723
724 if (mPhase < -(mPeriod / 2)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700725 mPhase += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000726 ALOGV("[%s] Adjusting mPhase -> %" PRId64, mName, ns2us(mPhase));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700727 }
728
Andy McFadden645b1f72014-06-10 14:43:32 -0700729 // Artificially inflate the period if requested.
730 mPeriod += mPeriod * mRefreshSkipCount;
731
Haixia Shi676b1f62015-10-28 16:19:01 -0700732 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
733 mModelUpdated = true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700734 }
735}
736
737void DispSync::updateErrorLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700738 if (!mModelUpdated) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700739 return;
740 }
741
Andy McFadden645b1f72014-06-10 14:43:32 -0700742 // Need to compare present fences against the un-adjusted refresh period,
743 // since they might arrive between two events.
744 nsecs_t period = mPeriod / (1 + mRefreshSkipCount);
745
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700746 int numErrSamples = 0;
747 nsecs_t sqErrSum = 0;
748
749 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700750 // Only check for the cached value of signal time to avoid unecessary
751 // syscalls. It is the responsibility of the DispSync owner to
752 // call getSignalTime() periodically so the cache is updated when the
753 // fence signals.
754 nsecs_t time = mPresentFences[i]->getCachedSignalTime();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800755 if (time == Fence::SIGNAL_TIME_PENDING || time == Fence::SIGNAL_TIME_INVALID) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700756 continue;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700757 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700758
759 nsecs_t sample = time - mReferenceTime;
760 if (sample <= mPhase) {
761 continue;
762 }
763
764 nsecs_t sampleErr = (sample - mPhase) % period;
765 if (sampleErr > period / 2) {
766 sampleErr -= period;
767 }
768 sqErrSum += sampleErr * sampleErr;
769 numErrSamples++;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700770 }
771
772 if (numErrSamples > 0) {
773 mError = sqErrSum / numErrSamples;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700774 mZeroErrSamplesCount = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700775 } else {
776 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700777 // Use mod ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT to avoid log spam.
778 mZeroErrSamplesCount++;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800779 ALOGE_IF((mZeroErrSamplesCount % ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT) == 0,
780 "No present times for model error.");
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700781 }
782
Ana Krulec064a82f2018-09-11 16:03:03 -0700783 if (mTraceDetailedInfo) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700784 ATRACE_INT64("DispSync:Error", mError);
785 }
786}
787
788void DispSync::resetErrorLocked() {
789 mPresentSampleOffset = 0;
790 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700791 mZeroErrSamplesCount = 0;
Alec Mourif8e689c2019-05-20 18:32:22 -0700792 if (mTraceDetailedInfo) {
793 ATRACE_INT64("DispSync:Error", mError);
794 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700795 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700796 mPresentFences[i] = FenceTime::NO_FENCE;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700797 }
798}
799
Andy McFadden41d67d72014-04-25 16:58:34 -0700800nsecs_t DispSync::computeNextRefresh(int periodOffset) const {
Andy McFadden150ecd82014-05-08 14:56:50 -0700801 Mutex::Autolock lock(mMutex);
Andy McFadden41d67d72014-04-25 16:58:34 -0700802 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Haixia Shi676b1f62015-10-28 16:19:01 -0700803 nsecs_t phase = mReferenceTime + mPhase;
Marissa Wall17b4e452018-12-26 16:32:34 -0800804 if (mPeriod == 0) {
805 return 0;
806 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700807 return (((now - phase) / mPeriod) + periodOffset + 1) * mPeriod + phase;
Andy McFadden41d67d72014-04-25 16:58:34 -0700808}
809
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700810void DispSync::setIgnorePresentFences(bool ignore) {
811 Mutex::Autolock lock(mMutex);
812 if (mIgnorePresentFences != ignore) {
813 mIgnorePresentFences = ignore;
814 resetLocked();
815 }
816}
817
Yiwei Zhang5434a782018-12-05 18:06:32 -0800818void DispSync::dump(std::string& result) const {
Andy McFaddenc751e922014-05-08 14:53:26 -0700819 Mutex::Autolock lock(mMutex);
Yiwei Zhang5434a782018-12-05 18:06:32 -0800820 StringAppendF(&result, "present fences are %s\n", mIgnorePresentFences ? "ignored" : "used");
821 StringAppendF(&result, "mPeriod: %" PRId64 " ns (%.3f fps; skipCount=%d)\n", mPeriod,
822 1000000000.0 / mPeriod, mRefreshSkipCount);
823 StringAppendF(&result, "mPhase: %" PRId64 " ns\n", mPhase);
824 StringAppendF(&result, "mError: %" PRId64 " ns (sqrt=%.1f)\n", mError, sqrt(mError));
825 StringAppendF(&result, "mNumResyncSamplesSincePresent: %d (limit %d)\n",
826 mNumResyncSamplesSincePresent, MAX_RESYNC_SAMPLES_WITHOUT_PRESENT);
827 StringAppendF(&result, "mNumResyncSamples: %zd (max %d)\n", mNumResyncSamples,
828 MAX_RESYNC_SAMPLES);
Andy McFaddenc751e922014-05-08 14:53:26 -0700829
Yiwei Zhang5434a782018-12-05 18:06:32 -0800830 result.append("mResyncSamples:\n");
Andy McFaddenc751e922014-05-08 14:53:26 -0700831 nsecs_t previous = -1;
832 for (size_t i = 0; i < mNumResyncSamples; i++) {
833 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
834 nsecs_t sampleTime = mResyncSamples[idx];
835 if (i == 0) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800836 StringAppendF(&result, " %" PRId64 "\n", sampleTime);
Andy McFaddenc751e922014-05-08 14:53:26 -0700837 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800838 StringAppendF(&result, " %" PRId64 " (+%" PRId64 ")\n", sampleTime,
839 sampleTime - previous);
Andy McFaddenc751e922014-05-08 14:53:26 -0700840 }
841 previous = sampleTime;
842 }
843
Yiwei Zhang5434a782018-12-05 18:06:32 -0800844 StringAppendF(&result, "mPresentFences [%d]:\n", NUM_PRESENT_SAMPLES);
Andy McFadden5167ec62014-05-22 13:08:43 -0700845 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700846 previous = Fence::SIGNAL_TIME_INVALID;
Andy McFaddenc751e922014-05-08 14:53:26 -0700847 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
848 size_t idx = (i + mPresentSampleOffset) % NUM_PRESENT_SAMPLES;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700849 nsecs_t presentTime = mPresentFences[idx]->getSignalTime();
850 if (presentTime == Fence::SIGNAL_TIME_PENDING) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800851 StringAppendF(&result, " [unsignaled fence]\n");
Lloyd Pique78ce4182018-01-31 16:39:51 -0800852 } else if (presentTime == Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800853 StringAppendF(&result, " [invalid fence]\n");
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700854 } else if (previous == Fence::SIGNAL_TIME_PENDING ||
Lloyd Pique78ce4182018-01-31 16:39:51 -0800855 previous == Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800856 StringAppendF(&result, " %" PRId64 " (%.3f ms ago)\n", presentTime,
857 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700858 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800859 StringAppendF(&result, " %" PRId64 " (+%" PRId64 " / %.3f) (%.3f ms ago)\n",
860 presentTime, presentTime - previous,
861 (presentTime - previous) / (double)mPeriod,
862 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700863 }
864 previous = presentTime;
865 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700866
Yiwei Zhang5434a782018-12-05 18:06:32 -0800867 StringAppendF(&result, "current monotonic time: %" PRId64 "\n", now);
Andy McFaddenc751e922014-05-08 14:53:26 -0700868}
869
Ana Krulec010d2192018-10-08 06:29:54 -0700870nsecs_t DispSync::expectedPresentTime() {
871 // The HWC doesn't currently have a way to report additional latency.
872 // Assume that whatever we submit now will appear right after the flip.
873 // For a smart panel this might be 1. This is expressed in frames,
874 // rather than time, because we expect to have a constant frame delay
875 // regardless of the refresh rate.
876 const uint32_t hwcLatency = 0;
877
878 // Ask DispSync when the next refresh will be (CLOCK_MONOTONIC).
Ana Krulec757f63a2019-01-25 10:46:18 -0800879 return computeNextRefresh(hwcLatency);
Ana Krulec010d2192018-10-08 06:29:54 -0700880}
881
Lloyd Pique41be5d22018-06-21 13:11:48 -0700882} // namespace impl
883
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700884} // namespace android