blob: ac8aa04e9d4307b1d4d1c338bfdb88f92c8d3559 [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
Mark Salyzyn7823e122016-09-29 08:08:05 -070027#include <log/log.h>
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070028#include <utils/String8.h>
29#include <utils/Thread.h>
30#include <utils/Trace.h>
31#include <utils/Vector.h>
32
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"
Fabien Sanglardc45a7d92017-03-14 13:24:22 -070036#include "SurfaceFlinger.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070037#include "EventLog/EventLog.h"
38
Tim Murray4a4e4a22016-04-19 16:29:23 +000039using std::max;
40using std::min;
41
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070042namespace android {
43
44// Setting this to true enables verbose tracing that can be used to debug
45// vsync event model or phase issues.
Andy McFadden5167ec62014-05-22 13:08:43 -070046static const bool kTraceDetailedInfo = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070047
Tim Murray4a4e4a22016-04-19 16:29:23 +000048// Setting this to true adds a zero-phase tracer for correlating with hardware
49// vsync events
50static const bool kEnableZeroPhaseTracer = false;
51
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070052// This is the threshold used to determine when hardware vsync events are
53// needed to re-synchronize the software vsync model with the hardware. The
54// error metric used is the mean of the squared difference between each
55// present time and the nearest software-predicted vsync.
Andy McFadden5167ec62014-05-22 13:08:43 -070056static const nsecs_t kErrorThreshold = 160000000000; // 400 usec squared
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070057
Tim Murray4a4e4a22016-04-19 16:29:23 +000058#undef LOG_TAG
59#define LOG_TAG "DispSyncThread"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070060class DispSyncThread: public Thread {
61public:
62
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -070063 explicit DispSyncThread(const char* name):
Tim Murray4a4e4a22016-04-19 16:29:23 +000064 mName(name),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070065 mStop(false),
66 mPeriod(0),
67 mPhase(0),
Haixia Shi676b1f62015-10-28 16:19:01 -070068 mReferenceTime(0),
Tim Murray4a4e4a22016-04-19 16:29:23 +000069 mWakeupLatency(0),
70 mFrameNumber(0) {}
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071
72 virtual ~DispSyncThread() {}
73
Haixia Shi676b1f62015-10-28 16:19:01 -070074 void updateModel(nsecs_t period, nsecs_t phase, nsecs_t referenceTime) {
Tim Murray4a4e4a22016-04-19 16:29:23 +000075 if (kTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070076 Mutex::Autolock lock(mMutex);
77 mPeriod = period;
78 mPhase = phase;
Haixia Shi676b1f62015-10-28 16:19:01 -070079 mReferenceTime = referenceTime;
Tim Murray4a4e4a22016-04-19 16:29:23 +000080 ALOGV("[%s] updateModel: mPeriod = %" PRId64 ", mPhase = %" PRId64
81 " mReferenceTime = %" PRId64, mName, ns2us(mPeriod),
82 ns2us(mPhase), ns2us(mReferenceTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070083 mCond.signal();
84 }
85
86 void stop() {
Tim Murray4a4e4a22016-04-19 16:29:23 +000087 if (kTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070088 Mutex::Autolock lock(mMutex);
89 mStop = true;
90 mCond.signal();
91 }
92
93 virtual bool threadLoop() {
94 status_t err;
95 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070096
97 while (true) {
98 Vector<CallbackInvocation> callbackInvocations;
99
100 nsecs_t targetTime = 0;
101
102 { // Scope for lock
103 Mutex::Autolock lock(mMutex);
104
Tim Murray4a4e4a22016-04-19 16:29:23 +0000105 if (kTraceDetailedInfo) {
106 ATRACE_INT64("DispSync:Frame", mFrameNumber);
107 }
108 ALOGV("[%s] Frame %" PRId64, mName, mFrameNumber);
109 ++mFrameNumber;
110
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111 if (mStop) {
112 return false;
113 }
114
115 if (mPeriod == 0) {
116 err = mCond.wait(mMutex);
117 if (err != NO_ERROR) {
118 ALOGE("error waiting for new events: %s (%d)",
119 strerror(-err), err);
120 return false;
121 }
122 continue;
123 }
124
Dan Stoza8f8374d2016-04-19 10:03:46 -0700125 targetTime = computeNextEventTimeLocked(now);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700126
127 bool isWakeup = false;
128
129 if (now < targetTime) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000130 if (kTraceDetailedInfo) ATRACE_NAME("DispSync waiting");
Dan Stoza8f8374d2016-04-19 10:03:46 -0700131
132 if (targetTime == INT64_MAX) {
133 ALOGV("[%s] Waiting forever", mName);
134 err = mCond.wait(mMutex);
135 } else {
136 ALOGV("[%s] Waiting until %" PRId64, mName,
137 ns2us(targetTime));
138 err = mCond.waitRelative(mMutex, targetTime - now);
139 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700140
141 if (err == TIMED_OUT) {
142 isWakeup = true;
143 } else if (err != NO_ERROR) {
144 ALOGE("error waiting for next event: %s (%d)",
145 strerror(-err), err);
146 return false;
147 }
148 }
149
150 now = systemTime(SYSTEM_TIME_MONOTONIC);
151
Tim Murray4a4e4a22016-04-19 16:29:23 +0000152 // Don't correct by more than 1.5 ms
153 static const nsecs_t kMaxWakeupLatency = us2ns(1500);
154
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700155 if (isWakeup) {
156 mWakeupLatency = ((mWakeupLatency * 63) +
157 (now - targetTime)) / 64;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000158 mWakeupLatency = min(mWakeupLatency, kMaxWakeupLatency);
Andy McFadden5167ec62014-05-22 13:08:43 -0700159 if (kTraceDetailedInfo) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000160 ATRACE_INT64("DispSync:WakeupLat", now - targetTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700161 ATRACE_INT64("DispSync:AvgWakeupLat", mWakeupLatency);
162 }
163 }
164
165 callbackInvocations = gatherCallbackInvocationsLocked(now);
166 }
167
168 if (callbackInvocations.size() > 0) {
Andy McFadden645b1f72014-06-10 14:43:32 -0700169 fireCallbackInvocations(callbackInvocations);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700170 }
171 }
172
173 return false;
174 }
175
Tim Murray4a4e4a22016-04-19 16:29:23 +0000176 status_t addEventListener(const char* name, nsecs_t phase,
177 const sp<DispSync::Callback>& callback) {
178 if (kTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700179 Mutex::Autolock lock(mMutex);
180
181 for (size_t i = 0; i < mEventListeners.size(); i++) {
182 if (mEventListeners[i].mCallback == callback) {
183 return BAD_VALUE;
184 }
185 }
186
187 EventListener listener;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000188 listener.mName = name;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700189 listener.mPhase = phase;
190 listener.mCallback = callback;
Jamie Gennis629b9872013-10-29 13:36:12 -0700191
192 // We want to allow the firstmost future event to fire without
Tim Murray4a4e4a22016-04-19 16:29:23 +0000193 // allowing any past events to fire
194 listener.mLastEventTime = systemTime() - mPeriod / 2 + mPhase -
195 mWakeupLatency;
Jamie Gennis629b9872013-10-29 13:36:12 -0700196
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700197 mEventListeners.push(listener);
198
199 mCond.signal();
200
201 return NO_ERROR;
202 }
203
204 status_t removeEventListener(const sp<DispSync::Callback>& callback) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000205 if (kTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700206 Mutex::Autolock lock(mMutex);
207
208 for (size_t i = 0; i < mEventListeners.size(); i++) {
209 if (mEventListeners[i].mCallback == callback) {
210 mEventListeners.removeAt(i);
211 mCond.signal();
212 return NO_ERROR;
213 }
214 }
215
216 return BAD_VALUE;
217 }
218
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800219 // This method is only here to handle the !SurfaceFlinger::hasSyncFramework
220 // case.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700221 bool hasAnyEventListeners() {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000222 if (kTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700223 Mutex::Autolock lock(mMutex);
224 return !mEventListeners.empty();
225 }
226
227private:
228
229 struct EventListener {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000230 const char* mName;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700231 nsecs_t mPhase;
232 nsecs_t mLastEventTime;
233 sp<DispSync::Callback> mCallback;
234 };
235
236 struct CallbackInvocation {
237 sp<DispSync::Callback> mCallback;
238 nsecs_t mEventTime;
239 };
240
241 nsecs_t computeNextEventTimeLocked(nsecs_t now) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000242 if (kTraceDetailedInfo) ATRACE_CALL();
243 ALOGV("[%s] computeNextEventTimeLocked", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700244 nsecs_t nextEventTime = INT64_MAX;
245 for (size_t i = 0; i < mEventListeners.size(); i++) {
246 nsecs_t t = computeListenerNextEventTimeLocked(mEventListeners[i],
247 now);
248
249 if (t < nextEventTime) {
250 nextEventTime = t;
251 }
252 }
253
Tim Murray4a4e4a22016-04-19 16:29:23 +0000254 ALOGV("[%s] nextEventTime = %" PRId64, mName, ns2us(nextEventTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700255 return nextEventTime;
256 }
257
258 Vector<CallbackInvocation> gatherCallbackInvocationsLocked(nsecs_t now) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000259 if (kTraceDetailedInfo) ATRACE_CALL();
260 ALOGV("[%s] gatherCallbackInvocationsLocked @ %" PRId64, mName,
261 ns2us(now));
262
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700263 Vector<CallbackInvocation> callbackInvocations;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000264 nsecs_t onePeriodAgo = now - mPeriod;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700265
266 for (size_t i = 0; i < mEventListeners.size(); i++) {
267 nsecs_t t = computeListenerNextEventTimeLocked(mEventListeners[i],
Tim Murray4a4e4a22016-04-19 16:29:23 +0000268 onePeriodAgo);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700269
Jamie Gennis0d5c60e2013-10-09 17:49:37 -0700270 if (t < now) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700271 CallbackInvocation ci;
272 ci.mCallback = mEventListeners[i].mCallback;
273 ci.mEventTime = t;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000274 ALOGV("[%s] [%s] Preparing to fire", mName,
275 mEventListeners[i].mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700276 callbackInvocations.push(ci);
277 mEventListeners.editItemAt(i).mLastEventTime = t;
278 }
279 }
280
281 return callbackInvocations;
282 }
283
284 nsecs_t computeListenerNextEventTimeLocked(const EventListener& listener,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000285 nsecs_t baseTime) {
286 if (kTraceDetailedInfo) ATRACE_CALL();
287 ALOGV("[%s] [%s] computeListenerNextEventTimeLocked(%" PRId64 ")",
288 mName, listener.mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700289
Tim Murray4a4e4a22016-04-19 16:29:23 +0000290 nsecs_t lastEventTime = listener.mLastEventTime + mWakeupLatency;
291 ALOGV("[%s] lastEventTime: %" PRId64, mName, ns2us(lastEventTime));
292 if (baseTime < lastEventTime) {
293 baseTime = lastEventTime;
294 ALOGV("[%s] Clamping baseTime to lastEventTime -> %" PRId64, mName,
295 ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700296 }
297
Tim Murray4a4e4a22016-04-19 16:29:23 +0000298 baseTime -= mReferenceTime;
299 ALOGV("[%s] Relative baseTime = %" PRId64, mName, ns2us(baseTime));
300 nsecs_t phase = mPhase + listener.mPhase;
301 ALOGV("[%s] Phase = %" PRId64, mName, ns2us(phase));
302 baseTime -= phase;
303 ALOGV("[%s] baseTime - phase = %" PRId64, mName, ns2us(baseTime));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700304
Tim Murray4a4e4a22016-04-19 16:29:23 +0000305 // If our previous time is before the reference (because the reference
306 // has since been updated), the division by mPeriod will truncate
307 // towards zero instead of computing the floor. Since in all cases
308 // before the reference we want the next time to be effectively now, we
309 // set baseTime to -mPeriod so that numPeriods will be -1.
310 // When we add 1 and the phase, we will be at the correct event time for
311 // this period.
312 if (baseTime < 0) {
313 ALOGV("[%s] Correcting negative baseTime", mName);
314 baseTime = -mPeriod;
315 }
316
317 nsecs_t numPeriods = baseTime / mPeriod;
318 ALOGV("[%s] numPeriods = %" PRId64, mName, numPeriods);
319 nsecs_t t = (numPeriods + 1) * mPeriod + phase;
320 ALOGV("[%s] t = %" PRId64, mName, ns2us(t));
321 t += mReferenceTime;
322 ALOGV("[%s] Absolute t = %" PRId64, mName, ns2us(t));
323
324 // Check that it's been slightly more than half a period since the last
325 // event so that we don't accidentally fall into double-rate vsyncs
326 if (t - listener.mLastEventTime < (3 * mPeriod / 5)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700327 t += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000328 ALOGV("[%s] Modifying t -> %" PRId64, mName, ns2us(t));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700329 }
330
Tim Murray4a4e4a22016-04-19 16:29:23 +0000331 t -= mWakeupLatency;
332 ALOGV("[%s] Corrected for wakeup latency -> %" PRId64, mName, ns2us(t));
333
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700334 return t;
335 }
336
337 void fireCallbackInvocations(const Vector<CallbackInvocation>& callbacks) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000338 if (kTraceDetailedInfo) ATRACE_CALL();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700339 for (size_t i = 0; i < callbacks.size(); i++) {
340 callbacks[i].mCallback->onDispSyncEvent(callbacks[i].mEventTime);
341 }
342 }
343
Tim Murray4a4e4a22016-04-19 16:29:23 +0000344 const char* const mName;
345
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700346 bool mStop;
347
348 nsecs_t mPeriod;
349 nsecs_t mPhase;
Haixia Shi676b1f62015-10-28 16:19:01 -0700350 nsecs_t mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700351 nsecs_t mWakeupLatency;
352
Tim Murray4a4e4a22016-04-19 16:29:23 +0000353 int64_t mFrameNumber;
354
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700355 Vector<EventListener> mEventListeners;
356
357 Mutex mMutex;
358 Condition mCond;
359};
360
Tim Murray4a4e4a22016-04-19 16:29:23 +0000361#undef LOG_TAG
362#define LOG_TAG "DispSync"
363
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700364class ZeroPhaseTracer : public DispSync::Callback {
365public:
366 ZeroPhaseTracer() : mParity(false) {}
367
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700368 virtual void onDispSyncEvent(nsecs_t /*when*/) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700369 mParity = !mParity;
370 ATRACE_INT("ZERO_PHASE_VSYNC", mParity ? 1 : 0);
371 }
372
373private:
374 bool mParity;
375};
376
Tim Murray4a4e4a22016-04-19 16:29:23 +0000377DispSync::DispSync(const char* name) :
378 mName(name),
Andy McFadden645b1f72014-06-10 14:43:32 -0700379 mRefreshSkipCount(0),
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800380 mThread(new DispSyncThread(name)),
381 mIgnorePresentFences(!SurfaceFlinger::hasSyncFramework){
Andy McFadden645b1f72014-06-10 14:43:32 -0700382
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700383 mPresentTimeOffset = SurfaceFlinger::dispSyncPresentTimeOffset;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700384 mThread->run("DispSync", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
Tim Murrayacff43d2016-07-29 13:57:24 -0700385 // set DispSync to SCHED_FIFO to minimize jitter
386 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700387 param.sched_priority = 2;
Tim Murrayacff43d2016-07-29 13:57:24 -0700388 if (sched_setscheduler(mThread->getTid(), SCHED_FIFO, &param) != 0) {
389 ALOGE("Couldn't set SCHED_FIFO for DispSyncThread");
390 }
391
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700392
393 reset();
394 beginResync();
395
Andy McFadden5167ec62014-05-22 13:08:43 -0700396 if (kTraceDetailedInfo) {
397 // If we're not getting present fences then the ZeroPhaseTracer
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700398 // would prevent HW vsync event from ever being turned off.
Andy McFadden5167ec62014-05-22 13:08:43 -0700399 // Even if we're just ignoring the fences, the zero-phase tracing is
400 // not needed because any time there is an event registered we will
401 // turn on the HW vsync events.
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800402 if (!mIgnorePresentFences && kEnableZeroPhaseTracer) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000403 addEventListener("ZeroPhaseTracer", 0, new ZeroPhaseTracer());
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700404 }
405 }
406}
407
408DispSync::~DispSync() {}
409
410void DispSync::reset() {
411 Mutex::Autolock lock(mMutex);
412
Haixia Shi676b1f62015-10-28 16:19:01 -0700413 mPhase = 0;
414 mReferenceTime = 0;
415 mModelUpdated = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 mNumResyncSamples = 0;
417 mFirstResyncSample = 0;
418 mNumResyncSamplesSincePresent = 0;
419 resetErrorLocked();
420}
421
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700422bool DispSync::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423 Mutex::Autolock lock(mMutex);
424
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700425 mPresentFences[mPresentSampleOffset] = fenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700426 mPresentSampleOffset = (mPresentSampleOffset + 1) % NUM_PRESENT_SAMPLES;
427 mNumResyncSamplesSincePresent = 0;
428
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429 updateErrorLocked();
430
Haixia Shi676b1f62015-10-28 16:19:01 -0700431 return !mModelUpdated || mError > kErrorThreshold;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432}
433
434void DispSync::beginResync() {
435 Mutex::Autolock lock(mMutex);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000436 ALOGV("[%s] beginResync", mName);
Haixia Shi676b1f62015-10-28 16:19:01 -0700437 mModelUpdated = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 mNumResyncSamples = 0;
439}
440
441bool DispSync::addResyncSample(nsecs_t timestamp) {
442 Mutex::Autolock lock(mMutex);
443
Tim Murray4a4e4a22016-04-19 16:29:23 +0000444 ALOGV("[%s] addResyncSample(%" PRId64 ")", mName, ns2us(timestamp));
445
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446 size_t idx = (mFirstResyncSample + mNumResyncSamples) % MAX_RESYNC_SAMPLES;
447 mResyncSamples[idx] = timestamp;
Haixia Shi664339a2015-10-28 13:22:22 -0700448 if (mNumResyncSamples == 0) {
Haixia Shi676b1f62015-10-28 16:19:01 -0700449 mPhase = 0;
450 mReferenceTime = timestamp;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000451 ALOGV("[%s] First resync sample: mPeriod = %" PRId64 ", mPhase = 0, "
452 "mReferenceTime = %" PRId64, mName, ns2us(mPeriod),
453 ns2us(mReferenceTime));
454 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
Haixia Shi664339a2015-10-28 13:22:22 -0700455 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700456
457 if (mNumResyncSamples < MAX_RESYNC_SAMPLES) {
458 mNumResyncSamples++;
459 } else {
460 mFirstResyncSample = (mFirstResyncSample + 1) % MAX_RESYNC_SAMPLES;
461 }
462
463 updateModelLocked();
464
465 if (mNumResyncSamplesSincePresent++ > MAX_RESYNC_SAMPLES_WITHOUT_PRESENT) {
466 resetErrorLocked();
467 }
468
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800469 if (mIgnorePresentFences) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470 // If we don't have the sync framework we will never have
471 // addPresentFence called. This means we have no way to know whether
472 // or not we're synchronized with the HW vsyncs, so we just request
473 // that the HW vsync events be turned on whenever we need to generate
474 // SW vsync events.
475 return mThread->hasAnyEventListeners();
476 }
477
Tim Murray4a4e4a22016-04-19 16:29:23 +0000478 // Check against kErrorThreshold / 2 to add some hysteresis before having to
479 // resync again
480 bool modelLocked = mModelUpdated && mError < (kErrorThreshold / 2);
481 ALOGV("[%s] addResyncSample returning %s", mName,
482 modelLocked ? "locked" : "unlocked");
483 return !modelLocked;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700484}
485
486void DispSync::endResync() {
487}
488
Tim Murray4a4e4a22016-04-19 16:29:23 +0000489status_t DispSync::addEventListener(const char* name, nsecs_t phase,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700490 const sp<Callback>& callback) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700491 Mutex::Autolock lock(mMutex);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000492 return mThread->addEventListener(name, phase, callback);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700493}
494
Andy McFadden645b1f72014-06-10 14:43:32 -0700495void DispSync::setRefreshSkipCount(int count) {
496 Mutex::Autolock lock(mMutex);
497 ALOGD("setRefreshSkipCount(%d)", count);
498 mRefreshSkipCount = count;
499 updateModelLocked();
Ruchi Kandoif52b3c82014-04-24 16:42:35 -0700500}
501
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502status_t DispSync::removeEventListener(const sp<Callback>& callback) {
503 Mutex::Autolock lock(mMutex);
504 return mThread->removeEventListener(callback);
505}
506
507void DispSync::setPeriod(nsecs_t period) {
508 Mutex::Autolock lock(mMutex);
509 mPeriod = period;
510 mPhase = 0;
Haixia Shi676b1f62015-10-28 16:19:01 -0700511 mReferenceTime = 0;
512 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700513}
514
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700515nsecs_t DispSync::getPeriod() {
516 // lock mutex as mPeriod changes multiple times in updateModelLocked
517 Mutex::Autolock lock(mMutex);
518 return mPeriod;
519}
520
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521void DispSync::updateModelLocked() {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000522 ALOGV("[%s] updateModelLocked %zu", mName, mNumResyncSamples);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523 if (mNumResyncSamples >= MIN_RESYNC_SAMPLES_FOR_UPDATE) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000524 ALOGV("[%s] Computing...", mName);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 nsecs_t durationSum = 0;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000526 nsecs_t minDuration = INT64_MAX;
527 nsecs_t maxDuration = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700528 for (size_t i = 1; i < mNumResyncSamples; i++) {
529 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
530 size_t prev = (idx + MAX_RESYNC_SAMPLES - 1) % MAX_RESYNC_SAMPLES;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000531 nsecs_t duration = mResyncSamples[idx] - mResyncSamples[prev];
532 durationSum += duration;
533 minDuration = min(minDuration, duration);
534 maxDuration = max(maxDuration, duration);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700535 }
536
Tim Murray4a4e4a22016-04-19 16:29:23 +0000537 // Exclude the min and max from the average
538 durationSum -= minDuration + maxDuration;
539 mPeriod = durationSum / (mNumResyncSamples - 3);
540
541 ALOGV("[%s] mPeriod = %" PRId64, mName, ns2us(mPeriod));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542
543 double sampleAvgX = 0;
544 double sampleAvgY = 0;
545 double scale = 2.0 * M_PI / double(mPeriod);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000546 // Intentionally skip the first sample
547 for (size_t i = 1; i < mNumResyncSamples; i++) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
Haixia Shi676b1f62015-10-28 16:19:01 -0700549 nsecs_t sample = mResyncSamples[idx] - mReferenceTime;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550 double samplePhase = double(sample % mPeriod) * scale;
551 sampleAvgX += cos(samplePhase);
552 sampleAvgY += sin(samplePhase);
553 }
554
Tim Murray4a4e4a22016-04-19 16:29:23 +0000555 sampleAvgX /= double(mNumResyncSamples - 1);
556 sampleAvgY /= double(mNumResyncSamples - 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700557
558 mPhase = nsecs_t(atan2(sampleAvgY, sampleAvgX) / scale);
559
Tim Murray4a4e4a22016-04-19 16:29:23 +0000560 ALOGV("[%s] mPhase = %" PRId64, mName, ns2us(mPhase));
561
562 if (mPhase < -(mPeriod / 2)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700563 mPhase += mPeriod;
Tim Murray4a4e4a22016-04-19 16:29:23 +0000564 ALOGV("[%s] Adjusting mPhase -> %" PRId64, mName, ns2us(mPhase));
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700565 }
566
Andy McFadden5167ec62014-05-22 13:08:43 -0700567 if (kTraceDetailedInfo) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568 ATRACE_INT64("DispSync:Period", mPeriod);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000569 ATRACE_INT64("DispSync:Phase", mPhase + mPeriod / 2);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700570 }
571
Andy McFadden645b1f72014-06-10 14:43:32 -0700572 // Artificially inflate the period if requested.
573 mPeriod += mPeriod * mRefreshSkipCount;
574
Haixia Shi676b1f62015-10-28 16:19:01 -0700575 mThread->updateModel(mPeriod, mPhase, mReferenceTime);
576 mModelUpdated = true;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 }
578}
579
580void DispSync::updateErrorLocked() {
Haixia Shi676b1f62015-10-28 16:19:01 -0700581 if (!mModelUpdated) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700582 return;
583 }
584
Andy McFadden645b1f72014-06-10 14:43:32 -0700585 // Need to compare present fences against the un-adjusted refresh period,
586 // since they might arrive between two events.
587 nsecs_t period = mPeriod / (1 + mRefreshSkipCount);
588
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589 int numErrSamples = 0;
590 nsecs_t sqErrSum = 0;
591
592 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700593 // Only check for the cached value of signal time to avoid unecessary
594 // syscalls. It is the responsibility of the DispSync owner to
595 // call getSignalTime() periodically so the cache is updated when the
596 // fence signals.
597 nsecs_t time = mPresentFences[i]->getCachedSignalTime();
598 if (time == Fence::SIGNAL_TIME_PENDING ||
599 time == Fence::SIGNAL_TIME_INVALID) {
600 continue;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700601 }
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700602
603 nsecs_t sample = time - mReferenceTime;
604 if (sample <= mPhase) {
605 continue;
606 }
607
608 nsecs_t sampleErr = (sample - mPhase) % period;
609 if (sampleErr > period / 2) {
610 sampleErr -= period;
611 }
612 sqErrSum += sampleErr * sampleErr;
613 numErrSamples++;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700614 }
615
616 if (numErrSamples > 0) {
617 mError = sqErrSum / numErrSamples;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700618 mZeroErrSamplesCount = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700619 } else {
620 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700621 // Use mod ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT to avoid log spam.
622 mZeroErrSamplesCount++;
623 ALOGE_IF(
624 (mZeroErrSamplesCount % ACCEPTABLE_ZERO_ERR_SAMPLES_COUNT) == 0,
625 "No present times for model error.");
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700626 }
627
Andy McFadden5167ec62014-05-22 13:08:43 -0700628 if (kTraceDetailedInfo) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700629 ATRACE_INT64("DispSync:Error", mError);
630 }
631}
632
633void DispSync::resetErrorLocked() {
634 mPresentSampleOffset = 0;
635 mError = 0;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700636 mZeroErrSamplesCount = 0;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700637 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700638 mPresentFences[i] = FenceTime::NO_FENCE;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700639 }
640}
641
Andy McFadden41d67d72014-04-25 16:58:34 -0700642nsecs_t DispSync::computeNextRefresh(int periodOffset) const {
Andy McFadden150ecd82014-05-08 14:56:50 -0700643 Mutex::Autolock lock(mMutex);
Andy McFadden41d67d72014-04-25 16:58:34 -0700644 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Haixia Shi676b1f62015-10-28 16:19:01 -0700645 nsecs_t phase = mReferenceTime + mPhase;
646 return (((now - phase) / mPeriod) + periodOffset + 1) * mPeriod + phase;
Andy McFadden41d67d72014-04-25 16:58:34 -0700647}
648
Andy McFaddenc751e922014-05-08 14:53:26 -0700649void DispSync::dump(String8& result) const {
650 Mutex::Autolock lock(mMutex);
Andy McFadden5167ec62014-05-22 13:08:43 -0700651 result.appendFormat("present fences are %s\n",
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800652 mIgnorePresentFences ? "ignored" : "used");
Andy McFadden645b1f72014-06-10 14:43:32 -0700653 result.appendFormat("mPeriod: %" PRId64 " ns (%.3f fps; skipCount=%d)\n",
654 mPeriod, 1000000000.0 / mPeriod, mRefreshSkipCount);
Andy McFadden5167ec62014-05-22 13:08:43 -0700655 result.appendFormat("mPhase: %" PRId64 " ns\n", mPhase);
656 result.appendFormat("mError: %" PRId64 " ns (sqrt=%.1f)\n",
Andy McFaddenc751e922014-05-08 14:53:26 -0700657 mError, sqrt(mError));
Andy McFadden5167ec62014-05-22 13:08:43 -0700658 result.appendFormat("mNumResyncSamplesSincePresent: %d (limit %d)\n",
Andy McFaddenc751e922014-05-08 14:53:26 -0700659 mNumResyncSamplesSincePresent, MAX_RESYNC_SAMPLES_WITHOUT_PRESENT);
Andy McFadden5167ec62014-05-22 13:08:43 -0700660 result.appendFormat("mNumResyncSamples: %zd (max %d)\n",
Andy McFaddenc751e922014-05-08 14:53:26 -0700661 mNumResyncSamples, MAX_RESYNC_SAMPLES);
662
663 result.appendFormat("mResyncSamples:\n");
664 nsecs_t previous = -1;
665 for (size_t i = 0; i < mNumResyncSamples; i++) {
666 size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
667 nsecs_t sampleTime = mResyncSamples[idx];
668 if (i == 0) {
Andy McFadden5167ec62014-05-22 13:08:43 -0700669 result.appendFormat(" %" PRId64 "\n", sampleTime);
Andy McFaddenc751e922014-05-08 14:53:26 -0700670 } else {
Andy McFadden5167ec62014-05-22 13:08:43 -0700671 result.appendFormat(" %" PRId64 " (+%" PRId64 ")\n",
Andy McFaddenc751e922014-05-08 14:53:26 -0700672 sampleTime, sampleTime - previous);
673 }
674 previous = sampleTime;
675 }
676
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700677 result.appendFormat("mPresentFences [%d]:\n",
Andy McFaddenc751e922014-05-08 14:53:26 -0700678 NUM_PRESENT_SAMPLES);
Andy McFadden5167ec62014-05-22 13:08:43 -0700679 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700680 previous = Fence::SIGNAL_TIME_INVALID;
Andy McFaddenc751e922014-05-08 14:53:26 -0700681 for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
682 size_t idx = (i + mPresentSampleOffset) % NUM_PRESENT_SAMPLES;
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700683 nsecs_t presentTime = mPresentFences[idx]->getSignalTime();
684 if (presentTime == Fence::SIGNAL_TIME_PENDING) {
Andy McFaddenc751e922014-05-08 14:53:26 -0700685 result.appendFormat(" [unsignaled fence]\n");
Brian Andersonfbc80ae2017-05-26 16:23:54 -0700686 } else if(presentTime == Fence::SIGNAL_TIME_INVALID) {
687 result.appendFormat(" [invalid fence]\n");
688 } else if (previous == Fence::SIGNAL_TIME_PENDING ||
689 previous == Fence::SIGNAL_TIME_INVALID) {
Andy McFadden5167ec62014-05-22 13:08:43 -0700690 result.appendFormat(" %" PRId64 " (%.3f ms ago)\n", presentTime,
691 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700692 } else {
Andy McFadden5167ec62014-05-22 13:08:43 -0700693 result.appendFormat(" %" PRId64 " (+%" PRId64 " / %.3f) (%.3f ms ago)\n",
Andy McFaddenc751e922014-05-08 14:53:26 -0700694 presentTime, presentTime - previous,
Andy McFadden5167ec62014-05-22 13:08:43 -0700695 (presentTime - previous) / (double) mPeriod,
696 (now - presentTime) / 1000000.0);
Andy McFaddenc751e922014-05-08 14:53:26 -0700697 }
698 previous = presentTime;
699 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700700
701 result.appendFormat("current monotonic time: %" PRId64 "\n", now);
Andy McFaddenc751e922014-05-08 14:53:26 -0700702}
703
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700704} // namespace android