blob: cd6fa419400fff178ab9ae697459b01ce95624a2 [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;
118 }
119
120 void unlockModel() {
121 Mutex::Autolock lock(mMutex);
122 mModelLocked = false;
123 }
124
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700125 virtual bool threadLoop() {
126 status_t err;
127 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
129 while (true) {
Ana Krulec9a52b192018-07-12 18:18:47 -0400130 std::vector<CallbackInvocation> callbackInvocations;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700131
132 nsecs_t targetTime = 0;
133
134 { // Scope for lock
135 Mutex::Autolock lock(mMutex);
136
Ana Krulec064a82f2018-09-11 16:03:03 -0700137 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000138 ATRACE_INT64("DispSync:Frame", mFrameNumber);
139 }
140 ALOGV("[%s] Frame %" PRId64, mName, mFrameNumber);
141 ++mFrameNumber;
142
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700143 if (mStop) {
144 return false;
145 }
146
147 if (mPeriod == 0) {
148 err = mCond.wait(mMutex);
149 if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800150 ALOGE("error waiting for new events: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700151 return false;
152 }
153 continue;
154 }
155
Dan Stoza8f8374d2016-04-19 10:03:46 -0700156 targetTime = computeNextEventTimeLocked(now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700157
158 bool isWakeup = false;
159
160 if (now < targetTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700161 if (mTraceDetailedInfo) ATRACE_NAME("DispSync waiting");
Dan Stoza8f8374d2016-04-19 10:03:46 -0700162
163 if (targetTime == INT64_MAX) {
164 ALOGV("[%s] Waiting forever", mName);
165 err = mCond.wait(mMutex);
166 } else {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800167 ALOGV("[%s] Waiting until %" PRId64, mName, ns2us(targetTime));
Dan Stoza8f8374d2016-04-19 10:03:46 -0700168 err = mCond.waitRelative(mMutex, targetTime - now);
169 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700170
171 if (err == TIMED_OUT) {
172 isWakeup = true;
173 } else if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800174 ALOGE("error waiting for next event: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700175 return false;
176 }
177 }
178
179 now = systemTime(SYSTEM_TIME_MONOTONIC);
180
Tim Murray4a4e4a22016-04-19 16:29:23 +0000181 // Don't correct by more than 1.5 ms
182 static const nsecs_t kMaxWakeupLatency = us2ns(1500);
183
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700184 if (isWakeup) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800185 mWakeupLatency = ((mWakeupLatency * 63) + (now - targetTime)) / 64;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000186 mWakeupLatency = min(mWakeupLatency, kMaxWakeupLatency);
Ana Krulec064a82f2018-09-11 16:03:03 -0700187 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000188 ATRACE_INT64("DispSync:WakeupLat", now - targetTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700189 ATRACE_INT64("DispSync:AvgWakeupLat", mWakeupLatency);
190 }
191 }
192
193 callbackInvocations = gatherCallbackInvocationsLocked(now);
194 }
195
196 if (callbackInvocations.size() > 0) {
Andy McFadden645b1f72014-06-10 14:43:32 -0700197 fireCallbackInvocations(callbackInvocations);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700198 }
199 }
200
201 return false;
202 }
203
Alec Mouri7355eb22019-03-05 14:19:10 -0800204 status_t addEventListener(const char* name, nsecs_t phase, DispSync::Callback* callback,
205 nsecs_t lastCallbackTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700206 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700207 Mutex::Autolock lock(mMutex);
208
209 for (size_t i = 0; i < mEventListeners.size(); i++) {
210 if (mEventListeners[i].mCallback == callback) {
211 return BAD_VALUE;
212 }
213 }
214
215 EventListener listener;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000216 listener.mName = name;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700217 listener.mPhase = phase;
218 listener.mCallback = callback;
Jamie Gennis629b9872013-10-29 13:36:12 -0700219
220 // We want to allow the firstmost future event to fire without
Alec Mouri81835982019-02-27 13:40:44 -0800221 // allowing any past events to fire. To do this extrapolate from
222 // mReferenceTime the most recent hardware vsync, and pin the
223 // last event time there.
224 const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
225 if (mPeriod != 0) {
226 const nsecs_t baseTime = now - mReferenceTime;
227 const nsecs_t numPeriodsSinceReference = baseTime / mPeriod;
228 const nsecs_t predictedReference = mReferenceTime + numPeriodsSinceReference * mPeriod;
Alec Mouridf3d2e12019-05-02 17:58:46 +0000229 const nsecs_t phaseCorrection = mPhase + listener.mPhase;
230 const nsecs_t predictedLastEventTime = predictedReference + phaseCorrection;
231 if (predictedLastEventTime >= now) {
232 // Make sure that the last event time does not exceed the current time.
233 // If it would, then back the last event time by a period.
234 listener.mLastEventTime = predictedLastEventTime - mPeriod;
235 } else {
236 listener.mLastEventTime = predictedLastEventTime;
Alec Mouri81835982019-02-27 13:40:44 -0800237 }
238 } else {
239 listener.mLastEventTime = now + mPhase - mWakeupLatency;
240 }
Jamie Gennis629b9872013-10-29 13:36:12 -0700241
Alec Mouri7355eb22019-03-05 14:19:10 -0800242 if (lastCallbackTime <= 0) {
243 // If there is no prior callback time, try to infer one based on the
244 // logical last event time.
245 listener.mLastCallbackTime = listener.mLastEventTime + mWakeupLatency;
246 } else {
247 listener.mLastCallbackTime = lastCallbackTime;
248 }
249
Ana Krulec9a52b192018-07-12 18:18:47 -0400250 mEventListeners.push_back(listener);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700251
252 mCond.signal();
253
254 return NO_ERROR;
255 }
256
Alec Mouri7355eb22019-03-05 14:19:10 -0800257 status_t removeEventListener(DispSync::Callback* callback, nsecs_t* outLastCallback) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700258 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700259 Mutex::Autolock lock(mMutex);
260
Ana Krulec9a52b192018-07-12 18:18:47 -0400261 for (std::vector<EventListener>::iterator it = mEventListeners.begin();
262 it != mEventListeners.end(); ++it) {
263 if (it->mCallback == callback) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800264 *outLastCallback = it->mLastCallbackTime;
Ana Krulec9a52b192018-07-12 18:18:47 -0400265 mEventListeners.erase(it);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700266 mCond.signal();
267 return NO_ERROR;
268 }
269 }
270
271 return BAD_VALUE;
272 }
273
Dan Stoza84d619e2018-03-28 17:07:36 -0700274 status_t changePhaseOffset(DispSync::Callback* callback, nsecs_t phase) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700275 if (mTraceDetailedInfo) ATRACE_CALL();
Dan Stoza84d619e2018-03-28 17:07:36 -0700276 Mutex::Autolock lock(mMutex);
277
Ana Krulec9a52b192018-07-12 18:18:47 -0400278 for (auto& eventListener : mEventListeners) {
279 if (eventListener.mCallback == callback) {
280 const nsecs_t oldPhase = eventListener.mPhase;
281 eventListener.mPhase = phase;
Dan Stoza84d619e2018-03-28 17:07:36 -0700282
283 // Pretend that the last time this event was handled at the same frame but with the
284 // new offset to allow for a seamless offset change without double-firing or
285 // skipping.
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200286 nsecs_t diff = oldPhase - phase;
287 if (diff > mPeriod / 2) {
288 diff -= mPeriod;
289 } else if (diff < -mPeriod / 2) {
290 diff += mPeriod;
291 }
Ana Krulec9a52b192018-07-12 18:18:47 -0400292 eventListener.mLastEventTime -= diff;
Dan Stoza84d619e2018-03-28 17:07:36 -0700293 mCond.signal();
294 return NO_ERROR;
295 }
296 }
Dan Stoza84d619e2018-03-28 17:07:36 -0700297 return BAD_VALUE;
298 }
299
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700300private:
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700301 struct EventListener {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000302 const char* mName;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700303 nsecs_t mPhase;
304 nsecs_t mLastEventTime;
Alec Mouri7355eb22019-03-05 14:19:10 -0800305 nsecs_t mLastCallbackTime;
Lloyd Piquee83f9312018-02-01 12:53:17 -0800306 DispSync::Callback* mCallback;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700307 bool mHasFired = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700308 };
309
310 struct CallbackInvocation {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800311 DispSync::Callback* mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700312 nsecs_t mEventTime;
313 };
314
315 nsecs_t computeNextEventTimeLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700316 if (mTraceDetailedInfo) ATRACE_CALL();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000317 ALOGV("[%s] computeNextEventTimeLocked", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700318 nsecs_t nextEventTime = INT64_MAX;
319 for (size_t i = 0; i < mEventListeners.size(); i++) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800320 nsecs_t t = computeListenerNextEventTimeLocked(mEventListeners[i], now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700321
322 if (t < nextEventTime) {
323 nextEventTime = t;
324 }
325 }
326
Tim Murray4a4e4a22016-04-19 16:29:23 +0000327 ALOGV("[%s] nextEventTime = %" PRId64, mName, ns2us(nextEventTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700328 return nextEventTime;
329 }
330
Alec Mouri7355eb22019-03-05 14:19:10 -0800331 // Sanity check that the duration is close enough in length to a period without
332 // falling into double-rate vsyncs.
Alec Mouridf3d2e12019-05-02 17:58:46 +0000333 bool isCloseToPeriod(nsecs_t duration) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800334 // Ratio of 3/5 is arbitrary, but it must be greater than 1/2.
335 return duration < (3 * mPeriod) / 5;
336 }
337
Ana Krulec9a52b192018-07-12 18:18:47 -0400338 std::vector<CallbackInvocation> gatherCallbackInvocationsLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700339 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800340 ALOGV("[%s] gatherCallbackInvocationsLocked @ %" PRId64, mName, ns2us(now));
Tim Murray4a4e4a22016-04-19 16:29:23 +0000341
Ana Krulec9a52b192018-07-12 18:18:47 -0400342 std::vector<CallbackInvocation> callbackInvocations;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000343 nsecs_t onePeriodAgo = now - mPeriod;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700344
Ana Krulec9a52b192018-07-12 18:18:47 -0400345 for (auto& eventListener : mEventListeners) {
346 nsecs_t t = computeListenerNextEventTimeLocked(eventListener, onePeriodAgo);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700347
Jamie Gennis0d5c60e2013-10-09 17:49:37 -0700348 if (t < now) {
Alec Mouridf3d2e12019-05-02 17:58:46 +0000349 if (isCloseToPeriod(now - eventListener.mLastCallbackTime)) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800350 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800351 ALOGV("[%s] [%s] Skipping event due to model error", mName,
352 eventListener.mName);
353 continue;
354 }
Alec Mouri016b8dd2019-04-24 15:16:05 -0700355 if (eventListener.mHasFired && !mModelLocked) {
356 eventListener.mLastEventTime = t;
357 ALOGV("[%s] [%s] Skipping event due to already firing", mName,
358 eventListener.mName);
359 continue;
360 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700361 CallbackInvocation ci;
Ana Krulec9a52b192018-07-12 18:18:47 -0400362 ci.mCallback = eventListener.mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700363 ci.mEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800364 ALOGV("[%s] [%s] Preparing to fire, latency: %" PRId64, mName, eventListener.mName,
365 t - eventListener.mLastEventTime);
Ana Krulec9a52b192018-07-12 18:18:47 -0400366 callbackInvocations.push_back(ci);
367 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800368 eventListener.mLastCallbackTime = now;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700369 eventListener.mHasFired = true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700370 }
371 }
372
373 return callbackInvocations;
374 }
375
Lloyd Pique78ce4182018-01-31 16:39:51 -0800376 nsecs_t computeListenerNextEventTimeLocked(const EventListener& listener, nsecs_t baseTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700377 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800378 ALOGV("[%s] [%s] computeListenerNextEventTimeLocked(%" PRId64 ")", mName, listener.mName,
379 ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700380
Tim Murray4a4e4a22016-04-19 16:29:23 +0000381 nsecs_t lastEventTime = listener.mLastEventTime + mWakeupLatency;
382 ALOGV("[%s] lastEventTime: %" PRId64, mName, ns2us(lastEventTime));
383 if (baseTime < lastEventTime) {
384 baseTime = lastEventTime;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800385 ALOGV("[%s] Clamping baseTime to lastEventTime -> %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700386 }
387
Tim Murray4a4e4a22016-04-19 16:29:23 +0000388 baseTime -= mReferenceTime;
389 ALOGV("[%s] Relative baseTime = %" PRId64, mName, ns2us(baseTime));
390 nsecs_t phase = mPhase + listener.mPhase;
391 ALOGV("[%s] Phase = %" PRId64, mName, ns2us(phase));
392 baseTime -= phase;
393 ALOGV("[%s] baseTime - phase = %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700394
Tim Murray4a4e4a22016-04-19 16:29:23 +0000395 // If our previous time is before the reference (because the reference
396 // has since been updated), the division by mPeriod will truncate
397 // towards zero instead of computing the floor. Since in all cases
398 // before the reference we want the next time to be effectively now, we
399 // set baseTime to -mPeriod so that numPeriods will be -1.
400 // When we add 1 and the phase, we will be at the correct event time for
401 // this period.
402 if (baseTime < 0) {
403 ALOGV("[%s] Correcting negative baseTime", mName);
404 baseTime = -mPeriod;
405 }
406
407 nsecs_t numPeriods = baseTime / mPeriod;
408 ALOGV("[%s] numPeriods = %" PRId64, mName, numPeriods);
409 nsecs_t t = (numPeriods + 1) * mPeriod + phase;
410 ALOGV("[%s] t = %" PRId64, mName, ns2us(t));
411 t += mReferenceTime;
412 ALOGV("[%s] Absolute t = %" PRId64, mName, ns2us(t));
413
414 // Check that it's been slightly more than half a period since the last
415 // event so that we don't accidentally fall into double-rate vsyncs
Alec Mouridf3d2e12019-05-02 17:58:46 +0000416 if (isCloseToPeriod(t - listener.mLastEventTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700417 t += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000418 ALOGV("[%s] Modifying t -> %" PRId64, mName, ns2us(t));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700419 }
420
Tim Murray4a4e4a22016-04-19 16:29:23 +0000421 t -= mWakeupLatency;
422 ALOGV("[%s] Corrected for wakeup latency -> %" PRId64, mName, ns2us(t));
423
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 return t;
425 }
426
Ana Krulec9a52b192018-07-12 18:18:47 -0400427 void fireCallbackInvocations(const std::vector<CallbackInvocation>& callbacks) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700428 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429 for (size_t i = 0; i < callbacks.size(); i++) {
430 callbacks[i].mCallback->onDispSyncEvent(callbacks[i].mEventTime);
431 }
432 }
433
Tim Murray4a4e4a22016-04-19 16:29:23 +0000434 const char* const mName;
435
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436 bool mStop;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700437 bool mModelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438
439 nsecs_t mPeriod;
440 nsecs_t mPhase;
Haixia Shi676b1f62015-10-28 16:19:01 -0700441 nsecs_t mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442 nsecs_t mWakeupLatency;
443
Tim Murray4a4e4a22016-04-19 16:29:23 +0000444 int64_t mFrameNumber;
445
Ana Krulec9a52b192018-07-12 18:18:47 -0400446 std::vector<EventListener> mEventListeners;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700447
448 Mutex mMutex;
449 Condition mCond;
Ana Krulec064a82f2018-09-11 16:03:03 -0700450
451 // Flag to turn on logging in systrace.
452 const bool mTraceDetailedInfo;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700453};
454
Tim Murray4a4e4a22016-04-19 16:29:23 +0000455#undef LOG_TAG
456#define LOG_TAG "DispSync"
457
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458class ZeroPhaseTracer : public DispSync::Callback {
459public:
460 ZeroPhaseTracer() : mParity(false) {}
461
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700462 virtual void onDispSyncEvent(nsecs_t /*when*/) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463 mParity = !mParity;
464 ATRACE_INT("ZERO_PHASE_VSYNC", mParity ? 1 : 0);
465 }
466
467private:
468 bool mParity;
469};
470
Ana Krulec064a82f2018-09-11 16:03:03 -0700471DispSync::DispSync(const char* name) : mName(name), mRefreshSkipCount(0) {
472 // This flag offers the ability to turn on systrace logging from the shell.
473 char value[PROPERTY_VALUE_MAX];
474 property_get("debug.sf.dispsync_trace_detailed_info", value, "0");
475 mTraceDetailedInfo = atoi(value);
476 mThread = new DispSyncThread(name, mTraceDetailedInfo);
477}
Andy McFadden645b1f72014-06-10 14:43:32 -0700478
Ady Abraham50c202a2019-03-14 11:44:38 -0700479DispSync::~DispSync() {
480 mThread->stop();
481 mThread->requestExitAndWait();
482}
Saurabh Shahf4174532017-07-13 10:45:07 -0700483
484void DispSync::init(bool hasSyncFramework, int64_t dispSyncPresentTimeOffset) {
485 mIgnorePresentFences = !hasSyncFramework;
486 mPresentTimeOffset = dispSyncPresentTimeOffset;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 mThread->run("DispSync", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
Saurabh Shahf4174532017-07-13 10:45:07 -0700488
Tim Murrayacff43d2016-07-29 13:57:24 -0700489 // set DispSync to SCHED_FIFO to minimize jitter
490 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700491 param.sched_priority = 2;
Tim Murrayacff43d2016-07-29 13:57:24 -0700492 if (sched_setscheduler(mThread->getTid(), SCHED_FIFO, &param) != 0) {
493 ALOGE("Couldn't set SCHED_FIFO for DispSyncThread");
494 }
495
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 reset();
497 beginResync();
498
Ana Krulec064a82f2018-09-11 16:03:03 -0700499 if (mTraceDetailedInfo && kEnableZeroPhaseTracer) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700500 mZeroPhaseTracer = std::make_unique<ZeroPhaseTracer>();
Alec Mouri7355eb22019-03-05 14:19:10 -0800501 addEventListener("ZeroPhaseTracer", 0, mZeroPhaseTracer.get(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 }
503}
504
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505void DispSync::reset() {
506 Mutex::Autolock lock(mMutex);
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700507 resetLocked();
508}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700509
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700510void DispSync::resetLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700511 mPhase = 0;
Alec Mouri75b0b622019-03-12 18:56:00 +0000512 const size_t lastSampleIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
513 // Keep the most recent sample, when we resync to hardware we'll overwrite this
514 // with a more accurate signal
515 if (mResyncSamples[lastSampleIdx] != 0) {
516 mReferenceTime = mResyncSamples[lastSampleIdx];
517 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700518 mModelUpdated = false;
Alec Mouri75b0b622019-03-12 18:56:00 +0000519 for (size_t i = 0; i < MAX_RESYNC_SAMPLES; i++) {
520 mResyncSamples[i] = 0;
521 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522 mNumResyncSamples = 0;
523 mFirstResyncSample = 0;
524 mNumResyncSamplesSincePresent = 0;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700525 mThread->unlockModel();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700526 resetErrorLocked();
527}
528
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700529bool DispSync::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530 Mutex::Autolock lock(mMutex);
531
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700532 if (mIgnorePresentFences) {
533 return true;
534 }
535
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700536 mPresentFences[mPresentSampleOffset] = fenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700537 mPresentSampleOffset = (mPresentSampleOffset + 1) % NUM_PRESENT_SAMPLES;
538 mNumResyncSamplesSincePresent = 0;
539
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540 updateErrorLocked();
541
Haixia Shi676b1f62015-10-28 16:19:01 -0700542 return !mModelUpdated || mError > kErrorThreshold;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700543}
544
545void DispSync::beginResync() {
546 Mutex::Autolock lock(mMutex);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000547 ALOGV("[%s] beginResync", mName);
Alec Mouri016b8dd2019-04-24 15:16:05 -0700548 mThread->unlockModel();
Haixia Shi676b1f62015-10-28 16:19:01 -0700549 mModelUpdated = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550 mNumResyncSamples = 0;
551}
552
Alec Mouri754c98a2019-03-18 18:53:42 -0700553bool DispSync::addResyncSample(nsecs_t timestamp, bool* periodChanged) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700554 Mutex::Autolock lock(mMutex);
555
Tim Murray4a4e4a22016-04-19 16:29:23 +0000556 ALOGV("[%s] addResyncSample(%" PRId64 ")", mName, ns2us(timestamp));
557
Alec Mouri754c98a2019-03-18 18:53:42 -0700558 *periodChanged = false;
559 const size_t idx = (mFirstResyncSample + mNumResyncSamples) % MAX_RESYNC_SAMPLES;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700560 mResyncSamples[idx] = timestamp;
Haixia Shi664339a2015-10-28 13:22:22 -0700561 if (mNumResyncSamples == 0) {
Haixia Shi676b1f62015-10-28 16:19:01 -0700562 mPhase = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000563 ALOGV("[%s] First resync sample: mPeriod = %" PRId64 ", mPhase = 0, "
Lloyd Pique78ce4182018-01-31 16:39:51 -0800564 "mReferenceTime = %" PRId64,
Alec Mouri754c98a2019-03-18 18:53:42 -0700565 mName, ns2us(mPeriod), ns2us(timestamp));
566 } else if (mPendingPeriod > 0) {
567 // mNumResyncSamples > 0, so priorIdx won't overflow
568 const size_t priorIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
569 const nsecs_t lastTimestamp = mResyncSamples[priorIdx];
570
571 const nsecs_t observedVsync = std::abs(timestamp - lastTimestamp);
572 if (std::abs(observedVsync - mPendingPeriod) < std::abs(observedVsync - mPeriod)) {
573 // Observed vsync is closer to the pending period, so reset the
574 // model and flush the pending period.
575 resetLocked();
576 mPeriod = mPendingPeriod;
577 mPendingPeriod = 0;
578 if (mTraceDetailedInfo) {
579 ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
580 }
581 *periodChanged = true;
582 }
Haixia Shi664339a2015-10-28 13:22:22 -0700583 }
Alec Mouri754c98a2019-03-18 18:53:42 -0700584 // Always update the reference time with the most recent timestamp.
585 mReferenceTime = timestamp;
586 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700587
588 if (mNumResyncSamples < MAX_RESYNC_SAMPLES) {
589 mNumResyncSamples++;
590 } else {
591 mFirstResyncSample = (mFirstResyncSample + 1) % MAX_RESYNC_SAMPLES;
592 }
593
594 updateModelLocked();
595
596 if (mNumResyncSamplesSincePresent++ > MAX_RESYNC_SAMPLES_WITHOUT_PRESENT) {
597 resetErrorLocked();
598 }
599
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800600 if (mIgnorePresentFences) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700601 // If we're ignoring the present fences we have no way to know whether
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602 // or not we're synchronized with the HW vsyncs, so we just request
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700603 // that the HW vsync events be turned on.
604 return true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700605 }
606
Tim Murray4a4e4a22016-04-19 16:29:23 +0000607 // Check against kErrorThreshold / 2 to add some hysteresis before having to
608 // resync again
Alec Mouri754c98a2019-03-18 18:53:42 -0700609 bool modelLocked = mModelUpdated && mError < (kErrorThreshold / 2) && mPendingPeriod == 0;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800610 ALOGV("[%s] addResyncSample returning %s", mName, modelLocked ? "locked" : "unlocked");
Alec Mouri016b8dd2019-04-24 15:16:05 -0700611 if (modelLocked) {
612 mThread->lockModel();
613 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000614 return !modelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700615}
616
Alec Mouri016b8dd2019-04-24 15:16:05 -0700617void DispSync::endResync() {
618 mThread->lockModel();
619}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700620
Alec Mouri7355eb22019-03-05 14:19:10 -0800621status_t DispSync::addEventListener(const char* name, nsecs_t phase, Callback* callback,
622 nsecs_t lastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700623 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800624 return mThread->addEventListener(name, phase, callback, lastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700625}
626
Andy McFadden645b1f72014-06-10 14:43:32 -0700627void DispSync::setRefreshSkipCount(int count) {
628 Mutex::Autolock lock(mMutex);
629 ALOGD("setRefreshSkipCount(%d)", count);
630 mRefreshSkipCount = count;
631 updateModelLocked();
Ruchi Kandoif52b3c82014-04-24 16:42:35 -0700632}
633
Alec Mouri7355eb22019-03-05 14:19:10 -0800634status_t DispSync::removeEventListener(Callback* callback, nsecs_t* outLastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700635 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800636 return mThread->removeEventListener(callback, outLastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700637}
638
Dan Stoza84d619e2018-03-28 17:07:36 -0700639status_t DispSync::changePhaseOffset(Callback* callback, nsecs_t phase) {
640 Mutex::Autolock lock(mMutex);
641 return mThread->changePhaseOffset(callback, phase);
642}
643
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700644void DispSync::setPeriod(nsecs_t period) {
645 Mutex::Autolock lock(mMutex);
Alec Mouri754c98a2019-03-18 18:53:42 -0700646 if (mTraceDetailedInfo) {
647 ATRACE_INT("DispSync:PendingPeriod", period);
648 }
649 mPendingPeriod = period;
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;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700665 for (size_t i = 1; i < mNumResyncSamples; i++) {
666 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
667 size_t prev = (idx + MAX_RESYNC_SAMPLES - 1) % MAX_RESYNC_SAMPLES;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000668 nsecs_t duration = mResyncSamples[idx] - mResyncSamples[prev];
669 durationSum += duration;
670 minDuration = min(minDuration, duration);
671 maxDuration = max(maxDuration, duration);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700672 }
673
Tim Murray4a4e4a22016-04-19 16:29:23 +0000674 // Exclude the min and max from the average
675 durationSum -= minDuration + maxDuration;
David Sodman1afa8b02018-10-15 11:20:48 -0700676 mPeriod = durationSum / (mNumResyncSamples - 3);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000677
678 ALOGV("[%s] mPeriod = %" PRId64, mName, ns2us(mPeriod));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700679
680 double sampleAvgX = 0;
681 double sampleAvgY = 0;
682 double scale = 2.0 * M_PI / double(mPeriod);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000683 // Intentionally skip the first sample
684 for (size_t i = 1; i < mNumResyncSamples; i++) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700685 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
Haixia Shi676b1f62015-10-28 16:19:01 -0700686 nsecs_t sample = mResyncSamples[idx] - mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700687 double samplePhase = double(sample % mPeriod) * scale;
688 sampleAvgX += cos(samplePhase);
689 sampleAvgY += sin(samplePhase);
690 }
691
Tim Murray4a4e4a22016-04-19 16:29:23 +0000692 sampleAvgX /= double(mNumResyncSamples - 1);
693 sampleAvgY /= double(mNumResyncSamples - 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700694
695 mPhase = nsecs_t(atan2(sampleAvgY, sampleAvgX) / scale);
696
Tim Murray4a4e4a22016-04-19 16:29:23 +0000697 ALOGV("[%s] mPhase = %" PRId64, mName, ns2us(mPhase));
698
699 if (mPhase < -(mPeriod / 2)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700700 mPhase += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000701 ALOGV("[%s] Adjusting mPhase -> %" PRId64, mName, ns2us(mPhase));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700702 }
703
Andy McFadden645b1f72014-06-10 14:43:32 -0700704 // Artificially inflate the period if requested.
705 mPeriod += mPeriod * mRefreshSkipCount;
706
Haixia Shi676b1f62015-10-28 16:19:01 -0700707 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
708 mModelUpdated = true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700709 }
710}
711
712void DispSync::updateErrorLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700713 if (!mModelUpdated) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700714 return;
715 }
716
Andy McFadden645b1f72014-06-10 14:43:32 -0700717 // Need to compare present fences against the un-adjusted refresh period,
718 // since they might arrive between two events.
719 nsecs_t period = mPeriod / (1 + mRefreshSkipCount);
720
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700721 int numErrSamples = 0;
722 nsecs_t sqErrSum = 0;
723
724 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700725 // Only check for the cached value of signal time to avoid unecessary
726 // syscalls. It is the responsibility of the DispSync owner to
727 // call getSignalTime() periodically so the cache is updated when the
728 // fence signals.
729 nsecs_t time = mPresentFences[i]->getCachedSignalTime();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800730 if (time == Fence::SIGNAL_TIME_PENDING || time == Fence::SIGNAL_TIME_INVALID) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700731 continue;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700732 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700733
734 nsecs_t sample = time - mReferenceTime;
735 if (sample <= mPhase) {
736 continue;
737 }
738
739 nsecs_t sampleErr = (sample - mPhase) % period;
740 if (sampleErr > period / 2) {
741 sampleErr -= period;
742 }
743 sqErrSum += sampleErr * sampleErr;
744 numErrSamples++;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700745 }
746
747 if (numErrSamples > 0) {
748 mError = sqErrSum / numErrSamples;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700749 mZeroErrSamplesCount = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700750 } else {
751 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700752 // Use mod ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT to avoid log spam.
753 mZeroErrSamplesCount++;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800754 ALOGE_IF((mZeroErrSamplesCount % ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT) == 0,
755 "No present times for model error.");
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700756 }
757
Ana Krulec064a82f2018-09-11 16:03:03 -0700758 if (mTraceDetailedInfo) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700759 ATRACE_INT64("DispSync:Error", mError);
760 }
761}
762
763void DispSync::resetErrorLocked() {
764 mPresentSampleOffset = 0;
765 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700766 mZeroErrSamplesCount = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700767 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700768 mPresentFences[i] = FenceTime::NO_FENCE;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700769 }
770}
771
Andy McFadden41d67d72014-04-25 16:58:34 -0700772nsecs_t DispSync::computeNextRefresh(int periodOffset) const {
Andy McFadden150ecd82014-05-08 14:56:50 -0700773 Mutex::Autolock lock(mMutex);
Andy McFadden41d67d72014-04-25 16:58:34 -0700774 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Haixia Shi676b1f62015-10-28 16:19:01 -0700775 nsecs_t phase = mReferenceTime + mPhase;
Marissa Wall17b4e452018-12-26 16:32:34 -0800776 if (mPeriod == 0) {
777 return 0;
778 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700779 return (((now - phase) / mPeriod) + periodOffset + 1) * mPeriod + phase;
Andy McFadden41d67d72014-04-25 16:58:34 -0700780}
781
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700782void DispSync::setIgnorePresentFences(bool ignore) {
783 Mutex::Autolock lock(mMutex);
784 if (mIgnorePresentFences != ignore) {
785 mIgnorePresentFences = ignore;
786 resetLocked();
787 }
788}
789
Yiwei Zhang5434a782018-12-05 18:06:32 -0800790void DispSync::dump(std::string& result) const {
Andy McFaddenc751e922014-05-08 14:53:26 -0700791 Mutex::Autolock lock(mMutex);
Yiwei Zhang5434a782018-12-05 18:06:32 -0800792 StringAppendF(&result, "present fences are %s\n", mIgnorePresentFences ? "ignored" : "used");
793 StringAppendF(&result, "mPeriod: %" PRId64 " ns (%.3f fps; skipCount=%d)\n", mPeriod,
794 1000000000.0 / mPeriod, mRefreshSkipCount);
795 StringAppendF(&result, "mPhase: %" PRId64 " ns\n", mPhase);
796 StringAppendF(&result, "mError: %" PRId64 " ns (sqrt=%.1f)\n", mError, sqrt(mError));
797 StringAppendF(&result, "mNumResyncSamplesSincePresent: %d (limit %d)\n",
798 mNumResyncSamplesSincePresent, MAX_RESYNC_SAMPLES_WITHOUT_PRESENT);
799 StringAppendF(&result, "mNumResyncSamples: %zd (max %d)\n", mNumResyncSamples,
800 MAX_RESYNC_SAMPLES);
Andy McFaddenc751e922014-05-08 14:53:26 -0700801
Yiwei Zhang5434a782018-12-05 18:06:32 -0800802 result.append("mResyncSamples:\n");
Andy McFaddenc751e922014-05-08 14:53:26 -0700803 nsecs_t previous = -1;
804 for (size_t i = 0; i < mNumResyncSamples; i++) {
805 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
806 nsecs_t sampleTime = mResyncSamples[idx];
807 if (i == 0) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800808 StringAppendF(&result, " %" PRId64 "\n", sampleTime);
Andy McFaddenc751e922014-05-08 14:53:26 -0700809 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800810 StringAppendF(&result, " %" PRId64 " (+%" PRId64 ")\n", sampleTime,
811 sampleTime - previous);
Andy McFaddenc751e922014-05-08 14:53:26 -0700812 }
813 previous = sampleTime;
814 }
815
Yiwei Zhang5434a782018-12-05 18:06:32 -0800816 StringAppendF(&result, "mPresentFences [%d]:\n", NUM_PRESENT_SAMPLES);
Andy McFadden5167ec62014-05-22 13:08:43 -0700817 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700818 previous = Fence::SIGNAL_TIME_INVALID;
Andy McFaddenc751e922014-05-08 14:53:26 -0700819 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
820 size_t idx = (i + mPresentSampleOffset) % NUM_PRESENT_SAMPLES;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700821 nsecs_t presentTime = mPresentFences[idx]->getSignalTime();
822 if (presentTime == Fence::SIGNAL_TIME_PENDING) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800823 StringAppendF(&result, " [unsignaled fence]\n");
Lloyd Pique78ce4182018-01-31 16:39:51 -0800824 } else if (presentTime == Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800825 StringAppendF(&result, " [invalid fence]\n");
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700826 } else if (previous == Fence::SIGNAL_TIME_PENDING ||
Lloyd Pique78ce4182018-01-31 16:39:51 -0800827 previous == Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800828 StringAppendF(&result, " %" PRId64 " (%.3f ms ago)\n", presentTime,
829 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700830 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800831 StringAppendF(&result, " %" PRId64 " (+%" PRId64 " / %.3f) (%.3f ms ago)\n",
832 presentTime, presentTime - previous,
833 (presentTime - previous) / (double)mPeriod,
834 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700835 }
836 previous = presentTime;
837 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700838
Yiwei Zhang5434a782018-12-05 18:06:32 -0800839 StringAppendF(&result, "current monotonic time: %" PRId64 "\n", now);
Andy McFaddenc751e922014-05-08 14:53:26 -0700840}
841
Ana Krulec010d2192018-10-08 06:29:54 -0700842nsecs_t DispSync::expectedPresentTime() {
843 // The HWC doesn't currently have a way to report additional latency.
844 // Assume that whatever we submit now will appear right after the flip.
845 // For a smart panel this might be 1. This is expressed in frames,
846 // rather than time, because we expect to have a constant frame delay
847 // regardless of the refresh rate.
848 const uint32_t hwcLatency = 0;
849
850 // Ask DispSync when the next refresh will be (CLOCK_MONOTONIC).
Ana Krulec757f63a2019-01-25 10:46:18 -0800851 return computeNextRefresh(hwcLatency);
Ana Krulec010d2192018-10-08 06:29:54 -0700852}
853
Lloyd Pique41be5d22018-06-21 13:11:48 -0700854} // namespace impl
855
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700856} // namespace android