blob: 809a0e52fa6a944c4265cb69c6218c0b2d970e33 [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
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070021#define ATRACE_TAG ATRACE_TAG_GRAPHICS
Tim Murray4a4e4a22016-04-19 16:29:23 +000022//#define LOG_NDEBUG 0
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070023
24// This is needed for stdint.h to define INT64_MAX in C++
25#define __STDC_LIMIT_MACROS
26
27#include <math.h>
28
Mark Salyzyna5e161b2016-09-29 08:08:05 -070029#include <algorithm>
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070030
Yiwei Zhang5434a782018-12-05 18:06:32 -080031#include <android-base/stringprintf.h>
David Sodman1afa8b02018-10-15 11:20:48 -070032#include <cutils/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080033#include <log/log.h>
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070034#include <utils/Thread.h>
35#include <utils/Trace.h>
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070036
Brian Andersonfbc80ae2017-05-26 16:23:54 -070037#include <ui/FenceTime.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070038
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070039#include "DispSync.h"
40#include "EventLog/EventLog.h"
Lloyd Pique78ce4182018-01-31 16:39:51 -080041#include "SurfaceFlinger.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070042
Yiwei Zhang5434a782018-12-05 18:06:32 -080043using android::base::StringAppendF;
Tim Murray4a4e4a22016-04-19 16:29:23 +000044using std::max;
45using std::min;
46
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070047namespace android {
48
Lloyd Pique41be5d22018-06-21 13:11:48 -070049DispSync::~DispSync() = default;
Kevin DuBois7b743be2019-02-27 10:05:48 -080050DispSync::Callback::~Callback() = default;
Lloyd Pique41be5d22018-06-21 13:11:48 -070051
52namespace impl {
53
Tim Murray4a4e4a22016-04-19 16:29:23 +000054// Setting this to true adds a zero-phase tracer for correlating with hardware
55// vsync events
56static const bool kEnableZeroPhaseTracer = false;
57
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070058// This is the threshold used to determine when hardware vsync events are
59// needed to re-synchronize the software vsync model with the hardware. The
60// error metric used is the mean of the squared difference between each
61// present time and the nearest software-predicted vsync.
Lloyd Pique78ce4182018-01-31 16:39:51 -080062static const nsecs_t kErrorThreshold = 160000000000; // 400 usec squared
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070063
Tim Murray4a4e4a22016-04-19 16:29:23 +000064#undef LOG_TAG
65#define LOG_TAG "DispSyncThread"
Lloyd Pique78ce4182018-01-31 16:39:51 -080066class DispSyncThread : public Thread {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070067public:
Ana Krulec064a82f2018-09-11 16:03:03 -070068 DispSyncThread(const char* name, bool showTraceDetailedInfo)
Lloyd Pique78ce4182018-01-31 16:39:51 -080069 : mName(name),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070 mStop(false),
Ady Abraham50204dd2019-07-19 15:47:11 -070071 mModelLocked("DispSync:ModelLocked", false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070072 mPeriod(0),
73 mPhase(0),
Haixia Shi676b1f62015-10-28 16:19:01 -070074 mReferenceTime(0),
Tim Murray4a4e4a22016-04-19 16:29:23 +000075 mWakeupLatency(0),
Ana Krulec064a82f2018-09-11 16:03:03 -070076 mFrameNumber(0),
77 mTraceDetailedInfo(showTraceDetailedInfo) {}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070078
79 virtual ~DispSyncThread() {}
80
Haixia Shi676b1f62015-10-28 16:19:01 -070081 void updateModel(nsecs_t period, nsecs_t phase, nsecs_t referenceTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -070082 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070083 Mutex::Autolock lock(mMutex);
Alec Mouri75b0b622019-03-12 18:56:00 +000084
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070085 mPhase = phase;
Alec Mouric3a482d2019-05-21 00:51:01 -070086 const bool referenceTimeChanged = mReferenceTime != referenceTime;
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 Mouric3a482d2019-05-21 00:51:01 -070097 if (!mModelLocked && referenceTimeChanged) {
98 for (auto& eventListener : mEventListeners) {
Ady Abraham81ca00f2019-06-19 17:01:57 -070099 eventListener.mLastEventTime = mReferenceTime + mPhase + eventListener.mPhase;
100 // If mLastEventTime is after mReferenceTime (can happen when positive phase offsets
101 // are used) we treat it as like it happened in previous period.
102 if (eventListener.mLastEventTime > mReferenceTime) {
103 eventListener.mLastEventTime -= mPeriod;
104 }
Alec Mouric3a482d2019-05-21 00:51:01 -0700105 }
106 }
Alec Mourif5fe85c2019-02-22 13:40:36 -0800107 if (mTraceDetailedInfo) {
108 ATRACE_INT64("DispSync:Period", mPeriod);
109 ATRACE_INT64("DispSync:Phase", mPhase + mPeriod / 2);
110 ATRACE_INT64("DispSync:Reference Time", mReferenceTime);
111 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000112 ALOGV("[%s] updateModel: mPeriod = %" PRId64 ", mPhase = %" PRId64
Lloyd Pique78ce4182018-01-31 16:39:51 -0800113 " mReferenceTime = %" PRId64,
114 mName, ns2us(mPeriod), ns2us(mPhase), ns2us(mReferenceTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700115 mCond.signal();
116 }
117
118 void stop() {
Ana Krulec064a82f2018-09-11 16:03:03 -0700119 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700120 Mutex::Autolock lock(mMutex);
121 mStop = true;
122 mCond.signal();
123 }
124
Alec Mouri016b8dd2019-04-24 15:16:05 -0700125 void lockModel() {
126 Mutex::Autolock lock(mMutex);
127 mModelLocked = true;
128 }
129
130 void unlockModel() {
131 Mutex::Autolock lock(mMutex);
132 mModelLocked = false;
133 }
134
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700135 virtual bool threadLoop() {
136 status_t err;
137 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700138
139 while (true) {
Ana Krulec9a52b192018-07-12 18:18:47 -0400140 std::vector<CallbackInvocation> callbackInvocations;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700141
142 nsecs_t targetTime = 0;
143
144 { // Scope for lock
145 Mutex::Autolock lock(mMutex);
146
Ana Krulec064a82f2018-09-11 16:03:03 -0700147 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000148 ATRACE_INT64("DispSync:Frame", mFrameNumber);
149 }
150 ALOGV("[%s] Frame %" PRId64, mName, mFrameNumber);
151 ++mFrameNumber;
152
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700153 if (mStop) {
154 return false;
155 }
156
157 if (mPeriod == 0) {
158 err = mCond.wait(mMutex);
159 if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800160 ALOGE("error waiting for new events: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700161 return false;
162 }
163 continue;
164 }
165
Dan Stoza8f8374d2016-04-19 10:03:46 -0700166 targetTime = computeNextEventTimeLocked(now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700167
168 bool isWakeup = false;
169
170 if (now < targetTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700171 if (mTraceDetailedInfo) ATRACE_NAME("DispSync waiting");
Dan Stoza8f8374d2016-04-19 10:03:46 -0700172
173 if (targetTime == INT64_MAX) {
174 ALOGV("[%s] Waiting forever", mName);
175 err = mCond.wait(mMutex);
176 } else {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800177 ALOGV("[%s] Waiting until %" PRId64, mName, ns2us(targetTime));
Dan Stoza8f8374d2016-04-19 10:03:46 -0700178 err = mCond.waitRelative(mMutex, targetTime - now);
179 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700180
181 if (err == TIMED_OUT) {
182 isWakeup = true;
183 } else if (err != NO_ERROR) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800184 ALOGE("error waiting for next event: %s (%d)", strerror(-err), err);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700185 return false;
186 }
187 }
188
189 now = systemTime(SYSTEM_TIME_MONOTONIC);
190
Tim Murray4a4e4a22016-04-19 16:29:23 +0000191 // Don't correct by more than 1.5 ms
192 static const nsecs_t kMaxWakeupLatency = us2ns(1500);
193
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700194 if (isWakeup) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800195 mWakeupLatency = ((mWakeupLatency * 63) + (now - targetTime)) / 64;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000196 mWakeupLatency = min(mWakeupLatency, kMaxWakeupLatency);
Ana Krulec064a82f2018-09-11 16:03:03 -0700197 if (mTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000198 ATRACE_INT64("DispSync:WakeupLat", now - targetTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700199 ATRACE_INT64("DispSync:AvgWakeupLat", mWakeupLatency);
200 }
201 }
202
203 callbackInvocations = gatherCallbackInvocationsLocked(now);
204 }
205
206 if (callbackInvocations.size() > 0) {
Andy McFadden645b1f72014-06-10 14:43:32 -0700207 fireCallbackInvocations(callbackInvocations);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700208 }
209 }
210
211 return false;
212 }
213
Alec Mouri7355eb22019-03-05 14:19:10 -0800214 status_t addEventListener(const char* name, nsecs_t phase, DispSync::Callback* callback,
215 nsecs_t lastCallbackTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700216 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700217 Mutex::Autolock lock(mMutex);
218
219 for (size_t i = 0; i < mEventListeners.size(); i++) {
220 if (mEventListeners[i].mCallback == callback) {
221 return BAD_VALUE;
222 }
223 }
224
225 EventListener listener;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000226 listener.mName = name;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700227 listener.mPhase = phase;
228 listener.mCallback = callback;
Jamie Gennis629b9872013-10-29 13:36:12 -0700229
230 // We want to allow the firstmost future event to fire without
Alec Mouri81835982019-02-27 13:40:44 -0800231 // allowing any past events to fire. To do this extrapolate from
232 // mReferenceTime the most recent hardware vsync, and pin the
233 // last event time there.
234 const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
235 if (mPeriod != 0) {
236 const nsecs_t baseTime = now - mReferenceTime;
237 const nsecs_t numPeriodsSinceReference = baseTime / mPeriod;
238 const nsecs_t predictedReference = mReferenceTime + numPeriodsSinceReference * mPeriod;
Alec Mouridf3d2e12019-05-02 17:58:46 +0000239 const nsecs_t phaseCorrection = mPhase + listener.mPhase;
240 const nsecs_t predictedLastEventTime = predictedReference + phaseCorrection;
241 if (predictedLastEventTime >= now) {
242 // Make sure that the last event time does not exceed the current time.
243 // If it would, then back the last event time by a period.
244 listener.mLastEventTime = predictedLastEventTime - mPeriod;
245 } else {
246 listener.mLastEventTime = predictedLastEventTime;
Alec Mouri81835982019-02-27 13:40:44 -0800247 }
248 } else {
249 listener.mLastEventTime = now + mPhase - mWakeupLatency;
250 }
Jamie Gennis629b9872013-10-29 13:36:12 -0700251
Alec Mouri7355eb22019-03-05 14:19:10 -0800252 if (lastCallbackTime <= 0) {
253 // If there is no prior callback time, try to infer one based on the
254 // logical last event time.
255 listener.mLastCallbackTime = listener.mLastEventTime + mWakeupLatency;
256 } else {
257 listener.mLastCallbackTime = lastCallbackTime;
258 }
259
Ana Krulec9a52b192018-07-12 18:18:47 -0400260 mEventListeners.push_back(listener);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700261
262 mCond.signal();
263
264 return NO_ERROR;
265 }
266
Alec Mouri7355eb22019-03-05 14:19:10 -0800267 status_t removeEventListener(DispSync::Callback* callback, nsecs_t* outLastCallback) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700268 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700269 Mutex::Autolock lock(mMutex);
270
Ana Krulec9a52b192018-07-12 18:18:47 -0400271 for (std::vector<EventListener>::iterator it = mEventListeners.begin();
272 it != mEventListeners.end(); ++it) {
273 if (it->mCallback == callback) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800274 *outLastCallback = it->mLastCallbackTime;
Ana Krulec9a52b192018-07-12 18:18:47 -0400275 mEventListeners.erase(it);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700276 mCond.signal();
277 return NO_ERROR;
278 }
279 }
280
281 return BAD_VALUE;
282 }
283
Dan Stoza84d619e2018-03-28 17:07:36 -0700284 status_t changePhaseOffset(DispSync::Callback* callback, nsecs_t phase) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700285 if (mTraceDetailedInfo) ATRACE_CALL();
Dan Stoza84d619e2018-03-28 17:07:36 -0700286 Mutex::Autolock lock(mMutex);
287
Ana Krulec9a52b192018-07-12 18:18:47 -0400288 for (auto& eventListener : mEventListeners) {
289 if (eventListener.mCallback == callback) {
290 const nsecs_t oldPhase = eventListener.mPhase;
291 eventListener.mPhase = phase;
Dan Stoza84d619e2018-03-28 17:07:36 -0700292
293 // Pretend that the last time this event was handled at the same frame but with the
294 // new offset to allow for a seamless offset change without double-firing or
295 // skipping.
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200296 nsecs_t diff = oldPhase - phase;
Ana Krulec9a52b192018-07-12 18:18:47 -0400297 eventListener.mLastEventTime -= diff;
Ady Abraham45e4e362019-06-07 18:20:51 -0700298 eventListener.mLastCallbackTime -= diff;
Dan Stoza84d619e2018-03-28 17:07:36 -0700299 mCond.signal();
300 return NO_ERROR;
301 }
302 }
Dan Stoza84d619e2018-03-28 17:07:36 -0700303 return BAD_VALUE;
304 }
305
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700306private:
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700307 struct EventListener {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000308 const char* mName;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700309 nsecs_t mPhase;
310 nsecs_t mLastEventTime;
Alec Mouri7355eb22019-03-05 14:19:10 -0800311 nsecs_t mLastCallbackTime;
Lloyd Piquee83f9312018-02-01 12:53:17 -0800312 DispSync::Callback* mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700313 };
314
315 struct CallbackInvocation {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800316 DispSync::Callback* mCallback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700317 nsecs_t mEventTime;
318 };
319
320 nsecs_t computeNextEventTimeLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700321 if (mTraceDetailedInfo) ATRACE_CALL();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000322 ALOGV("[%s] computeNextEventTimeLocked", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700323 nsecs_t nextEventTime = INT64_MAX;
324 for (size_t i = 0; i < mEventListeners.size(); i++) {
Lloyd Pique78ce4182018-01-31 16:39:51 -0800325 nsecs_t t = computeListenerNextEventTimeLocked(mEventListeners[i], now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700326
327 if (t < nextEventTime) {
328 nextEventTime = t;
329 }
330 }
331
Tim Murray4a4e4a22016-04-19 16:29:23 +0000332 ALOGV("[%s] nextEventTime = %" PRId64, mName, ns2us(nextEventTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700333 return nextEventTime;
334 }
335
Alec Mouri7355eb22019-03-05 14:19:10 -0800336 // Sanity check that the duration is close enough in length to a period without
337 // falling into double-rate vsyncs.
Alec Mouridf3d2e12019-05-02 17:58:46 +0000338 bool isCloseToPeriod(nsecs_t duration) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800339 // Ratio of 3/5 is arbitrary, but it must be greater than 1/2.
340 return duration < (3 * mPeriod) / 5;
341 }
342
Ana Krulec9a52b192018-07-12 18:18:47 -0400343 std::vector<CallbackInvocation> gatherCallbackInvocationsLocked(nsecs_t now) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700344 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800345 ALOGV("[%s] gatherCallbackInvocationsLocked @ %" PRId64, mName, ns2us(now));
Tim Murray4a4e4a22016-04-19 16:29:23 +0000346
Ana Krulec9a52b192018-07-12 18:18:47 -0400347 std::vector<CallbackInvocation> callbackInvocations;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000348 nsecs_t onePeriodAgo = now - mPeriod;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700349
Ana Krulec9a52b192018-07-12 18:18:47 -0400350 for (auto& eventListener : mEventListeners) {
351 nsecs_t t = computeListenerNextEventTimeLocked(eventListener, onePeriodAgo);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700352
Jamie Gennis0d5c60e2013-10-09 17:49:37 -0700353 if (t < now) {
Alec Mouridf3d2e12019-05-02 17:58:46 +0000354 if (isCloseToPeriod(now - eventListener.mLastCallbackTime)) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800355 eventListener.mLastEventTime = t;
Alec Mouri7355eb22019-03-05 14:19:10 -0800356 ALOGV("[%s] [%s] Skipping event due to model error", mName,
357 eventListener.mName);
358 continue;
359 }
Ady Abraham45e4e362019-06-07 18:20:51 -0700360
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;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700369 }
370 }
371
372 return callbackInvocations;
373 }
374
Lloyd Pique78ce4182018-01-31 16:39:51 -0800375 nsecs_t computeListenerNextEventTimeLocked(const EventListener& listener, nsecs_t baseTime) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700376 if (mTraceDetailedInfo) ATRACE_CALL();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800377 ALOGV("[%s] [%s] computeListenerNextEventTimeLocked(%" PRId64 ")", mName, listener.mName,
378 ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700379
Tim Murray4a4e4a22016-04-19 16:29:23 +0000380 nsecs_t lastEventTime = listener.mLastEventTime + mWakeupLatency;
381 ALOGV("[%s] lastEventTime: %" PRId64, mName, ns2us(lastEventTime));
382 if (baseTime < lastEventTime) {
383 baseTime = lastEventTime;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800384 ALOGV("[%s] Clamping baseTime to lastEventTime -> %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700385 }
386
Tim Murray4a4e4a22016-04-19 16:29:23 +0000387 baseTime -= mReferenceTime;
388 ALOGV("[%s] Relative baseTime = %" PRId64, mName, ns2us(baseTime));
389 nsecs_t phase = mPhase + listener.mPhase;
390 ALOGV("[%s] Phase = %" PRId64, mName, ns2us(phase));
391 baseTime -= phase;
392 ALOGV("[%s] baseTime - phase = %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700393
Tim Murray4a4e4a22016-04-19 16:29:23 +0000394 // If our previous time is before the reference (because the reference
395 // has since been updated), the division by mPeriod will truncate
396 // towards zero instead of computing the floor. Since in all cases
397 // before the reference we want the next time to be effectively now, we
398 // set baseTime to -mPeriod so that numPeriods will be -1.
399 // When we add 1 and the phase, we will be at the correct event time for
400 // this period.
401 if (baseTime < 0) {
402 ALOGV("[%s] Correcting negative baseTime", mName);
403 baseTime = -mPeriod;
404 }
405
406 nsecs_t numPeriods = baseTime / mPeriod;
407 ALOGV("[%s] numPeriods = %" PRId64, mName, numPeriods);
408 nsecs_t t = (numPeriods + 1) * mPeriod + phase;
409 ALOGV("[%s] t = %" PRId64, mName, ns2us(t));
410 t += mReferenceTime;
411 ALOGV("[%s] Absolute t = %" PRId64, mName, ns2us(t));
412
413 // Check that it's been slightly more than half a period since the last
414 // event so that we don't accidentally fall into double-rate vsyncs
Alec Mouridf3d2e12019-05-02 17:58:46 +0000415 if (isCloseToPeriod(t - listener.mLastEventTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 t += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000417 ALOGV("[%s] Modifying t -> %" PRId64, mName, ns2us(t));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 }
419
Tim Murray4a4e4a22016-04-19 16:29:23 +0000420 t -= mWakeupLatency;
421 ALOGV("[%s] Corrected for wakeup latency -> %" PRId64, mName, ns2us(t));
422
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423 return t;
424 }
425
Ana Krulec9a52b192018-07-12 18:18:47 -0400426 void fireCallbackInvocations(const std::vector<CallbackInvocation>& callbacks) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700427 if (mTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700428 for (size_t i = 0; i < callbacks.size(); i++) {
429 callbacks[i].mCallback->onDispSyncEvent(callbacks[i].mEventTime);
430 }
431 }
432
Tim Murray4a4e4a22016-04-19 16:29:23 +0000433 const char* const mName;
434
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700435 bool mStop;
Ady Abraham50204dd2019-07-19 15:47:11 -0700436 TracedOrdinal<bool> mModelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700437
438 nsecs_t mPeriod;
439 nsecs_t mPhase;
Haixia Shi676b1f62015-10-28 16:19:01 -0700440 nsecs_t mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700441 nsecs_t mWakeupLatency;
442
Tim Murray4a4e4a22016-04-19 16:29:23 +0000443 int64_t mFrameNumber;
444
Ana Krulec9a52b192018-07-12 18:18:47 -0400445 std::vector<EventListener> mEventListeners;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446
447 Mutex mMutex;
448 Condition mCond;
Ana Krulec064a82f2018-09-11 16:03:03 -0700449
450 // Flag to turn on logging in systrace.
451 const bool mTraceDetailedInfo;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452};
453
Tim Murray4a4e4a22016-04-19 16:29:23 +0000454#undef LOG_TAG
455#define LOG_TAG "DispSync"
456
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700457class ZeroPhaseTracer : public DispSync::Callback {
458public:
Ady Abraham50204dd2019-07-19 15:47:11 -0700459 ZeroPhaseTracer() : mParity("ZERO_PHASE_VSYNC", false) {}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700460
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700461 virtual void onDispSyncEvent(nsecs_t /*when*/) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462 mParity = !mParity;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463 }
464
465private:
Ady Abraham50204dd2019-07-19 15:47:11 -0700466 TracedOrdinal<bool> mParity;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467};
468
Dominik Laskowski98041832019-08-01 18:35:59 -0700469DispSync::DispSync(const char* name, bool hasSyncFramework)
470 : mName(name), mIgnorePresentFences(!hasSyncFramework) {
Ana Krulec064a82f2018-09-11 16:03:03 -0700471 // This flag offers the ability to turn on systrace logging from the shell.
472 char value[PROPERTY_VALUE_MAX];
473 property_get("debug.sf.dispsync_trace_detailed_info", value, "0");
474 mTraceDetailedInfo = atoi(value);
Dominik Laskowski98041832019-08-01 18:35:59 -0700475
Ana Krulec064a82f2018-09-11 16:03:03 -0700476 mThread = new DispSyncThread(name, mTraceDetailedInfo);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700477 mThread->run("DispSync", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
Saurabh Shahf4174532017-07-13 10:45:07 -0700478
Tim Murrayacff43d2016-07-29 13:57:24 -0700479 // set DispSync to SCHED_FIFO to minimize jitter
480 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700481 param.sched_priority = 2;
Tim Murrayacff43d2016-07-29 13:57:24 -0700482 if (sched_setscheduler(mThread->getTid(), SCHED_FIFO, &param) != 0) {
483 ALOGE("Couldn't set SCHED_FIFO for DispSyncThread");
484 }
485
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700486 beginResync();
487
Ana Krulec064a82f2018-09-11 16:03:03 -0700488 if (mTraceDetailedInfo && kEnableZeroPhaseTracer) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700489 mZeroPhaseTracer = std::make_unique<ZeroPhaseTracer>();
Alec Mouri7355eb22019-03-05 14:19:10 -0800490 addEventListener("ZeroPhaseTracer", 0, mZeroPhaseTracer.get(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700491 }
492}
493
Dominik Laskowski98041832019-08-01 18:35:59 -0700494DispSync::~DispSync() {
495 mThread->stop();
496 mThread->requestExitAndWait();
497}
498
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700499void DispSync::reset() {
500 Mutex::Autolock lock(mMutex);
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700501 resetLocked();
502}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700503
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700504void DispSync::resetLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700505 mPhase = 0;
Alec Mouri75b0b622019-03-12 18:56:00 +0000506 const size_t lastSampleIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
507 // Keep the most recent sample, when we resync to hardware we'll overwrite this
508 // with a more accurate signal
509 if (mResyncSamples[lastSampleIdx] != 0) {
510 mReferenceTime = mResyncSamples[lastSampleIdx];
511 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700512 mModelUpdated = false;
Alec Mouri75b0b622019-03-12 18:56:00 +0000513 for (size_t i = 0; i < MAX_RESYNC_SAMPLES; i++) {
514 mResyncSamples[i] = 0;
515 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 mNumResyncSamples = 0;
517 mFirstResyncSample = 0;
518 mNumResyncSamplesSincePresent = 0;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700519 mThread->unlockModel();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520 resetErrorLocked();
521}
522
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700523bool DispSync::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700524 Mutex::Autolock lock(mMutex);
525
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700526 if (mIgnorePresentFences) {
527 return true;
528 }
529
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700530 mPresentFences[mPresentSampleOffset] = fenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 mPresentSampleOffset = (mPresentSampleOffset + 1) % NUM_PRESENT_SAMPLES;
532 mNumResyncSamplesSincePresent = 0;
533
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 updateErrorLocked();
535
Haixia Shi676b1f62015-10-28 16:19:01 -0700536 return !mModelUpdated || mError > kErrorThreshold;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700537}
538
539void DispSync::beginResync() {
540 Mutex::Autolock lock(mMutex);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000541 ALOGV("[%s] beginResync", mName);
Alec Mourif8e689c2019-05-20 18:32:22 -0700542 resetLocked();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700543}
544
Ady Abraham5dee2f12020-02-05 17:49:47 -0800545bool DispSync::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> /*hwcVsyncPeriod*/,
546 bool* periodFlushed) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700547 Mutex::Autolock lock(mMutex);
548
Tim Murray4a4e4a22016-04-19 16:29:23 +0000549 ALOGV("[%s] addResyncSample(%" PRId64 ")", mName, ns2us(timestamp));
550
Alec Mourif8e689c2019-05-20 18:32:22 -0700551 *periodFlushed = false;
Alec Mouri754c98a2019-03-18 18:53:42 -0700552 const size_t idx = (mFirstResyncSample + mNumResyncSamples) % MAX_RESYNC_SAMPLES;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700553 mResyncSamples[idx] = timestamp;
Haixia Shi664339a2015-10-28 13:22:22 -0700554 if (mNumResyncSamples == 0) {
Haixia Shi676b1f62015-10-28 16:19:01 -0700555 mPhase = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000556 ALOGV("[%s] First resync sample: mPeriod = %" PRId64 ", mPhase = 0, "
Lloyd Pique78ce4182018-01-31 16:39:51 -0800557 "mReferenceTime = %" PRId64,
Alec Mouri754c98a2019-03-18 18:53:42 -0700558 mName, ns2us(mPeriod), ns2us(timestamp));
559 } else if (mPendingPeriod > 0) {
560 // mNumResyncSamples > 0, so priorIdx won't overflow
561 const size_t priorIdx = (mFirstResyncSample + mNumResyncSamples - 1) % MAX_RESYNC_SAMPLES;
562 const nsecs_t lastTimestamp = mResyncSamples[priorIdx];
563
564 const nsecs_t observedVsync = std::abs(timestamp - lastTimestamp);
Alec Mourif8e689c2019-05-20 18:32:22 -0700565 if (std::abs(observedVsync - mPendingPeriod) <= std::abs(observedVsync - mIntendedPeriod)) {
566 // Either the observed vsync is closer to the pending period, (and
567 // thus we detected a period change), or the period change will
568 // no-op. In either case, reset the model and flush the pending
569 // period.
Alec Mouri754c98a2019-03-18 18:53:42 -0700570 resetLocked();
Alec Mourif8e689c2019-05-20 18:32:22 -0700571 mIntendedPeriod = mPendingPeriod;
Alec Mouri754c98a2019-03-18 18:53:42 -0700572 mPeriod = mPendingPeriod;
573 mPendingPeriod = 0;
574 if (mTraceDetailedInfo) {
575 ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
Alec Mourif8e689c2019-05-20 18:32:22 -0700576 ATRACE_INT("DispSync:IntendedPeriod", mIntendedPeriod);
Alec Mouri754c98a2019-03-18 18:53:42 -0700577 }
Alec Mourif8e689c2019-05-20 18:32:22 -0700578 *periodFlushed = true;
Alec Mouri754c98a2019-03-18 18:53:42 -0700579 }
Haixia Shi664339a2015-10-28 13:22:22 -0700580 }
Alec Mouri754c98a2019-03-18 18:53:42 -0700581 // Always update the reference time with the most recent timestamp.
582 mReferenceTime = timestamp;
583 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700584
585 if (mNumResyncSamples < MAX_RESYNC_SAMPLES) {
586 mNumResyncSamples++;
587 } else {
588 mFirstResyncSample = (mFirstResyncSample + 1) % MAX_RESYNC_SAMPLES;
589 }
590
591 updateModelLocked();
592
593 if (mNumResyncSamplesSincePresent++ > MAX_RESYNC_SAMPLES_WITHOUT_PRESENT) {
594 resetErrorLocked();
595 }
596
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800597 if (mIgnorePresentFences) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700598 // If we're ignoring the present fences we have no way to know whether
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700599 // or not we're synchronized with the HW vsyncs, so we just request
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700600 // that the HW vsync events be turned on.
601 return true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602 }
603
Tim Murray4a4e4a22016-04-19 16:29:23 +0000604 // Check against kErrorThreshold / 2 to add some hysteresis before having to
605 // resync again
Alec Mouri754c98a2019-03-18 18:53:42 -0700606 bool modelLocked = mModelUpdated && mError < (kErrorThreshold / 2) && mPendingPeriod == 0;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800607 ALOGV("[%s] addResyncSample returning %s", mName, modelLocked ? "locked" : "unlocked");
Alec Mouri016b8dd2019-04-24 15:16:05 -0700608 if (modelLocked) {
Alec Mourif8e689c2019-05-20 18:32:22 -0700609 *periodFlushed = true;
Alec Mouri016b8dd2019-04-24 15:16:05 -0700610 mThread->lockModel();
611 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000612 return !modelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700613}
614
Alec Mouri016b8dd2019-04-24 15:16:05 -0700615void DispSync::endResync() {
616 mThread->lockModel();
617}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700618
Alec Mouri7355eb22019-03-05 14:19:10 -0800619status_t DispSync::addEventListener(const char* name, nsecs_t phase, Callback* callback,
620 nsecs_t lastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700621 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800622 return mThread->addEventListener(name, phase, callback, lastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700623}
624
Alec Mouri7355eb22019-03-05 14:19:10 -0800625status_t DispSync::removeEventListener(Callback* callback, nsecs_t* outLastCallbackTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700626 Mutex::Autolock lock(mMutex);
Alec Mouri7355eb22019-03-05 14:19:10 -0800627 return mThread->removeEventListener(callback, outLastCallbackTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700628}
629
Dan Stoza84d619e2018-03-28 17:07:36 -0700630status_t DispSync::changePhaseOffset(Callback* callback, nsecs_t phase) {
631 Mutex::Autolock lock(mMutex);
632 return mThread->changePhaseOffset(callback, phase);
633}
634
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700635void DispSync::setPeriod(nsecs_t period) {
636 Mutex::Autolock lock(mMutex);
Alec Mourif8e689c2019-05-20 18:32:22 -0700637
638 const bool pendingPeriodShouldChange =
639 period != mIntendedPeriod || (period == mIntendedPeriod && mPendingPeriod != 0);
640
641 if (pendingPeriodShouldChange) {
642 mPendingPeriod = period;
Alec Mouri754c98a2019-03-18 18:53:42 -0700643 }
Alec Mourif8e689c2019-05-20 18:32:22 -0700644 if (mTraceDetailedInfo) {
645 ATRACE_INT("DispSync:IntendedPeriod", mIntendedPeriod);
646 ATRACE_INT("DispSync:PendingPeriod", mPendingPeriod);
647 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700648}
649
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700650nsecs_t DispSync::getPeriod() {
651 // lock mutex as mPeriod changes multiple times in updateModelLocked
652 Mutex::Autolock lock(mMutex);
653 return mPeriod;
654}
655
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700656void DispSync::updateModelLocked() {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000657 ALOGV("[%s] updateModelLocked %zu", mName, mNumResyncSamples);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700658 if (mNumResyncSamples >= MIN_RESYNC_SAMPLES_FOR_UPDATE) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000659 ALOGV("[%s] Computing...", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700660 nsecs_t durationSum = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000661 nsecs_t minDuration = INT64_MAX;
662 nsecs_t maxDuration = 0;
Alec Mouri94390a32019-07-16 13:20:19 -0700663 // We skip the first 2 samples because the first vsync duration on some
664 // devices may be much more inaccurate than on other devices, e.g. due
665 // to delays in ramping up from a power collapse. By doing so this
666 // actually increases the accuracy of the DispSync model even though
667 // we're effectively relying on fewer sample points.
668 static constexpr size_t numSamplesSkipped = 2;
669 for (size_t i = numSamplesSkipped; i < mNumResyncSamples; i++) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700670 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
671 size_t prev = (idx + MAX_RESYNC_SAMPLES - 1) % MAX_RESYNC_SAMPLES;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000672 nsecs_t duration = mResyncSamples[idx] - mResyncSamples[prev];
673 durationSum += duration;
674 minDuration = min(minDuration, duration);
675 maxDuration = max(maxDuration, duration);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700676 }
677
Tim Murray4a4e4a22016-04-19 16:29:23 +0000678 // Exclude the min and max from the average
679 durationSum -= minDuration + maxDuration;
Alec Mouri94390a32019-07-16 13:20:19 -0700680 mPeriod = durationSum / (mNumResyncSamples - numSamplesSkipped - 2);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000681
682 ALOGV("[%s] mPeriod = %" PRId64, mName, ns2us(mPeriod));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700683
684 double sampleAvgX = 0;
685 double sampleAvgY = 0;
686 double scale = 2.0 * M_PI / double(mPeriod);
Alec Mouri94390a32019-07-16 13:20:19 -0700687 for (size_t i = numSamplesSkipped; i < mNumResyncSamples; i++) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700688 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
Haixia Shi676b1f62015-10-28 16:19:01 -0700689 nsecs_t sample = mResyncSamples[idx] - mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700690 double samplePhase = double(sample % mPeriod) * scale;
691 sampleAvgX += cos(samplePhase);
692 sampleAvgY += sin(samplePhase);
693 }
694
Alec Mouri94390a32019-07-16 13:20:19 -0700695 sampleAvgX /= double(mNumResyncSamples - numSamplesSkipped);
696 sampleAvgY /= double(mNumResyncSamples - numSamplesSkipped);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700697
698 mPhase = nsecs_t(atan2(sampleAvgY, sampleAvgX) / scale);
699
Tim Murray4a4e4a22016-04-19 16:29:23 +0000700 ALOGV("[%s] mPhase = %" PRId64, mName, ns2us(mPhase));
701
702 if (mPhase < -(mPeriod / 2)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700703 mPhase += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000704 ALOGV("[%s] Adjusting mPhase -> %" PRId64, mName, ns2us(mPhase));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700705 }
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
717 int numErrSamples = 0;
718 nsecs_t sqErrSum = 0;
719
720 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700721 // Only check for the cached value of signal time to avoid unecessary
722 // syscalls. It is the responsibility of the DispSync owner to
723 // call getSignalTime() periodically so the cache is updated when the
724 // fence signals.
725 nsecs_t time = mPresentFences[i]->getCachedSignalTime();
Lloyd Pique78ce4182018-01-31 16:39:51 -0800726 if (time == Fence::SIGNAL_TIME_PENDING || time == Fence::SIGNAL_TIME_INVALID) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700727 continue;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700728 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700729
730 nsecs_t sample = time - mReferenceTime;
731 if (sample <= mPhase) {
732 continue;
733 }
734
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -0700735 nsecs_t sampleErr = (sample - mPhase) % mPeriod;
736 if (sampleErr > mPeriod / 2) {
737 sampleErr -= mPeriod;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700738 }
739 sqErrSum += sampleErr * sampleErr;
740 numErrSamples++;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700741 }
742
743 if (numErrSamples > 0) {
744 mError = sqErrSum / numErrSamples;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700745 mZeroErrSamplesCount = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700746 } else {
747 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700748 // Use mod ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT to avoid log spam.
749 mZeroErrSamplesCount++;
Lloyd Pique78ce4182018-01-31 16:39:51 -0800750 ALOGE_IF((mZeroErrSamplesCount % ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT) == 0,
751 "No present times for model error.");
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700752 }
753
Ana Krulec064a82f2018-09-11 16:03:03 -0700754 if (mTraceDetailedInfo) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700755 ATRACE_INT64("DispSync:Error", mError);
756 }
757}
758
759void DispSync::resetErrorLocked() {
760 mPresentSampleOffset = 0;
761 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700762 mZeroErrSamplesCount = 0;
Alec Mourif8e689c2019-05-20 18:32:22 -0700763 if (mTraceDetailedInfo) {
764 ATRACE_INT64("DispSync:Error", mError);
765 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700766 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700767 mPresentFences[i] = FenceTime::NO_FENCE;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700768 }
769}
770
Andy McFadden41d67d72014-04-25 16:58:34 -0700771nsecs_t DispSync::computeNextRefresh(int periodOffset) const {
Andy McFadden150ecd82014-05-08 14:56:50 -0700772 Mutex::Autolock lock(mMutex);
Andy McFadden41d67d72014-04-25 16:58:34 -0700773 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Haixia Shi676b1f62015-10-28 16:19:01 -0700774 nsecs_t phase = mReferenceTime + mPhase;
Marissa Wall17b4e452018-12-26 16:32:34 -0800775 if (mPeriod == 0) {
776 return 0;
777 }
Haixia Shi676b1f62015-10-28 16:19:01 -0700778 return (((now - phase) / mPeriod) + periodOffset + 1) * mPeriod + phase;
Andy McFadden41d67d72014-04-25 16:58:34 -0700779}
780
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700781void DispSync::setIgnorePresentFences(bool ignore) {
782 Mutex::Autolock lock(mMutex);
783 if (mIgnorePresentFences != ignore) {
784 mIgnorePresentFences = ignore;
785 resetLocked();
786 }
787}
788
Yiwei Zhang5434a782018-12-05 18:06:32 -0800789void DispSync::dump(std::string& result) const {
Andy McFaddenc751e922014-05-08 14:53:26 -0700790 Mutex::Autolock lock(mMutex);
Yiwei Zhang5434a782018-12-05 18:06:32 -0800791 StringAppendF(&result, "present fences are %s\n", mIgnorePresentFences ? "ignored" : "used");
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -0700792 StringAppendF(&result, "mPeriod: %" PRId64 " ns (%.3f fps)\n", mPeriod, 1000000000.0 / mPeriod);
Yiwei Zhang5434a782018-12-05 18:06:32 -0800793 StringAppendF(&result, "mPhase: %" PRId64 " ns\n", mPhase);
794 StringAppendF(&result, "mError: %" PRId64 " ns (sqrt=%.1f)\n", mError, sqrt(mError));
795 StringAppendF(&result, "mNumResyncSamplesSincePresent: %d (limit %d)\n",
796 mNumResyncSamplesSincePresent, MAX_RESYNC_SAMPLES_WITHOUT_PRESENT);
797 StringAppendF(&result, "mNumResyncSamples: %zd (max %d)\n", mNumResyncSamples,
798 MAX_RESYNC_SAMPLES);
Andy McFaddenc751e922014-05-08 14:53:26 -0700799
Yiwei Zhang5434a782018-12-05 18:06:32 -0800800 result.append("mResyncSamples:\n");
Andy McFaddenc751e922014-05-08 14:53:26 -0700801 nsecs_t previous = -1;
802 for (size_t i = 0; i < mNumResyncSamples; i++) {
803 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
804 nsecs_t sampleTime = mResyncSamples[idx];
805 if (i == 0) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800806 StringAppendF(&result, " %" PRId64 "\n", sampleTime);
Andy McFaddenc751e922014-05-08 14:53:26 -0700807 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800808 StringAppendF(&result, " %" PRId64 " (+%" PRId64 ")\n", sampleTime,
809 sampleTime - previous);
Andy McFaddenc751e922014-05-08 14:53:26 -0700810 }
811 previous = sampleTime;
812 }
813
Yiwei Zhang5434a782018-12-05 18:06:32 -0800814 StringAppendF(&result, "mPresentFences [%d]:\n", NUM_PRESENT_SAMPLES);
Andy McFadden5167ec62014-05-22 13:08:43 -0700815 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700816 previous = Fence::SIGNAL_TIME_INVALID;
Andy McFaddenc751e922014-05-08 14:53:26 -0700817 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
818 size_t idx = (i + mPresentSampleOffset) % NUM_PRESENT_SAMPLES;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700819 nsecs_t presentTime = mPresentFences[idx]->getSignalTime();
820 if (presentTime == Fence::SIGNAL_TIME_PENDING) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800821 StringAppendF(&result, " [unsignaled fence]\n");
Lloyd Pique78ce4182018-01-31 16:39:51 -0800822 } else if (presentTime == Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800823 StringAppendF(&result, " [invalid fence]\n");
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700824 } else if (previous == Fence::SIGNAL_TIME_PENDING ||
Lloyd Pique78ce4182018-01-31 16:39:51 -0800825 previous == Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800826 StringAppendF(&result, " %" PRId64 " (%.3f ms ago)\n", presentTime,
827 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700828 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -0800829 StringAppendF(&result, " %" PRId64 " (+%" PRId64 " / %.3f) (%.3f ms ago)\n",
830 presentTime, presentTime - previous,
831 (presentTime - previous) / (double)mPeriod,
832 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700833 }
834 previous = presentTime;
835 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700836
Yiwei Zhang5434a782018-12-05 18:06:32 -0800837 StringAppendF(&result, "current monotonic time: %" PRId64 "\n", now);
Andy McFaddenc751e922014-05-08 14:53:26 -0700838}
839
Ana Krulec010d2192018-10-08 06:29:54 -0700840nsecs_t DispSync::expectedPresentTime() {
841 // The HWC doesn't currently have a way to report additional latency.
842 // Assume that whatever we submit now will appear right after the flip.
843 // For a smart panel this might be 1. This is expressed in frames,
844 // rather than time, because we expect to have a constant frame delay
845 // regardless of the refresh rate.
846 const uint32_t hwcLatency = 0;
847
848 // Ask DispSync when the next refresh will be (CLOCK_MONOTONIC).
Ana Krulec757f63a2019-01-25 10:46:18 -0800849 return computeNextRefresh(hwcLatency);
Ana Krulec010d2192018-10-08 06:29:54 -0700850}
851
Lloyd Pique41be5d22018-06-21 13:11:48 -0700852} // namespace impl
853
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700854} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800855
856// TODO(b/129481165): remove the #pragma below and fix conversion issues
857#pragma clang diagnostic pop // ignored "-Wconversion"