基于Android Q分析SurfaceFlinger启动过程

Vsync简介

屏幕的刷新过程是每一行从左到右(行刷新,水平刷新,Horizontal Scanning),从上到下(屏幕刷新,垂直刷新,Vertical Scanning)。当整个屏幕刷新完毕,即一个垂直刷新周期完成,会有短暂的空白期,此时发出 VSync 信号。所以,VSync 中的 V 指的是垂直刷新中的垂直-Vertical。

Android系统以60帧刷新时每隔16ms发出VSYNC信号,触发对UI进行渲染,VSync是Vertical Synchronization(垂直同步)的缩写,是一种在PC上很早就广泛使用的技术,可以简单的把它认为是一种定时中断。而在Android 4.1(JB)中已经开始引入VSync机制,用来同步渲染,让AppUI和SurfaceFlinger可以按硬件产生的VSync节奏进行工作。

黄油计划:三个方法改进显示系统

  1. Vsync同步
  2. 多级缓冲
  3. Vsync虚拟化(Vsync App + Vsync SurfaceFlinger):
    虽然vsync使得CPU/GPU/Display同步了,但App UI和SurfaceFlinger的工作显然是一个流水线的模型。即对于一帧内容,先等App UI画完了,SurfaceFlinger再出场对其进行合并渲染后放入framebuffer,最后整到屏幕上。而现有的VSync模型是让大家一起开始干活,这样对于同一帧内容,第一个VSync信号时App UI的数据开始准备,第二个VSync信号时SurfaceFlinger工作,第三个VSync信号时用户看到Display内容,这样就两个VSync period(每个16ms)过去了,影响用户体验。
      解决思路:SurfaceFlinger在App UI准备好数据后及时开工做合成。

Android 4.4(KitKat)引入了VSync的虚拟化,即把硬件的VSync信号先同步到一个本地VSync模型中,再从中一分为二,引出两条VSync时间与之有固定偏移的线程。
这样,大家工作既保持一定的节拍,又可以相互错开,一前一后保持着流水节奏。

vsync机制

  • DispSyncThread发信号给EventThread,EventThread发信号给SF线程。故,在这个框架中有两个主要的死循环分别为,DispSyncThreadthreadLoop以及EventThreadthreadMain()中的waitForEventLocked

  • EventThread需要向DispSyncThread注册eventListener; SF/App线程需要向DispSyncThread注册connection

  • 在EventThread循环中调用了EventThread::enableVSyncLocked —> mVSyncSource->setVSyncEnabled mVSyncSource是eventThread构造函数中传递进来的,它是SF中DispSyncSource的父类 ----> mDispSync->addEventListener在SF中的DSS调用,mDispSync是其属性为DispSync类型,是mEventThreadSource构造时传入的mPrimaryDispSync,为DispSync类型 —> mThread->addEventListener 又回到了DispSync类中,往mEventListener中push,等待DispSyncThread传来信号。

  • 当SF/APP有需要时会向EventThread的mDisplayEventConnections新增一个connection.当eventThread收到信号后,会遍历每个connection调用postEvent

  • 信号来临时。eventThead的OnVSyncEvent被调用,执行mCondition.notify_All. 在threadMain中循环的eventThread被唤醒,waitForLocked执行结束,继续执行theadMain()对每个connection执行conn->postEvent, 随后调用DisplayEventReceiver.sendEvents, BitTube::sendObjects.MessageQueue在监听BitTUbe,收到信号后就开始handler执行

关键类:

DispSync: 表示了一个基于硬件VSync信号的同步模型,它会根据从HWComposer来的硬件VSync信号的采样来进行同步。

EventThread: 分别用了两个不同的虚拟VSync信号源(用DispSyncSource表示,其中包含了与真实VSync信号的偏移值),这两个VSync信号源就是被虚拟出来分别用于控制App UI和SurfaceFlinger渲染。在EventThread的线程循环中,如果有需要就会向DispSync注册相应的listener(mEventListeners).

DispSyncThread: 它在threadLoop()主循环中会先通过已经向DispSync注册的listener计算下一个要产生的虚拟VSync信号还要多久,当收到vsync信号后被唤醒,会调用相应listener的callback函数,执行EventThread::onVsynevent。这样,对于那些注册了listener的监听者来说,就好像被真实的VSync信号控制着一样。

SurfaceFlinger启动时序图, Base Android Q
基于Android Q分析SurfaceFlinger启动过程_第1张图片
类图
基于Android Q分析SurfaceFlinger启动过程_第2张图片

源码分析

路径: frameworks/native/services/surfaceflinger

一.启动SurfaceFlinger

1 启动SurfaceFlinger主线程: /main_surfaceflinger.cpp

int main(int, char**) {
    signal(SIGPIPE, SIG_IGN);
    //设定surfaceflinger进程的binder线程池个数上限为4,并启动binder线程池;
    ProcessState::self()->setThreadPoolMaxThreadCount(4);
    sp ps(ProcessState::self());
    ps->startThreadPool();
    //实例化1.1
    sp flinger = DisplayUtils::getInstance()->getSFInstance();
    //设置surfaceflinger进程为高优先级以及前台调度策略
    setpriority(PRIO_PROCESS, 0, PRIORITY_URGENT_DISPLAY);
    set_sched_policy(0, SP_FOREGROUND);

    //初始化SurfaceFlinge 1.2
    flinger->init();

    // publish surface flinger 将”SurfaceFlinger”服务注册到Service Manager
    sp sm(defaultServiceManager());
    sm->addService(String16(SurfaceFlinger::getServiceName()), flinger, false,IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);

    // publish GpuService
    sp gpuservice = new GpuService();
    sm->addService(String16(GpuService::SERVICE_NAME), gpuservice, false);
    startDisplayService(); // dependency on SF getting registered above
    //在当前主线程执行SurfaceFlinger的run方法。
    flinger->run(); 1.7

    return 0;
}

1.1 实例化SurfaceFlinger

SurfaceFlinger继承于BnSurfaceComposer,IBinder::DeathRecipient,HWComposer::EventHandler

flinger的数据类型为sp强指针类型,当首次被强指针引用时则执行OnFirstRef(),操作是初始化消息队列,其中创建了loop和handler

void SurfaceFlinger::onFirstRef()
{
    mEventQueue->init(this);
}

/MessageQueue.cpp

void MessageQueue::init(const sp& flinger) {
    mFlinger = flinger;
    mLooper = new Looper(true);
    mHandler = new Handler(*this);
}

这个Handler是MessageQueue的内部类Handler继承自MessageHandler,此处传递的*this便是MessageQueue本身。

/MessageQueue.cpp
MessageQueue::init

void MessageQueue::init(const sp& flinger) {
    mFlinger = flinger;
    mLooper = new Looper(true);
    mHandler = new Handler(*this);
}
class MessageQueue final : public android::MessageQueue {
    class Handler : public MessageHandler {
        enum { eventMaskInvalidate = 0x1, eventMaskRefresh = 0x2, eventMaskTransaction = 0x4 };
        MessageQueue& mQueue;
        int32_t mEventMask;

    public:
        explicit Handler(MessageQueue& queue) : mQueue(queue), mEventMask(0) {}
        virtual void handleMessage(const Message& message);
        void dispatchRefresh();
        void dispatchInvalidate();
        ...
    };
};

1.2 flinger->init()

/ SurfaceFlinger.cpp

该方法主要功能是:

  • 初始化 EGL
  • 创建 HWComposer
  • 初始化非虚拟显示屏
  • 启动 EventThread 线程
  • 启动开机动画
void SurfaceFlinger::init() {
    Mutex::Autolock _l(mStateLock);

    // start the EventThread (创建了两个EventThread,他们的名字和offset不同)
    mEventThreadSource =std::make_unique(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,true, "app");
    mEventThread = std::make_unique//1.5节
    (mEventThreadSource.get(),[this]() { resyncWithRateLimit(); },impl::EventThread::InterceptVSyncsCallback(), "appEventThread");
    mSfEventThreadSource =std::make_unique(&mPrimaryDispSync,SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");

    mSFEventThread = std::make_unique(mSfEventThreadSource.get(),[this]() { resyncWithRateLimit(); },[this](nsecs_t timestamp) { mInterceptor->saveVSyncEvent(timestamp);},"sfEventThread");
    //创建sf与EventThread之间的connection  1.5节
    mEventQueue->setEventThread(mSFEventThread.get());
    mVsyncModulator.setEventThread(mSFEventThread.get());

    //获取RenderEngine引擎
    getBE().mRenderEngine =
            RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888, hasWideColorDisplay ? RE::RenderEngine::WIDE_COLOR_SUPPORT: 0);
    //初始化硬件composer对象
    getBE().mHwc.reset(
            new HWComposer(std::make_unique(getBE().mHwcServiceName)));
    getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);

    // Process any initial hotplug and resulting display changes.
    processDisplayHotplugEventsLocked();

    getDefaultDisplayDeviceLocked()->makeCurrent();

    //创建eventControlThread 1.6
    mEventControlThread = std::make_unique(
            [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });

    //初始化绘图状态
    mDrawingState = mCurrentState;

    //初始化显示设备
    initializeDisplays();

    getBE().mRenderEngine->primeCache();

    // Inform native graphics APIs whether the present timestamp is supported:
    ...
    ALOGV("Done initializing");
}

1.3 创建HWComposer

/DisplayHardware/HWComposer.cpp

HWComposer代表着硬件显示设备,注册了VSYNC信号的回调。VSYNC信号本身是由显示驱动产生的, 在不支持硬件的VSYNC,则会创建“VSyncThread”线程来模拟定时VSYNC信号。

1.4 DispSyncSource

class DispSyncSource final : public VSyncSource, private DispSync::Callback {
public:
    DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
        const char* name) :
            mName(name),
            mValue(0),
            mTraceVsync(traceVsync),
            mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
            mVsyncEventLabel(String8::format("VSYNC-%s", name)),
            mDispSync(dispSync),
            mCallbackMutex(),
            mVsyncMutex(),
            mPhaseOffset(phaseOffset),
            mEnabled(false) {}

父类是VSyncSource. 创建eventThread前,需要创建eventThreadSource,类型为VsyncSource.

1.5 EventThread线程

/EventThread.cpp

EventThread::EventThread(VSyncSource* src, ResyncWithRateLimitCallback resyncWithRateLimitCallback,
                         InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName)
      : mVSyncSource(src),//VSyncSource,即前面创建的eventThreadSource
        mResyncWithRateLimitCallback(resyncWithRateLimitCallback),
        mInterceptVSyncsCallback(interceptVSyncsCallback) {
    for (auto& event : mVSyncEvent) {
        event.header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
        event.header.id = 0;
        event.header.timestamp = 0;
        event.vsync.count = 0;
    }
    //将threadMain参数初始化mThread.
    //在析构函数中调用了mThread.join();执行threadMain()
    //C++ Thread类传入某类的函数作为参数时,要在随后传入该类的对象
    mThread = std::thread(&EventThread::threadMain, this);

    pthread_setname_np(mThread.native_handle(), threadName);

    pid_t tid = pthread_gettid_np(mThread.native_handle());

    // Use SCHED_FIFO to minimize jitter
    constexpr int EVENT_THREAD_PRIORITY = 2;
    struct sched_param param = {0};
    param.sched_priority = EVENT_THREAD_PRIORITY;
    set_sched_policy(tid, SP_FOREGROUND);

EventThread继承于Thread和VSyncSource::Callback两个类。

EventThread::threadMain()

void EventThread::threadMain() NO_THREAD_SAFETY_ANALYSIS {
    std::unique_lock lock(mMutex);
    while (mKeepRunning) {
        DisplayEventReceiver::Event event;
        Vector > signalConnections;
        // 等待事件
        signalConnections = waitForEventLocked(&lock, &event);

        // dispatch events to listeners...
        //分发事件给所有的监听者
        const size_t count = signalConnections.size();
        for (size_t i = 0; i < count; i++) {
            const sp& conn(signalConnections[i]);
            // now see if we still need to report this event
            //传递事件
            status_t err = conn->postEvent(event);
            if (err == -EAGAIN || err == -EWOULDBLOCK) {
                //可能此时connection已满,则直接抛弃事件
                ALOGW("EventThread: dropping event (%08x) for connection %p", event.header.type,
                      conn.get());
            } else if (err < 0) {
                //发生致命错误,则清理该连接
                removeDisplayEventConnectionLocked(signalConnections[i]);
            }
        }
    }
}

EventThread::waitForEventLocked

// This will return when
//(1) a vsync event has been received, and (2) there was at least one connection interested in receiving it when we started waiting.
Vector > EventThread::waitForEventLocked(
        std::unique_lock* lock, DisplayEventReceiver::Event* event) {
    Vector > signalConnections;

    while (signalConnections.isEmpty() && mKeepRunning) {
        bool eventPending = false;
        bool waitForVSync = false;

        size_t vsyncCount = 0;
        nsecs_t timestamp = 0;
        for (int32_t i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; i++) {
            timestamp = mVSyncEvent[i].header.timestamp;
            if (timestamp) {
                // we have a vsync event to dispatch
                if (mInterceptVSyncsCallback) {
                    mInterceptVSyncsCallback(timestamp);
                }
                *event = mVSyncEvent[i];
                mVSyncEvent[i].header.timestamp = 0;
                vsyncCount = mVSyncEvent[i].vsync.count;
                break;
            }
        }

        // find out connections waiting for events
        size_t count = mDisplayEventConnections.size();
        if (!timestamp && count) {
            //没有vsync事件,则查看其它事件
            eventPending = !mPendingEvents.isEmpty();
            if (eventPending) {
                // we have some other event to dispatch
                *event = mPendingEvents[0];
                mPendingEvents.removeAt(0);
            }
        }

        for (size_t i = 0; i < count;) {
            sp connection(mDisplayEventConnections[i].promote());
            if (connection != nullptr) {
                bool added = false;
                if (connection->count >= 0) {
                    // we need vsync events because at least
                    // one connection is waiting for it
                    waitForVSync = true;
                    if (timestamp) {
                        // we consume the event only if it's time
                        // (ie: we received a vsync event)
                        if (connection->count == 0) {
                            // fired this time around
                            connection->count = -1;
                            signalConnections.add(connection);
                            added = true;
                        } else if (connection->count == 1 ||
                                   (vsyncCount % connection->count) == 0) {
                            // continuous event, and time to report it
                            signalConnections.add(connection);
                            added = true;
                        }
                    }
                }
                if (eventPending && !timestamp && !added) {

                    signalConnections.add(connection);
                }
                ++i;
            } else {

                mDisplayEventConnections.removeAt(i);
                --count;
            }
        }

        if (timestamp && !waitForVSync) {

            disableVSyncLocked();
        } else if (!timestamp && waitForVSync) {

            enableVSyncLocked();//这里向DispSource中添加了Eventlistener, 见下节
        }

        if (!timestamp && !eventPending) {
            // wait for something to happen
            if (waitForVSync) {

                bool softwareSync = mUseSoftwareVSync;
                auto timeout = softwareSync ? 16ms : 1000ms;
                if (mCondition.wait_for(*lock, timeout) == std::cv_status::timeout) {
                    if (!softwareSync) {
                        ALOGW("Timed out waiting for hw vsync; faking it");
                    }
                    // FIXME: how do we decide which display id the fake
                    // vsync came from ?
                    mVSyncEvent[0].header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
                    mVSyncEvent[0].header.id = DisplayDevice::DISPLAY_PRIMARY;
                    mVSyncEvent[0].header.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
                    mVSyncEvent[0].vsync.count++;
                }
            } else {

                mCondition.wait(*lock);
            }
        }
    }

    return signalConnections;
}

EventThread::enableVSyncLocked

void EventThread::enableVSyncLocked() {
    if (!mUseSoftwareVSync) {
        // never enable h/w VSYNC when screen is off
        if (!mVsyncEnabled) {
            mVsyncEnabled = true;
            mVSyncSource->setCallback(this);//将这个source的callback设置为当前的eventThread. Vsync到来后会调用这个函数
            mVSyncSource->setVSyncEnabled(true);
        }
    }
    mDebugVsyncEnabled = true;
}

DispSyncSource::DispSyncSource::setVSyncEnabled

void DispSyncSource::setVSyncEnabled(bool enable) {
    std::lock_guard lock(mVsyncMutex);
   if (enable) {
       status_t err = mDispSync->addEventListener(mName, mPhaseOffset, static_cast(this),mLastCallbackTime);
   }
   ...
}
//dispSync.cpp
status_t DispSync::addEventListener(const char* name, nsecs_t phase, Callback* callback) {
    Mutex::Autolock lock(mMutex);
    return mThread->addEventListener(name, phase, callback);
}

MessageQueue::setEventThread

/ MessageQueue.cpp

此处mEvents的数据类型为sp,mEventTube的数据类型为sp。

void MessageQueue::setEventThread(android::EventThread* eventThread) {
    if (mEventThread == eventThread) {
        return;
    }
    if (mEventTube.getFd() >= 0) {
        mLooper->removeFd(mEventTube.getFd());
    }
    mEventThread = eventThread;
    //创建连接,从连接获得dataChannel,把它的Fd添加到Looper,
    //也就是把EventThread里的一个fd传给了SF线程,
    //以后EventThread与SF就可以通过这个fd通信,
    mEvents = eventThread->createEventConnection();
    //获取BitTube对象
    mEvents->stealReceiveChannel(&mEventTube);
    //监听BitTube,一旦有数据到来则调用cb_eventReceiver()
    // //这个cb_eventRecevier很重要,它负责处理EventThread发过来的信号
    mLooper->addFd(mEventTube.getFd(), 0, Looper::EVENT_INPUT, MessageQueue::cb_eventReceiver,
                   this);
}
sp EventThread::createEventConnection() const {
    return new Connection(const_cast(this));
}

//构造函数
EventThread::Connection::Connection(EventThread* eventThread)
      : count(-1), mEventThread(eventThread), mChannel(gui::BitTube::DefaultSize) {}

由于是强引用,执行onFirstRef

void EventThread::Connection::onFirstRef() {
    // NOTE: mEventThread doesn't hold a strong reference on us
    mEventThread->registerDisplayEventConnection(this);
}
status_t EventThread::registerDisplayEventConnection(
        const sp& connection) {
    std::lock_guard lock(mMutex);
    mDisplayEventConnections.add(connection);
    mCondition.notify_all();
    return NO_ERROR;
}

1.6 EventControlThread线程

EventControlThread::EventControlThread

EventControlThread::EventControlThread(EventControlThread::SetVSyncEnabledFunction function)
      : mSetVSyncEnabled(function) {
    pthread_setname_np(mThread.native_handle(), "EventControlThread");

    pid_t tid = pthread_gettid_np(mThread.native_handle());
    setpriority(PRIO_PROCESS, tid, ANDROID_PRIORITY_URGENT_DISPLAY);
    set_sched_policy(tid, SP_FOREGROUND);
}

1.7 SurfaceFlinger::run()

/SurfaceFlinger.cpp

void SurfaceFlinger::run() {
    do {
        waitForEvent();
    } while (true);
}

SurfaceFlinger::waitForEvent

void SurfaceFlinger::waitForEvent() {
    mEventQueue->waitMessage();
}

1.8 MessageQueue::waitMessage()

/MessageQueue.cpp

void MessageQueue::waitMessage() {
    do {
        IPCThreadState::self()->flushCommands();
        int32_t ret = mLooper->pollOnce(-1);
        switch (ret) {
            case Looper::POLL_WAKE:
            case Looper::POLL_CALLBACK:
                continue;
            case Looper::POLL_ERROR:
                ALOGE("Looper::POLL_ERROR");
                continue;
            case Looper::POLL_TIMEOUT:
                // timeout (should not happen)
                continue;
            default:
                // should not happen
                ALOGE("Looper::pollOnce() returned unknown status %d", ret);
                continue;
        }
    } while (true);
}

二 接收VSYNC信号

HWComposer对象创建过程,会注册一些回调方法,当硬件产生VSYNC信号时,则会回调hook_vsync()方法。最终会调用SurfaceFlinger::onVSyncReceived.

2.1 SurfaceFlinger::onVSyncReceived

void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
        hwc2_display_t displayId, int64_t timestamp) {
    Mutex::Autolock lock(mStateLock);
    // Ignore any vsyncs from a previous hardware composer.
    if (sequenceId != getBE().mComposerSequenceId) {
        return;
    }
    int32_t type;
    if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
        return;
    }
    bool needsHwVsync = false;
    { // Scope for the lock
        Mutex::Autolock _l(mHWVsyncLock);
        if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
            //此处mPrimaryDispSync为DispSync类, 此处调用addResyncSample对象的addResyncSample方法,那么先来看看DispSync对象的初始化过程
            needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
        }
    }

    if (needsHwVsync) {
        enableHardwareVsync();
    } else {
        disableHardwareVsync(false);
    }
}

2.2 DispSync::DispSync()

/DispSync.cpp

在surfaceFlinger构造函数中,进行初始化.
mPrimaryDispSync(“PrimaryDispSync”),接着调用了DispSync::init,执行了mThread.run函数,

DispSync::DispSync(const char* name)
        //这里初始化了一个线程.
      : mName(name), mRefreshSkipCount(0), mThread(new DispSyncThread(name)) {}

mPrimaryDispSync.addResyncSample

bool DispSync::addResyncSample(nsecs_t timestamp) {
    Mutex::Autolock lock(mMutex);
    ...
    updateModelLocked();//见下节
    ...

    return !modelLocked;
}

void DispSync::updateModelLocked()

void DispSync::updateModelLocked() {
    ...
    mThread->updateModel(mPeriod, mPhase);//初始化时创建的mThread
}

DispSync::updateModel()

    void updateModel(nsecs_t period, nsecs_t phase, nsecs_t referenceTime) {
        if (kTraceDetailedInfo) ATRACE_CALL();
        Mutex::Autolock lock(mMutex);
        mPeriod = period;
        mPhase = phase;
        mReferenceTime = referenceTime;
        mCond.signal();//唤醒目标线程
    }

2.3 DispSyncThread线程

DispSyncThread::threadLoop

线程”DispSync”停留在mCond的wait()过程,等待被mCond.signal()唤醒。

virtual bool threadLoop() {
        status_t err;
        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);

        while (true) {
            Vector callbackInvocations;
            nsecs_t targetTime = 0;
            { // Scope for lock
                ...
                if (mPeriod == 0) {
                 err = mCond.wait(mMutex);
                 continue;
                }
                ...    
                now = systemTime(SYSTEM_TIME_MONOTONIC);
                //收集vsync信号的所有回调方法
                callbackInvocations = gatherCallbackInvocationsLocked(now);
            }
            if (callbackInvocations.size() > 0) {
                //回调所有对象的onDispSyncEvent方法
                fireCallbackInvocations(callbackInvocations);//见下节
            }
        }
        return false;
    }

fireCallbackInvocations

在前面小节1.2SurfaceFlinger调用init()的过程,创建过DispSyncSource对象。接下里便是回调该对象的 onDispSyncEvent。
这里的callbacks,来自mEventListeners,是通过
addEventListener添加的.

void fireCallbackInvocations(const Vector& callbacks) {
        if (kTraceDetailedInfo) ATRACE_CALL();
        for (size_t i = 0; i < callbacks.size(); i++) {
            callbacks[i].mCallback->onDispSyncEvent(callbacks[i].mEventTime);
        }
    }

DispSyncSource.onDispSyncEvent()

virtual void onDispSyncEvent(nsecs_t when) {
        VSyncSource::Callback* callback;
        {
            Mutex::Autolock lock(mCallbackMutex);
            callback = mCallback;

            if (mTraceVsync) {
                mValue = (mValue + 1) % 2;
                ATRACE_INT(mVsyncEventLabel.string(), mValue);
            }
        }

        if (callback != nullptr) {
            callback->onVSyncEvent(when);//见下节
        }
    }

EventThread::onVSyncEvent

mCondition.notify_all能够唤醒处理waitForEventLocked()过程的EventThread,并threadMain()这个死循环函数,往下执行conn的postEvent().

void EventThread::onVSyncEvent(nsecs_t timestamp) {
    std::lock_guard lock(mMutex);
    mVSyncEvent[0].header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
    mVSyncEvent[0].header.id = 0;
    mVSyncEvent[0].header.timestamp = timestamp;
    mVSyncEvent[0].vsync.count++;
    mCondition.notify_all();//唤醒EventThread线程
}

EventThread.postEvent()

status_t EventThread::Connection::postEvent(const DisplayEventReceiver::Event& event) {
    ssize_t size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
    return size < 0 ? status_t(size) : status_t(NO_ERROR);
}

DisplayEventReceiver.sendEvents

根据小节1.5可知监听BitTube,此处调用BitTube来sendObjects。一旦收到数据,则调用MQ.cb_eventReceiver()方法。

ssize_t DisplayEventReceiver::sendEvents(const sp& dataChannel,
        Event const* events, size_t count)
{
    return BitTube::sendObjects(dataChannel, events, count);
}

2.4 MessageQueue接收到信号
MessageQueue.cb_eventReceiver

int MessageQueue::cb_eventReceiver(int fd, int events, void* data) {
    MessageQueue* queue = reinterpret_cast(data);
    return queue->eventReceiver(fd, events);
}

MessageQueue.eventReceiver

int MessageQueue::eventReceiver(int /*fd*/, int /*events*/) {
    ssize_t n;
    DisplayEventReceiver::Event buffer[8];
    while ((n = DisplayEventReceiver::getEvents(&mEventTube, buffer, 8)) > 0) {
        for (int i = 0; i < n; i++) {
            if (buffer[i].header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
                mHandler->dispatchInvalidate();
                break;
            }
        }
    }
    return 1;
}

MessageQueue::Handler::dispatchInvalidate

void MessageQueue::Handler::dispatchInvalidate() {
    if ((android_atomic_or(eventMaskInvalidate, &mEventMask) & eventMaskInvalidate) == 0) {
        mQueue.mLooper->sendMessage(this, Message(MessageQueue::INVALIDATE));
    }
}

MessageQueue::Handler::handleMessage

void MessageQueue::Handler::handleMessage(const Message& message) {
    switch (message.what) {
        case INVALIDATE:
            android_atomic_and(~eventMaskInvalidate, &mEventMask);
            mQueue.mFlinger->onMessageReceived(message.what);
            break;
        case REFRESH:
            android_atomic_and(~eventMaskRefresh, &mEventMask);
            mQueue.mFlinger->onMessageReceived(message.what);
            break;
    }
}

2.5 SurfaceFlinger处理消息

void SurfaceFlinger::onMessageReceived(int32_t what) {
    ATRACE_CALL();
    switch (what) {
        case MessageQueue::INVALIDATE: {
            bool frameMissed = !mHadClientComposition &&
                    mPreviousPresentFence != Fence::NO_FENCE &&
                    (mPreviousPresentFence->getSignalTime() ==
                            Fence::SIGNAL_TIME_PENDING);
            ATRACE_INT("FrameMissed", static_cast(frameMissed));
            if (frameMissed) {
                mTimeStats.incrementMissedFrames();
                if (mPropagateBackpressure) {
                    signalLayerUpdate();
                    break;
                }
            }
            updateVrFlinger();

            bool refreshNeeded = handleMessageTransaction();
            refreshNeeded |= handleMessageInvalidate();
            refreshNeeded |= mRepaintEverything;
            if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
                // Signal a refresh if a transaction modified the window state,
                // a new buffer was latched, or if HWC has requested a full
                // repaint
                signalRefresh();
            }
            break;
        }
        case MessageQueue::REFRESH: {
            handleMessageRefresh();
            break;
        }
    }
}

然后开始执行handleMessageTransaction(),handleMessageInvalidate()若需要refresh则调用signalRefresh()

void SurfaceFlinger::signalRefresh() {
    mRefreshPending = true;
    mEventQueue->refresh();
}
void MessageQueue::refresh() {
    mHandler->dispatchRefresh();
}

最终再调用handleMessageRefresh()

参考:
https://www.cnblogs.com/blogs-of-lxl/p/11443693.html
http://gityuan.com/2017/02/11/surface_flinger/
https://www.cnblogs.com/blogs-of-lxl/p/11272756.html

你可能感兴趣的:(Android,surfaceflinger)