SurfaceFlinger Vsync(一) app vsync
1
app请求vsync入口
// frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp
void EventThreadConnection::requestNextVsync() {
ATRACE_NAME("requestNextVsync");
mEventThread->requestNextVsync(this);
}
EventThreadConnection继承BnDisplayEventConnection,Bp端在APP侧,这个后续分析。
EventThreadConnection就是app和sf通信的binder桥梁。
void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
if (connection->resyncCallback) {
connection->resyncCallback();
}
std::lock_guard<std::mutex> lock(mMutex);
if (connection->vsyncRequest == VSyncRequest::None) {
// mark A
connection->vsyncRequest = VSyncRequest::Single;
// mark B
mCondition.notify_all();
}
}
EventThread::requestNextVsync主要设置connection->vsyncRequest = Single,并调用条件变量,
有notify的地方,就有wait的地方。
在EventThread构造函数里,起了一个子线程,并运行threadMain函数,wait就在该函数中,
下面详细解释该函数:
void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
DisplayEventConsumers consumers;
while (mState != State::Quit) {
std::optional<DisplayEventReceiver::Event> event;
// Determine next event to dispatch.
// 第一次进来mPendingEvents为空,mark C
if (!mPendingEvents.empty()) {
event = mPendingEvents.front();
mPendingEvents.pop_front();
switch (event->header.type) {
case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
if (event->hotplug.connected && !mVSyncState) {
mVSyncState.emplace(event->header.displayId);
} else if (!event->hotplug.connected && mVSyncState &&
mVSyncState->displayId == event->header.displayId) {
mVSyncState.reset();
}
break;
case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
if (mInterceptVSyncsCallback) {
mInterceptVSyncsCallback(event->header.timestamp);
}
break;
}
}
bool vsyncRequested = false;
// Find connections that should consume this event.
// 所有和EventThread建立链接的APP的connection都会保存在mDisplayEventConnections
auto it = mDisplayEventConnections.begin();
while (it != mDisplayEventConnections.end()) {
if (const auto connection = it->promote()) {
// 只要有一个connection的vsyncRequest != None,vsyncRequested就等于true,
// 上面mark A处已经给connection->vsyncRequest设置了Single
vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
if (event && shouldConsumeEvent(*event, connection)) {
consumers.push_back(connection);
}
++it;
} else {
it = mDisplayEventConnections.erase(it);
}
}
// 第一次进来consumers为空,TODO
if (!consumers.empty()) {
dispatchEvent(*event, consumers);
consumers.clear();
}
State nextState;
// mVSyncState被定义为std::optional,所以不为空,mVSyncState上面被赋值为true
if (mVSyncState && mVSyncState ) {
// nextState = VSync
nextState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
} else {
ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
nextState = State::Idle;
}
// 第一次进来mState = None,所以走else if
if (mState != nextState) {
if (mState == State::VSync) {
mVSyncSource->setVSyncEnabled(false);
} else if (nextState == State::VSync) {
// mVSyncSource 是啥?哪来的?TODO
// 参考下面2.1,分析内部流程
mVSyncSource->setVSyncEnabled(true);
}
mState = nextState;
}
if (event) {
continue;
}
// Wait for event or client registration/request.
if (mState == State::Idle) {
mCondition.wait(lock);
} else {
// Generate a fake VSYNC after a long timeout in case the driver stalls. When the
// display is off, keep feeding clients at 60 Hz.
const std::chrono::nanoseconds timeout =
mState == State::SyntheticVSync ? 16ms : 1000ms;
if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
if (mState == State::VSync) {
ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
std::string debugInfo = "VsyncSource debug info:\n";
mVSyncSource->dump(debugInfo);
// Log the debug info line-by-line to avoid logcat overflow
auto pos = debugInfo.find('\n');
while (pos != std::string::npos) {
ALOGW("%s", debugInfo.substr(0, pos).c_str());
debugInfo = debugInfo.substr(pos + 1);
pos = debugInfo.find('\n');
}
}
LOG_FATAL_IF(!mVSyncState);
const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
const auto expectedVSyncTime = now + timeout.count();
mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
++mVSyncState->count, expectedVSyncTime));
}
}
}
}
2.1
frameworks/native/services/surfaceflinger/Scheduler/DispSyncSource.cpp
void DispSyncSource::setVSyncEnabled(bool enable) {
std::lock_guard lock(mVsyncMutex);
if (enable) {
// 走这里,mCallbackRepeater 又是什么,怎么赋值?
mCallbackRepeater->start(mWorkDuration, mReadyDuration);
// ATRACE_INT(mVsyncOnLabel.c_str(), 1);
} else {
mCallbackRepeater->stop();
// ATRACE_INT(mVsyncOnLabel.c_str(), 0);
}
mEnabled = enable;
}
class CallbackRepeater {
void start(std::chrono::nanoseconds workDuration, std::chrono::nanoseconds readyDuration) {
...
// // 走这里,mRegistration 又是什么,怎么赋值?
auto const scheduleResult =
mRegistration.schedule({.workDuration = mWorkDuration.count(),
.readyDuration = mReadyDuration.count(),
.earliestVsync = mLastCallTime.count()});
}
frameworks/native/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp
ScheduleResult VSyncDispatchTimerQueue::schedule(CallbackToken token,
ScheduleTiming scheduleTiming) {
...
// 参考下面2.2,等待下一个sw_vsync,也就是下一个唤醒时间
result = callback->schedule(scheduleTiming, mTracker, now);
...
// mIntendedWakeupTime 默认值无穷大,走进if
if (callback->wakeupTime() < mIntendedWakeupTime - mTimerSlack) {
// 参考2.3,计时开始
rearmTimerSkippingUpdateFor(now, it);
}
}
}
2.2
ScheduleResult VSyncDispatchTimerQueueEntry::schedule(VSyncDispatch::ScheduleTiming timing,
VSyncTracker& tracker, nsecs_t now) {
// timing.workDuration:app vsync 工作周期,通常16.5
// timing.readyDuration: app vsync 等待周期,通常15.6
// nextVsyncTime 这里就是预测出下一个hw vsync时间
auto nextVsyncTime = tracker.nextAnticipatedVSyncTimeFrom(
std::max(timing.earliestVsync, now + timing.workDuration + timing.readyDuration));
// 用下一个hw sync周期减去app的vsync准备时间,就是下一个sw sync时间,即下一次唤醒时间
auto nextWakeupTime = nextVsyncTime - timing.workDuration - timing.readyDuration;
...
// 这里就是返回下一个sw sync时间
return getExpectedCallbackTime(nextVsyncTime, timing);
}
2.3
frameworks/native/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp
void VSyncDispatchTimerQueue::rearmTimerSkippingUpdateFor(
nsecs_t now, CallbackMap::iterator const& skipUpdateIt) {
std::optional<nsecs_t> min;
...
auto const wakeupTime = *callback->wakeupTime();
if (!min || (min && *min > wakeupTime)) {
nextWakeupName = callback->name();
min = wakeupTime;
targetVsync = callback->targetVsync();
}
}
if (min && (min < mIntendedWakeupTime)) {
if (targetVsync && nextWakeupName) {
mTraceBuffer.note(*nextWakeupName, *min - now, *targetVsync - now);
}
// 在这里启动计时
setTimer(*min, now);
} else {
ATRACE_NAME("cancel timer");
cancelTimer();
}
}
void VSyncDispatchTimerQueue::setTimer(nsecs_t targetTime, nsecs_t /*now*/) {
mIntendedWakeupTime = targetTime;
mTimeKeeper->alarmAt(std::bind(&VSyncDispatchTimerQueue::timerCallback, this),
mIntendedWakeupTime);
mLastTimerSchedule = mTimeKeeper->now();
}
/frameworks/native/services/surfaceflinger/Scheduler/Timer.cpp
void Timer::alarmAt(std::function<void()> const& cb, nsecs_t time) {
...
// mCallback 就是VSyncDispatchTimerQueue的timerCallback函数
mCallback = cb;
...
if (timerfd_settime(mTimerFd, TFD_TIMER_ABSTIME, &new_timer, &old_timer)) {
ALOGW("Failed to set timerfd %s (%i)", strerror(errno), errno);
}
}
Timer类在构造函数中,拉起一个子线程,子线程while一直调用dispatch函数,通过epoll机制,监听mTimerFd(在上面函数Timer::alarmAt,设置了mTimerFd),如果监听到,就会调用mCallback,
也就是VSyncDispatchTimerQueue的timerCallback函数
bool Timer::dispatch() {
...
if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mTimerFd, &timerEvent) == -1) {
ALOGE("Error adding timer fd to epoll dispatch loop");
return true;
}
...
while (true) {
...
int nfds = epoll_wait(mEpollFd, events, DispatchType::MAX_DISPATCH_TYPE, -1);
...
cb = mCallback;
cb();
}
}
frameworks/native/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp
void VSyncDispatchTimerQueue::timerCallback() {
struct Invocation {
std::shared_ptr<VSyncDispatchTimerQueueEntry> callback;
nsecs_t vsyncTimestamp;
nsecs_t wakeupTimestamp;
nsecs_t deadlineTimestamp;
};
std::vector<Invocation> invocations;
{
std::lock_guard lock(mMutex);
auto const now = mTimeKeeper->now();
mLastTimerCallback = now;
// mCallbacks有三个成员app, sf, sfApp, 后续分析
for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
auto& callback = it->second;
// 此时不为空
auto const wakeupTime = callback->wakeupTime();
if (!wakeupTime) {
continue;
}
auto const readyTime = callback->readyTime();
auto const lagAllowance = std::max(now - mIntendedWakeupTime, static_cast<nsecs_t>(0));
if (*wakeupTime < mIntendedWakeupTime + mTimerSlack + lagAllowance) {
// 这里就是把VSyncDispatchTimerQueue.cpp中的mArmedInfo置为空,
// 而mArmedInfo就是上面callback->wakeupTime()
callback->executing();
// 将要回调的函数加入队列,在下面调用
invocations.emplace_back(Invocation{callback, *callback->lastExecutedVsyncTarget(),
*wakeupTime, *readyTime});
}
}
mIntendedWakeupTime = kInvalidTime;
rearmTimer(mTimeKeeper->now());
}
for (auto const& invocation : invocations) {
// 这里就是调用 VSyncDispatchTimerQueueEntry::callback, 通过上面的Invocation定义便可得出
invocation.callback->callback(invocation.vsyncTimestamp, invocation.wakeupTimestamp,
invocation.deadlineTimestamp);
}
}
void VSyncDispatchTimerQueueEntry::callback(nsecs_t vsyncTimestamp, nsecs_t wakeupTimestamp,
nsecs_t deadlineTimestamp) {
...
// 这个mCallback是哪来的,看下面调用链
mCallback(vsyncTimestamp, wakeupTimestamp, deadlineTimestamp);
;
}
3
3.1
在surfaceFlinger的初始化时,会调用
void SurfaceFlinger::initScheduler(const sp<DisplayDevice>& display) {
...
// start the EventThread
// 在这里会创建Scheduler,在Scheduler的构造过程中,会new 一个VsyncSchedule结构体,
// 结构体中的dispatch成员,又会new一个VSyncDispatchTimerQueue对象,
mScheduler = getFactory().createScheduler(display->holdRefreshRateConfigs(), *this);
...
// 这里看起来时创建一个和app的connection,后续分析怎么联系起来的。
mAppConnectionHandle =
mScheduler->createConnection("app", mFrameTimeline->getTokenManager(),
/*workDuration=*/configs.late.appWorkDuration,
/*readyDuration=*/configs.late.sfWorkDuration,
impl::EventThread::InterceptVSyncsCallback());
mSfConnectionHandle =
mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(),
/*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),
/*readyDuration=*/configs.late.sfWorkDuration,
[this](nsecs_t timestamp) {
mInterceptor->saveVSyncEvent(timestamp);
});
}
frameworks/native/services/surfaceflinger/Scheduler/Scheduler.cpp
Scheduler::ConnectionHandle Scheduler::createConnection(
const char* connectionName, frametimeline::TokenManager* tokenManager,
std::chrono::nanoseconds workDuration, std::chrono::nanoseconds readyDuration,
impl::EventThread::InterceptVSyncsCallback interceptCallback) {
// 在调用makePrimaryDispSyncSource, 返回一个DispSyncSource对象
auto vsyncSource = makePrimaryDispSyncSource(connectionName, workDuration, readyDuration);
auto throttleVsync = makeThrottleVsyncCallback();
auto getVsyncPeriod = makeGetVsyncPeriodFunction();
// 创建EventThread,EventThread构造函数中,会通过调用DispSyncSource的setCallback函数
// 将EventThread自己传入,DispSyncSource会把EventThread赋值给mCallback
auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource), tokenManager,
std::move(interceptCallback),
std::move(throttleVsync),
std::move(getVsyncPeriod));
return createConnection(std::move(eventThread));
}
std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(
const char* name, std::chrono::nanoseconds workDuration,
std::chrono::nanoseconds readyDuration, bool traceVsync) {
// 这里会new一个DispSyncSource,注意第一个参数就是上面说的VSyncDispatchTimerQueue
return std::make_unique<scheduler::DispSyncSource>(*mVsyncSchedule.dispatch, workDuration,
readyDuration, traceVsync, name);
}
frameworks/native/services/surfaceflinger/Scheduler/DispSyncSource.cpp
3.2
DispSyncSource::DispSyncSource(scheduler::VSyncDispatch& vSyncDispatch,
std::chrono::nanoseconds workDuration,
std::chrono::nanoseconds readyDuration, bool traceVsync,
const char* name)
: mName(name),
mValue(base::StringPrintf("VSYNC-%s", name), 0),
mTraceVsync(traceVsync),
mVsyncOnLabel(base::StringPrintf("VsyncOn-%s", name)),
mWorkDuration(base::StringPrintf("VsyncWorkDuration-%s", name), workDuration),
mReadyDuration(readyDuration) {
// 这里会new一个CallbackRepeater,
// 第一个参数就是上面说的VSyncDispatchTimerQueue
// 第二个参数是DispSyncSource::onVsyncCallback函数
mCallbackRepeater =
std::make_unique<CallbackRepeater>(vSyncDispatch,
std::bind(&DispSyncSource::onVsyncCallback, this,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3),
name, workDuration, readyDuration,
std::chrono::steady_clock::now().time_since_epoch());
}
CallbackRepeater(VSyncDispatch& dispatch, VSyncDispatch::Callback cb, const char* name,
std::chrono::nanoseconds workDuration, std::chrono::nanoseconds readyDuration,
std::chrono::nanoseconds notBefore)
: mName(name),
mCallback(cb),
// 这里会new一个VSyncCallbackRegistration,
// 第一个参数就是上面说VSyncDispatchTimerQueue
// 第二个参数是CallbackRepeater::callback函数,该函数中调用了mCallback,
// mCallback在这里又被赋值给了DispSyncSource::onVsyncCallback
mRegistration(dispatch,
std::bind(&CallbackRepeater::callback, this, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3),
mName),
mStarted(false),
mWorkDuration(workDuration),
mReadyDuration(readyDuration),
mLastCallTime(notBefore) {}
frameworks/native/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp
VSyncCallbackRegistration::VSyncCallbackRegistration(VSyncDispatch& dispatch,
VSyncDispatch::Callback const& callbackFn,
std::string const& callbackName)
: mDispatch(dispatch),
// 调用VSyncDispatchTimerQueue的registerCallback
// 第二个参数是DispSyncSource::onVsyncCallback函数
mToken(dispatch.registerCallback(callbackFn, callbackName)),
mValidToken(true) {}
VSyncDispatchTimerQueue::CallbackToken VSyncDispatchTimerQueue::registerCallback(
Callback const& callbackFn, std::string callbackName) {
std::lock_guard lock(mMutex);
return CallbackToken{
mCallbacks
.emplace(++mCallbackToken,
// 创建VSyncDispatchTimerQueueEntry
// // 第二个参数是DispSyncSource::onVsyncCallback函数
std::make_shared<VSyncDispatchTimerQueueEntry>(callbackName,
callbackFn,
mMinVsyncDistance))
.first->first};
}
VSyncDispatchTimerQueueEntry::VSyncDispatchTimerQueueEntry(std::string const& name,
VSyncDispatch::Callback const& cb,
nsecs_t minVsyncDistance)
: mName(name),
mCallback(cb), // 第二个参数是DispSyncSource::onVsyncCallback函数
mMinVsyncDistance(minVsyncDistance) {}
4
根据第三章整个调用链的跟踪,在第二章sw vsync timer 触发时,就调用DispSyncSource::onVsyncCallback,该函数内部又会调用mCallback的onVSyncEvent,在第三章分析,
DispSyncSource的mCallback就是EventThread,继续分析:
frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp
void EventThread::onVSyncEvent(nsecs_t timestamp, nsecs_t expectedVSyncTimestamp,
nsecs_t deadlineTimestamp) {
...
// 压入mPendingEvents
mPendingEvents.push_back(makeVSync(mVSyncState->displayId, timestamp, ++mVSyncState->count,
expectedVSyncTimestamp, deadlineTimestamp, vsyncId));
// 唤醒子线程
mCondition.notify_all();
}
void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
DisplayEventConsumers consumers;
while (mState != State::Quit) {
std::optional<DisplayEventReceiver::Event> event;
// Determine next event to dispatch.
//第二次执行threadMain时,mPendingEvents不为空了,走进来,给event赋值。
// 第二次执行threadMain,再一次执行while,mPendingEvents为空了,所以event = null
if (!mPendingEvents.empty()) {
event = mPendingEvents.front();
mPendingEvents.pop_front();
switch (event->header.type) {
case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
if (event->hotplug.connected && !mVSyncState) {
mVSyncState.emplace(event->header.displayId);
} else if (!event->hotplug.connected && mVSyncState &&
mVSyncState->displayId == event->header.displayId) {
mVSyncState.reset();
}
break;
case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
if (mInterceptVSyncsCallback) {
mInterceptVSyncsCallback(event->header.timestamp);
}
break;
}
}
bool vsyncRequested = false;
// Find connections that should consume this event.
auto it = mDisplayEventConnections.begin();
while (it != mDisplayEventConnections.end()) {
if (const auto connection = it->promote()) {
// 在上面第一章节的时候,connection->vsyncRequest在一开始就被赋值给了Single,
// 所以第二次执行threadMain时,这里vsyncRequested = true
// 第二次执行threadMain,再一次执行while时,connection->vsyncRequest = SingleSuppressCallback,所以vsyncRequested 还是true
vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
// shouldConsumeEvent中,如果connection->vsyncReques = Single
// 就把connection->vsyncReques改为SingleSuppressCallback;然后返回true
if (event && shouldConsumeEvent(*event, connection)) {
// 找到要通知的app,给consumers赋值
consumers.push_back(connection);
}
++it;
} else {
it = mDisplayEventConnections.erase(it);
}
}
if (!consumers.empty()) {
// 通知app,第二次执行threadMain时,看起来主要就是为了走到这里通知app的,后面要分析一下 TODO
dispatchEvent(*event, consumers);
consumers.clear();
}
State nextState;
if (mVSyncState && vsyncRequested) {
nextState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
} else {
ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
nextState = State::Idle;
}
// 第二次执行threadMain时,mState == nextState,都是VSync
//第二次执行threadMain,再一次执行while时,mState == nextState,都是VSync
if (mState != nextState) {
if (mState == State::VSync) {
mVSyncSource->setVSyncEnabled(false);
} else if (nextState == State::VSync) {
mVSyncSource->setVSyncEnabled(true);
}
mState = nextState;
}
if (event) {
// 第二次执行threadMain时,走这里,继续while循环
continue;
}
// Wait for event or client registration/request.
if (mState == State::Idle) {
mCondition.wait(lock);
} else {
// Generate a fake VSYNC after a long timeout in case the driver stalls. When the
// display is off, keep feeding clients at 60 Hz.
const std::chrono::nanoseconds timeout =
mState == State::SyntheticVSync ? 16ms : 1000ms;
// 第二次执行threadMain,再一次执行while时,wait在这里
if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
if (mState == State::VSync) {
ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
std::string debugInfo = "VsyncSource debug info:\n";
mVSyncSource->dump(debugInfo);
// Log the debug info line-by-line to avoid logcat overflow
auto pos = debugInfo.find('\n');
while (pos != std::string::npos) {
ALOGW("%s", debugInfo.substr(0, pos).c_str());
debugInfo = debugInfo.substr(pos + 1);
pos = debugInfo.find('\n');
}
}
LOG_FATAL_IF(!mVSyncState);
const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
const auto deadlineTimestamp = now + timeout.count();
const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
const int64_t vsyncId = [&] {
if (mTokenManager != nullptr) {
return mTokenManager->generateTokenForPredictions(
{now, deadlineTimestamp, expectedVSyncTime});
}
return FrameTimelineInfo::INVALID_VSYNC_ID;
}();
mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
++mVSyncState->count, expectedVSyncTime,
deadlineTimestamp, vsyncId));
}
}
}
}
5
上面的app请求vsync流程还没有走完.
5.1
其实在第三章节中,3.2小节中,DispSyncSource在构造函数中new了一个CallbackRepeater ,在CallbackRepeater 的callback函数中除了调用DispSyncSource的callback,还调用了mRegistration.schedule,又触发了一个vsync计时,计时到时,回到了上面的第二章节了。最后还会调用到EventThread的threadMain函数里面。
那么这里问题来了,如果mStarted一直为true,vsync就一直循环了,一定有设置fasle的地方,先继续分析。
/frameworks/native/services/surfaceflinger/Scheduler/DispSyncSource.cpp
class CallbackRepeater {
void callback(nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
{
std::lock_guard lock(mMutex);
mLastCallTime = std::chrono::nanoseconds(vsyncTime);
}
// 第四章分析过,这里会调用DispSyncSource的onVsyncCallback
mCallback(vsyncTime, wakeupTime, readyTime);
{
std::lock_guard lock(mMutex);
// 此时mStarted = true,看来这个变量很关键,如果它为true, vsync就会继续执行。
// 后面分析mStarted 的变化
if (!mStarted) {
return;
}
// 继续一个vsync定时
auto const scheduleResult =
mRegistration.schedule({.workDuration = mWorkDuration.count(),
.readyDuration = mReadyDuration.count(),
.earliestVsync = vsyncTime});
LOG_ALWAYS_FATAL_IF(!scheduleResult.has_value(), "Error rescheduling callback");
}
}
5.2
/frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp
void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
DisplayEventConsumers consumers;
while (mState != State::Quit) {
std::optional<DisplayEventReceiver::Event> event;
// Determine next event to dispatch.
// 第二次触发vsync时,从前面1~4章节的分析,此时mPendingEvents不为空,
// 继续下面mark A的分析,再一次执行while,mPendingEvents为空
if (!mPendingEvents.empty()) {
event = mPendingEvents.front();
mPendingEvents.pop_front();
switch (event->header.type) {
case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
if (event->hotplug.connected && !mVSyncState) {
mVSyncState.emplace(event->header.displayId);
} else if (!event->hotplug.connected && mVSyncState &&
mVSyncState->displayId == event->header.displayId) {
mVSyncState.reset();
}
break;
case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
if (mInterceptVSyncsCallback) {
mInterceptVSyncsCallback(event->header.timestamp);
}
break;
}
}
bool vsyncRequested = false;
// Find connections that should consume this event.
auto it = mDisplayEventConnections.begin();
while (it != mDisplayEventConnections.end()) {
if (const auto connection = it->promote()) {
// 第二次触发vsync时,在5.1章节中, connection->vsyncRequest被赋值为SingleSuppressCallback,vsyncRequested = true。
// 再一次执行while时,connection->vsyncRequest为None,vsyncRequested 终于等于false 了
vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
// event 不为空,shouldConsumeEvent中又将connection->vsyncRequest赋值为None;
//
if (event && shouldConsumeEvent(*event, connection)) {
consumers.push_back(connection);
}
++it;
} else {
it = mDisplayEventConnections.erase(it);
}
}
// 回调app,这个后面分析
if (!consumers.empty()) {
dispatchEvent(*event, consumers);
consumers.clear();
}
State nextState;
// 再一次执行while时,vsyncRequested = false, nextState = Idle, mState目前还是VSync
if (mVSyncState && vsyncRequested) {
// nextState 依然为VSync
nextState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
} else {
ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
nextState = State::Idle;
}
if (mState != nextState) {
if (mState == State::VSync) {
// 再一次执行while时,走这里了
mVSyncSource->setVSyncEnabled(false);
} else if (nextState == State::VSync) {
mVSyncSource->setVSyncEnabled(true);
}
mState = nextState;
}
if (event) {
// 走这里继续执行while,make A
continue;
}
// Wait for event or client registration/request.
if (mState == State::Idle) {
mCondition.wait(lock);
} else {
// Generate a fake VSYNC after a long timeout in case the driver stalls. When the
// display is off, keep feeding clients at 60 Hz.
const std::chrono::nanoseconds timeout =
mState == State::SyntheticVSync ? 16ms : 1000ms;
if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
if (mState == State::VSync) {
ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
std::string debugInfo = "VsyncSource debug info:\n";
mVSyncSource->dump(debugInfo);
// Log the debug info line-by-line to avoid logcat overflow
auto pos = debugInfo.find('\n');
while (pos != std::string::npos) {
ALOGW("%s", debugInfo.substr(0, pos).c_str());
debugInfo = debugInfo.substr(pos + 1);
pos = debugInfo.find('\n');
}
}
LOG_FATAL_IF(!mVSyncState);
const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
const auto deadlineTimestamp = now + timeout.count();
const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
const int64_t vsyncId = [&] {
if (mTokenManager != nullptr) {
return mTokenManager->generateTokenForPredictions(
{now, deadlineTimestamp, expectedVSyncTime});
}
return FrameTimelineInfo::INVALID_VSYNC_ID;
}();
mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
++mVSyncState->count, expectedVSyncTime,
deadlineTimestamp, vsyncId));
}
}
}
}
5.3
frameworks/native/services/surfaceflinger/Scheduler/DispSyncSource.cpp
139 void DispSyncSource::setVSyncEnabled(bool enable) {
140 std::lock_guard lock(mVsyncMutex);
141 if (enable) {
142 mCallbackRepeater->start(mWorkDuration, mReadyDuration);
143 // ATRACE_INT(mVsyncOnLabel.c_str(), 1);
144 } else {
145 mCallbackRepeater->stop();
146 // ATRACE_INT(mVsyncOnLabel.c_str(), 0);
147 }
148 mEnabled = enable;
149 }
class CallbackRepeater {
void stop() {
std::lock_guard lock(mMutex);
LOG_ALWAYS_FATAL_IF(!mStarted, "DispSyncInterface misuse: callback already stopped");
// 记住这个mStarted ,在这里被赋值为false。这里就回答了上面5.1章节的问题。
mStarted = false;
// 这里会取消掉vsync的timer
mRegistration.cancel();
}
5.4
app的第一次vsync请求就分析完了,但是一般情况下app不只是请求一次,会请求很多次。当再次请求时:
void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
if (connection->resyncCallback) {
connection->resyncCallback();
}
std::lock_guard<std::mutex> lock(mMutex);
if (connection->vsyncRequest == VSyncRequest::None) {
connection->vsyncRequest = VSyncRequest::Single;
mCondition.notify_all();
// 如果connection->vsyncRequest此时等于SingleSuppressCallback,只是改成了Single,并没有触发threadMain中的条件变量,
// 那则么继续执行呢,细想一下,如果connection->vsyncRequest = SingleSuppressCallback,参考5.1,还有一个vsync定时,
// 当定时触发运行时,connection->vsyncRequest = Single了,在threadMain中就不会走到5.3中了,所以vsync流程还会继续走。
// 所以这里说明一下。
} else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
connection->vsyncRequest = VSyncRequest::Single;
}
}
更多推荐
所有评论(0)