VSYNC 信号完整流程2
完整调用链路图
scss
┌──────────────────────────────────────────────────────────────────────────────┐
│ APP 端 (Java/Native) │
│ │
│ Choreographer.postFrameCallback() │
│ ↓ │
│ scheduleVsyncLocked() │
│ ↓ │
│ DisplayEventReceiver.scheduleVsync() │
│ ↓ (JNI) │
│ NativeDisplayEventReceiver.scheduleVsync() │
│ ↓ │
│ DisplayEventDispatcher.scheduleVsync() │
│ ↓ │
│ DisplayEventReceiver.requestNextVsync() │
│ ↓ (Binder/AIDL) │
└──────────────────────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────────┐
│ SurfaceFlinger 端 │
│ │
│ EventThreadConnection.requestNextVsync() │
│ ↓ │
│ EventThread.requestNextVsync() ← 设置 vsyncRequest=Single │
│ ↓ (唤醒 EventThread 主循环) │
│ EventThread.threadMain() │
│ ↓ (检测到 vsyncRequested=true) │
│ mVsyncRegistration.schedule() │
│ ↓ │
│ VSyncDispatchTimerQueue.schedule() │
│ ↓ │
│ VSyncDispatchTimerQueueEntry.schedule() ← 计算 wakeupTime │
│ ↓ │
│ Timer::alarmAt() ← 设置 timerfd │
│ ↓ (等待定时器到期) │
│ Timer::dispatch() ← epoll_wait │
│ ↓ │
│ VSyncDispatchTimerQueue::timerCallback() │
│ ↓ │
│ VSyncDispatchTimerQueueEntry::callback() │
│ ↓ (调用 std::function) │
│ [lambda] → EventThread::onVsync() ← 创建 VSYNC 事件 │
│ ↓ │
│ EventThread::dispatchEvent() │
│ ↓ (通过 BitTube 发送) │
└──────────────────────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────────┐
│ APP 端回调 │
│ │
│ DisplayEventDispatcher.handleEvent() ← Looper 检测到 FD 可读 │
│ ↓ │
│ processPendingEvents() ← 读取 VSYNC 事件 │
│ ↓ │
│ dispatchVsync() ← JNI 回调 │
│ ↓ │
│ DisplayEventReceiver.dispatchVsync() │
│ ↓ │
│ Choreographer.onVsync() │
│ ↓ │
│ Choreographer.doFrame() │
│ ↓ │
│ FrameCallback.doFrame() ← App 注册的回调 │
└──────────────────────────────────────────────────────────────────────────────┘
阶段一:App 端发起 VSYNC 请求
1.1 Choreographer 请求下一帧
文件 : frameworks/base/core/java/android/view/Choreographer.java:967-975
java
private void scheduleVsyncLocked() {
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "Choreographer#scheduleVsyncLocked");
mDisplayEventReceiver.scheduleVsync();
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
调用栈:
scss
Choreographer.postFrameCallback()
→ postCallbackDelayed(CALLBACK_ANIMATION, action, FRAME_CALLBACK_TOKEN, 0)
→ scheduleFrameLocked(now)
→ doScheduleVsync()
→ scheduleVsyncLocked()
1.2 DisplayEventReceiver (Java) 调用 Native
文件 : frameworks/base/core/java/android/view/DisplayEventReceiver.java:328-336
java
public void scheduleVsync() {
if (mReceiverPtr == 0) {
Log.w(TAG, "Attempted to schedule a vertical sync pulse...");
} else {
nativeScheduleVsync(mReceiverPtr);
}
}
1.3 JNI 层调用 Native DisplayEventReceiver
文件 : frameworks/base/core/jni/android_view_DisplayEventReceiver.cpp:285-293
cpp
static void nativeScheduleVsync(JNIEnv* env, jclass clazz, jlong receiverPtr) {
sp<NativeDisplayEventReceiver> receiver =
reinterpret_cast<NativeDisplayEventReceiver*>(receiverPtr);
status_t status = receiver->scheduleVsync();
if (status) {
String8 message;
message.appendFormat("Failed to schedule next vertical sync pulse. status=%d", status);
jniThrowRuntimeException(env, message.string());
}
}
1.4 DisplayEventDispatcher 请求 VSYNC
文件 : frameworks/native/libs/gui/DisplayEventDispatcher.cpp:76-93
cpp
status_t DisplayEventDispatcher::scheduleVsync() {
if (!mWaitingForVsync) {
ALOGV("dispatcher %p ~ Scheduling vsync.", this);
// 清空所有待处理事件
nsecs_t vsyncTimestamp;
PhysicalDisplayId vsyncDisplayId;
uint32_t vsyncCount;
VsyncEventData vsyncEventData;
if (processPendingEvents(&vsyncTimestamp, &vsyncDisplayId, &vsyncCount, &vsyncEventData)) {
ALOGE("dispatcher %p ~ last event processed while scheduling was for %" PRId64 "", this,
ns2ms(static_cast<nsecs_t>(vsyncTimestamp)));
}
status_t status = mReceiver.requestNextVsync(); // ← 关键调用
if (status) {
ALOGW("Failed to request next vsync, status=%d", status);
return status;
}
mWaitingForVsync = true;
mLastScheduleVsyncTime = systemTime(SYSTEM_TIME_MONOTONIC);
}
return OK;
}
1.5 通过 Binder 调用 SurfaceFlinger
文件 : frameworks/native/libs/gui/DisplayEventReceiver.cpp:89-97
cpp
status_t DisplayEventReceiver::requestNextVsync() {
if (mEventConnection != nullptr) {
mEventConnection->requestNextVsync(); // ← AIDL 调用
return NO_ERROR;
}
return mInitError.has_value() ? mInitError.value() : NO_INIT;
}
AIDL 接口 : frameworks/native/libs/gui/aidl/android/gui/IDisplayEventConnection.aidl:39-41
aidl
/**
* requestNextVsync() schedules the next vsync event.
*/
oneway void requestNextVsync(); // Asynchronous
阶段二:SurfaceFlinger 接收并处理请求
2.1 EventThreadConnection 接收请求
文件 : frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp:199-204
cpp
binder::Status EventThreadConnection::requestNextVsync() {
ATRACE_CALL();
mEventThread->requestNextVsync(sp<EventThreadConnection>::fromExisting(this));
return binder::Status::ok();
}
2.2 EventThread 处理 VSYNC 请求
文件 : frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp:346-360
cpp
void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
if (connection->resyncCallback) {
connection->resyncCallback(); // ← 触发硬件 resync
}
std::lock_guard<std::mutex> lock(mMutex);
if (connection->vsyncRequest == VSyncRequest::None) {
connection->vsyncRequest = VSyncRequest::Single; // ← 设置单次 VSYNC
mCondition.notify_all(); // ← 唤醒 EventThread 主循环
} else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
connection->vsyncRequest = VSyncRequest::Single;
}
}
2.3 EventThread 主循环等待 VSYNC
文件 : frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp:439-507
cpp
void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
DisplayEventConsumers consumers;
while (mState != State::Quit) {
// ... 处理待分发事件
bool vsyncRequested = false;
// 查找应该消费此事件的连接
auto it = mDisplayEventConnections.begin();
while (it != mDisplayEventConnections.end()) {
if (const auto connection = it->promote()) {
vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
++it;
}
}
// 根据状态调度 VSYNC 回调
if (mVSyncState && vsyncRequested) {
mState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
} else {
mState = State::Idle;
}
if (mState == State::VSync) {
// ← 关键:调度 VSyncDispatch 回调
const auto scheduleResult =
mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
.readyDuration = mReadyDuration.count(),
.earliestVsync = mLastVsyncCallbackTime.ns()});
LOG_ALWAYS_FATAL_IF(!scheduleResult, "Error scheduling callback");
} else {
mVsyncRegistration.cancel();
}
// 等待事件或客户端注册/请求
if (mState == State::Idle) {
mCondition.wait(lock); // ← 等待 requestNextVsync 或硬件 VSYNC
} else {
const std::chrono::nanoseconds timeout =
mState == State::SyntheticVSync ? 16ms : 1000ms;
if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
// 超时生成伪 VSYNC
}
}
}
}
阶段三:VSyncDispatchTimerQueue 定时器机制
3.1 EventThread 注册回调到 VSyncDispatch
文件 : frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp:253-254
cpp
EventThread::EventThread(...)
: ...
mVsyncRegistration(mVsyncSchedule->getDispatch(), createDispatchCallback(), name),
...
{}
createDispatchCallback 定义 : frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp:751-755
cpp
scheduler::VSyncDispatch::Callback EventThread::createDispatchCallback() {
return [this](nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
onVsync(vsyncTime, wakeupTime, readyTime); // ← 捕获 this 调用 onVsync
};
}
3.2 VSyncDispatchTimerQueue 注册回调
文件 : frameworks/native/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp:328-337
cpp
VSyncDispatchTimerQueue::CallbackToken VSyncDispatchTimerQueue::registerCallback(
Callback callback, std::string callbackName) {
std::lock_guard lock(mMutex);
return CallbackToken{
mCallbacks
.emplace(++mCallbackToken,
std::make_shared<VSyncDispatchTimerQueueEntry>(
std::move(callbackName),
std::move(callback), // ← 保存 lambda
mMinVsyncDistance))
.first->first};
}
3.3 EventThread 调度 VSYNC 回调
文件 : frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp:484-491
cpp
if (mState == State::VSync) {
const auto scheduleResult =
mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
.readyDuration = mReadyDuration.count(),
.earliestVsync = mLastVsyncCallbackTime.ns()});
LOG_ALWAYS_FATAL_IF(!scheduleResult, "Error scheduling callback");
}
3.4 VSyncDispatchTimerQueueEntry 计算唤醒时间
文件 : frameworks/native/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp:93-114
cpp
ScheduleResult VSyncDispatchTimerQueueEntry::schedule(VSyncDispatch::ScheduleTiming timing,
VSyncTracker& tracker, nsecs_t now) {
// 预测下一个 VSYNC 时间
auto nextVsyncTime = tracker.nextAnticipatedVSyncTimeFrom(
std::max(timing.earliestVsync, now + timing.workDuration + timing.readyDuration));
// 计算唤醒时间 = VSYNC 时间 - 工作时间 - 准备时间
auto nextWakeupTime = nextVsyncTime - timing.workDuration - timing.readyDuration;
nextVsyncTime = adjustVsyncIfNeeded(tracker, nextVsyncTime);
nextWakeupTime = nextVsyncTime - timing.workDuration - timing.readyDuration;
auto const nextReadyTime = nextVsyncTime - timing.readyDuration;
mScheduleTiming = timing;
mArmedInfo = {nextWakeupTime, nextVsyncTime, nextReadyTime}; // ← 保存时间信息
return getExpectedCallbackTime(nextVsyncTime, timing);
}
3.5 设置 Linux timerfd 定时器
文件 : frameworks/native/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp:243-247
cpp
void VSyncDispatchTimerQueue::setTimer(nsecs_t targetTime, nsecs_t /*now*/) {
mIntendedWakeupTime = targetTime;
mTimeKeeper->alarmAt(std::bind(&VSyncDispatchTimerQueue::timerCallback, this),
mIntendedWakeupTime);
mLastTimerSchedule = mTimeKeeper->now();
}
Timer 实现 (使用 timerfd) : frameworks/native/services/surfaceflinger/Scheduler/src/Timer.cpp:109-131
cpp
void Timer::alarmAt(std::function<void()> callback, nsecs_t time) {
std::lock_guard lock(mMutex);
using namespace std::literals;
static constexpr int ns_per_s =
std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
mCallback = std::move(callback);
mExpectingCallback = true;
struct itimerspec old_timer;
struct itimerspec new_timer {
.it_interval = {.tv_sec = 0, .tv_nsec = 0},
.it_value = {.tv_sec = static_cast<long>(time / ns_per_s),
.tv_nsec = static_cast<long>(time % ns_per_s)},
};
// ← 设置绝对时间定时器
if (timerfd_settime(mTimerFd, TFD_TIMER_ABSTIME, &new_timer, &old_timer)) {
ALOGW("Failed to set timerfd %s (%i)", strerror(errno), errno);
}
}
3.6 Timer 线程等待并触发回调
文件 : frameworks/native/services/surfaceflinger/Scheduler/src/Timer.cpp:168-218
cpp
bool Timer::dispatch() {
// 设置线程优先级为实时 (SCHED_FIFO)
struct sched_param param = {0};
param.sched_priority = 2;
pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶m);
pthread_setname_np(pthread_self(), "TimerDispatch");
// 将 timerfd 添加到 epoll
epoll_event timerEvent;
timerEvent.events = EPOLLIN;
timerEvent.data.u32 = DispatchType::TIMER;
epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mTimerFd, &timerEvent);
while (true) {
epoll_event events[DispatchType::MAX_DISPATCH_TYPE];
int nfds = epoll_wait(mEpollFd, events, DispatchType::MAX_DISPATCH_TYPE, -1);
for (auto i = 0; i < nfds; i++) {
if (events[i].data.u32 == DispatchType::TIMER) {
// 读取 timerfd,清除事件
uint64_t mIgnored = 0;
read(mTimerFd, &mIgnored, sizeof(mIgnored));
// 获取并调用回调
std::function<void()> cb;
{
std::lock_guard lock(mMutex);
cb = mCallback;
mExpectingCallback = false;
}
if (cb) {
cb(); // ← 调用 VSyncDispatchTimerQueue::timerCallback
}
}
// 处理 TERMINATE 事件...
}
}
}
3.7 VSyncDispatchTimerQueue::timerCallback 触发所有到期回调
文件 : frameworks/native/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp:289-326
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;
// 遍历所有注册的回调
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();
// 检查是否到期(考虑 timer slack 和 lag)
auto const lagAllowance = std::max(now - mIntendedWakeupTime, static_cast<nsecs_t>(0));
if (*wakeupTime < mIntendedWakeupTime + mTimerSlack + lagAllowance) {
callback->executing(); // 标记为执行中,解除武装
invocations.emplace_back(Invocation{callback,
*callback->lastExecutedVsyncTarget(),
*wakeupTime,
*readyTime});
}
}
mIntendedWakeupTime = kInvalidTime;
rearmTimer(mTimeKeeper->now()); // 重新设置定时器
}
// 在锁外调用所有到期的回调
for (auto const& invocation : invocations) {
invocation.callback->callback(invocation.vsyncTimestamp,
invocation.wakeupTimestamp,
invocation.deadlineTimestamp);
}
}
3.8 VSyncDispatchTimerQueueEntry::callback 调用 std::function
文件 : frameworks/native/services/surfaceflinger/Scheduler/VSyncDispatchTimerQueue.cpp:175-187
cpp
void VSyncDispatchTimerQueueEntry::callback(nsecs_t vsyncTimestamp, nsecs_t wakeupTimestamp,
nsecs_t deadlineTimestamp) {
{
std::lock_guard<std::mutex> lk(mRunningMutex);
mRunning = true;
}
mCallback(vsyncTimestamp, wakeupTimestamp, deadlineTimestamp); // ← 调用 EventThread 的 lambda
std::lock_guard<std::mutex> lk(mRunningMutex);
mRunning = false;
mCv.notify_all();
}
此时 mCallback 就是之前注册的 lambda:
cpp
[this](nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
onVsync(vsyncTime, wakeupTime, readyTime);
}
3.9 EventThread::onVsync 创建 VSYNC 事件
文件 : frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp:400-408
cpp
void EventThread::onVsync(nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
std::lock_guard<std::mutex> lock(mMutex);
mLastVsyncCallbackTime = TimePoint::fromNs(vsyncTime);
LOG_FATAL_IF(!mVSyncState);
mVsyncTracer = (mVsyncTracer + 1) % 2;
// ← 创建 VSYNC 事件并添加到待发送队列
mPendingEvents.push_back(makeVSync(mVSyncState->displayId, wakeupTime, ++mVSyncState->count,
vsyncTime, readyTime));
mCondition.notify_all(); // ← 唤醒 EventThread 主循环分发事件
}
阶段四:VSYNC 事件分发到 App
4.1 EventThread 分发事件
文件 : frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp:467-470
cpp
if (!consumers.empty()) {
dispatchEvent(*event, consumers);
consumers.clear();
}
dispatchEvent 实现 : frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp:569-580
cpp
void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
DisplayEventConsumers& consumers) {
for (const auto& consumer : consumers) {
if (status_t status = consumer->postEvent(event); status != NO_ERROR) {
ALOGE("Failed to post event to %s: %s", toString(*consumer).c_str(),
statusToString(status));
}
}
}
4.2 EventThreadConnection 通过 BitTube 发送事件
文件 : frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp:229-243
cpp
status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
constexpr auto toStatus = [](ssize_t size) {
return size < 0 ? status_t(size) : status_t(NO_ERROR);
};
if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
// 处理帧率覆盖事件...
}
// ← 通过 BitTube 发送 VSYNC 事件
auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
return toStatus(size);
}
4.3 App 端 Looper 检测并读取事件
文件 : frameworks/native/libs/gui/DisplayEventDispatcher.cpp:115-143
cpp
int DisplayEventDispatcher::handleEvent(int, int events, void*) {
if (events & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP)) {
ALOGE("Display event receiver pipe was closed or an error occurred.");
return 0;
}
if (!(events & Looper::EVENT_INPUT)) {
ALOGW("Received spurious callback for unhandled poll event.");
return 1;
}
// 读取所有待处理事件,保留最后一个 vsync
nsecs_t vsyncTimestamp;
PhysicalDisplayId vsyncDisplayId;
uint32_t vsyncCount;
VsyncEventData vsyncEventData;
if (processPendingEvents(&vsyncTimestamp, &vsyncDisplayId, &vsyncCount, &vsyncEventData)) {
ALOGV("dispatcher %p ~ Vsync pulse: timestamp=%" PRId64 ", displayId=%s, count=%d",
this, ns2ms(vsyncTimestamp), to_string(vsyncDisplayId).c_str(), vsyncCount);
mWaitingForVsync = false;
mLastVsyncCount = vsyncCount;
dispatchVsync(vsyncTimestamp, vsyncDisplayId, vsyncCount, vsyncEventData); // ← 回调
}
return 1;
}
4.4 JNI 回调到 Java 层
文件 : frameworks/base/core/jni/android_view_DisplayEventReceiver.cpp:158-203
cpp
void NativeDisplayEventReceiver::dispatchVsync(nsecs_t timestamp, PhysicalDisplayId displayId,
uint32_t count, VsyncEventData vsyncEventData) {
JNIEnv* env = AndroidRuntime::getJNIEnv();
ScopedLocalRef<jobject> receiverObj(env, GetReferent(env, mReceiverWeakGlobal));
ScopedLocalRef<jobject> vsyncEventDataObj(env, GetReferent(env, mVsyncEventDataWeakGlobal));
if (receiverObj.get() && vsyncEventDataObj.get()) {
// 更新 VsyncEventData 字段
env->SetIntField(vsyncEventDataObj.get(),
gDisplayEventReceiverClassInfo.vsyncEventDataClassInfo
.preferredFrameTimelineIndex,
vsyncEventData.preferredFrameTimelineIndex);
// ... 更新其他字段
// ← 调用 Java 层的 dispatchVsync
env->CallVoidMethod(receiverObj.get(), gDisplayEventReceiverClassInfo.dispatchVsync,
timestamp, displayId.value, count);
}
mMessageQueue->raiseAndClearException(env, "dispatchVsync");
}
4.5 Java 层处理 VSYNC
文件 : frameworks/base/core/java/android/view/DisplayEventReceiver.java:343-348
java
@SuppressWarnings("unused")
private void dispatchVsync(long timestampNanos, long physicalDisplayId, int frame) {
onVsync(timestampNanos, physicalDisplayId, frame, mVsyncEventData);
}
4.6 Choreographer 执行 Frame 回调
文件 : frameworks/base/core/java/android/view/Choreographer.java:1301-1321
java
@Override
public void onVsync(long timestampNanos, long physicalDisplayId, int frame,
VsyncEventData vsyncEventData) {
long now = System.nanoTime();
if (timestampNanos > now) {
Log.w(TAG, "Frame time is " + ((timestampNanos - now) * 0.000001f)
+ " ms in the future!");
timestampNanos = now;
}
if (mHavePendingVsync) {
Log.w(TAG, "Already have a pending vsync event.");
} else {
mHavePendingVsync = true;
}
mTimestampNanos = timestampNanos;
mFrame = frame;
mLastVsyncEventData.copyFrom(vsyncEventData);
// ← 发送消息到 Handler,在 vsync 时间执行
Message msg = Message.obtain(mHandler, this);
msg.setAsynchronous(true);
mHandler.sendMessageAtTime(msg, timestampNanos / TimeUtils.NANOS_PER_MS);
}
@Override
public void run() {
mHavePendingVsync = false;
doFrame(mTimestampNanos, mFrame, mLastVsyncEventData);
}
4.7 执行 App 注册的回调
文件 : frameworks/base/core/java/android/view/Choreographer.java:844-878
java
void doFrame(long frameTimeNanos, int frame, DisplayEventReceiver.VsyncEventData vsyncEventData) {
// ... 更新 frame 数据
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "mChoreographer.doFrame");
// 1. 处理输入回调
doCallbacks(CALLBACK_INPUT, frameIntervalNanos);
// 2. 处理动画回调
doCallbacks(CALLBACK_ANIMATION, frameIntervalNanos);
// 3. 处理 insets 动画回调
doCallbacks(CALLBACK_INSETS_ANIMATION, frameIntervalNanos);
// 4. 处理遍历回调 (layout/draw)
doCallbacks(CALLBACK_TRAVERSAL, frameIntervalNanos);
// 5. 处理提交回调
doCallbacks(CALLBACK_COMMIT, frameIntervalNanos);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
// 调度下一个 VSYNC
scheduleFrameLocked(now);
}
关键时序关系
scss
时间轴 (ns):
─────────────────────────────────────────────────────────────────────────►
T0: App 调用 postFrameCallback()
│
▼
T1: scheduleVsyncLocked() → nativeScheduleVsync()
│
▼
T2: DisplayEventDispatcher::scheduleVsync()
│
▼
T3: EventThreadConnection::requestNextVsync()
│
▼
T4: EventThread::requestNextVsync() 设置 vsyncRequest=Single
│
▼
T5: EventThread::threadMain() 检测到 vsyncRequested
│
▼
T6: mVsyncRegistration.schedule() 调度回调
│
▼
T7: VSyncDispatchTimerQueueEntry::schedule()
│ 计算 wakeupTime = vsyncTime - workDuration - readyDuration
│
▼
T8: Timer::alarmAt() 设置 timerfd
│
▼
T9: Timer::dispatch() epoll_wait 等待
│
▼
T10: timerfd 到期,epoll_wait 返回
│
▼
T11: Timer::dispatch() 调用回调
│ → VSyncDispatchTimerQueue::timerCallback()
│
▼
T12: VSyncDispatchTimerQueueEntry::callback()
│ → EventThread::onVsync()
│
▼
T13: EventThread::onVsync() 创建 VSYNC 事件
│ mPendingEvents.push_back(makeVSync(...))
│ mCondition.notify_all()
│
▼
T14: EventThread::dispatchEvent() 通过 BitTube 发送
│
▼
T15: App 端 Looper 检测到 FD 可读
│
▼
T16: DisplayEventDispatcher::handleEvent() 读取事件
│
▼
T17: JNI dispatchVsync() 回调到 Java
│
▼
T18: Choreographer.onVsync() 发送 MSG_DO_FRAME 消息
│
▼
T19: FrameHandler 在 vsync 时间执行 doFrame()
│
▼
T20: 执行 App 注册的 FrameCallback.doFrame()
关键时间计算
cpp
// VSyncDispatchTimerQueue.cpp:93-114
// 预测的下一个 VSYNC 时间
nextVsyncTime = tracker.nextAnticipatedVSyncTimeFrom(
std::max(timing.earliestVsync,
now + timing.workDuration + timing.readyDuration));
// 唤醒时间 = VSYNC 时间 - SurfaceFlinger 工作时间 - App 渲染时间
nextWakeupTime = nextVsyncTime - timing.workDuration - timing.readyDuration;
// 截止时间 = VSYNC 时间 - App 渲染时间
nextReadyTime = nextVsyncTime - timing.readyDuration;
典型值:
workDuration: 8ms (SurfaceFlinger 合成时间)readyDuration: 8ms (App 渲染时间)vsyncTime: 下一个 VSYNC 时间点 (如 16.67ms 间隔)
核心数据结构
VSyncRequest 枚举
cpp
// EventThread.cpp:53-64
enum class VSyncRequest {
None = 0, // 无请求
Single = 1, // 单次 VSYNC (requestNextVsync)
SingleSuppressCallback = 2,
// Periodic = N (N > 1) // 周期性 VSYNC (setVsyncRate)
};
VSyncDispatch::ScheduleTiming
cpp
// VSyncDispatch.h:73-83
struct ScheduleTiming {
nsecs_t workDuration = 0; // SurfaceFlinger 工作时间
nsecs_t readyDuration = 0; // App 渲染时间
nsecs_t earliestVsync = 0; // 最早目标 VSYNC 时间
};
DisplayEventReceiver::Event
cpp
// 通过 BitTube 传输的事件结构
struct Event {
struct Header {
int32_t type; // DISPLAY_EVENT_VSYNC
PhysicalDisplayId displayId;
nsecs_t timestamp;
} header;
union {
struct {
uint32_t count;
VsyncData vsyncData;
} vsync;
};
};