显示图形系统分析之默认DisplayDevice显示设备加载流程分析

1,884 阅读11分钟

「这是我参与2022首次更文挑战的第6天,活动详情查看:2022首次更文挑战」。

默认DisplayDevice显示设备加载流程分析

在前篇SurfaceFlinger启动流程分析中,有分析过,在SurfaceFlinger服务启动的过程中,当HWComposer指针对象的setConfiguration函数调用的时候,有Display驱动层向frameworks层发送信号,从而调用SurfaceFlinger回调函数onHotplugReceive函数,接下来我们就接着这个函数来继续分析

// 第一个参数是一个整形变量,其通过HWComposer指针对象的setConfiguration函数设置到Display驱动,此时回调函数需要判断其跟设置的是否一致,若不一致,此处会直接退出
// 第二个参数hwcDisplayId,是Display驱动层对于显示设备的一个唯一标识
// 第三个参数代表的是当前是否已经连接,从日志和代码中看,收到回调时,为Connected
void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
                                       hal::Connection connection) {
    // ...... 日志打印,此处省略
    // Ignore events that do not have the right sequenceId.
    // 判断sequenceId是否和传入的一致
    if (sequenceId != getBE().mComposerSequenceId) {
        return;
    }

    // Only lock if we're not on the main thread. This function is normally
    // called on a hwbinder thread, but for the primary display it's called on
    // the main thread with the state lock already held, so don't attempt to
    // acquire it here.
    ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
    // 初始化一个HotplugEvent,添加到mPendingHotplugEvents中
    mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});

    if (std::this_thread::get_id() == mMainThreadId) {
        // Process all pending hot plug events immediately if we are on the main thread.
        // 主线程中调用Display插入事件函数
        processDisplayHotplugEventsLocked();
    }
    // 设置SurfaceFlinger的事务Flags
    setTransactionFlags(eDisplayTransactionNeeded);
}

此处我们重点分析processDisplayHotplugEventsLocked函数的调用

void SurfaceFlinger::processDisplayHotplugEventsLocked() {
    // 还记得在上个函数onHotplugReceive函数中添加了一个HotplugEvent么?
    for (const auto& event : mPendingHotplugEvents) {
        // 1. HWComposer对象的onHotplug函数调用
        // 这边会判断当前的hwcDisplayID对应的DisplayIdentificationInfo是否存在
        // 若不存在,则初始化一个DisplayIdentificationInfo对象,同时会在系统层中分配当前默认Display的内存空间
        // 若存在,则更新其参数
        const std::optional<DisplayIdentificationInfo> info =
                getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
        // ...... 第一次进入,此处代码可忽略,省略
        const DisplayId displayId = info->id;
        // 第一次进入的时候,此处由于未添加mPhysicalDisplayTokens
        // 因此此处获取的it一定为end
        const auto it = mPhysicalDisplayTokens.find(displayId);
        
        if (event.connection == hal::Connection::CONNECTED) {
            if (it == mPhysicalDisplayTokens.end()) {
                ALOGV("Creating display %s", to_string(displayId).c_str());

                if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
                    // 2. 初始化Scheduler,同时创建SurfaceFlinger的两大EventThread
                    initScheduler(displayId);
                }
                // 3. 初始化一个DisplayDeviceState对象,并且保存
                DisplayDeviceState state;
                state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
                                  event.hwcDisplayId};
                state.isSecure = true; // All physical displays are currently considered secure.
                state.displayName = info->name;

                sp<IBinder> token = new BBinder();
                mCurrentState.displays.add(token, state);
                mPhysicalDisplayTokens.emplace(displayId, std::move(token));

                mInterceptor->saveDisplayCreation(state);
            } 
            // ...... else条件无法满足,此处代码省略不看
        }
        // ...... else条件无法满足,此处代码省略不看
        // 4. 调用Display对象变化事件处理
        processDisplayChangesLocked();
    }
    // 清理本次的HotplugEvent
    mPendingHotplugEvents.clear();
}

如上的代码备注,此处我们需要按照如上的四条步骤分析,因此

HWComposer对象的onHotplug函数调用

std::optional<DisplayIdentificationInfo> HWComposer::onHotplug(hal::HWDisplayId hwcDisplayId,
                                                               hal::Connection connection) {
    switch (connection) {
        case hal::Connection::CONNECTED:
            return onHotplugConnect(hwcDisplayId);
        // ...... 条件不满足,代码省略
    }
}

std::optional<DisplayIdentificationInfo> HWComposer::onHotplugConnect(
        hal::HWDisplayId hwcDisplayId) {
    std::optional<DisplayIdentificationInfo> info;
    // 显然条件不满足
    if (const auto displayId = toPhysicalDisplayId(hwcDisplayId)) {
        // ...... 此分支不进入,代码省略
    } else {
        uint8_t port;
        DisplayIdentificationData data;
        // ...... 一些判空操作以及功能无关的代码,省略
        // 直接初始化一个DisplayIdentificationInfo对象
        info = [this, hwcDisplayId, &port, &data, hasDisplayIdentificationData] {
            const bool isPrimary = !mInternalHwcDisplayId; // true
            if (mHasMultiDisplaySupport) {
                // ...... 从日志和代码分析看,此处无法进入,代码省略
            } else {
                // ...... 日志打印,此处省略
                port = isPrimary ? LEGACY_DISPLAY_TYPE_PRIMARY : LEGACY_DISPLAY_TYPE_EXTERNAL;
            }
            // 最后直接返回此处的DisplayIdentificationInfo对象
            return DisplayIdentificationInfo{.id = getFallbackDisplayId(port),
                                             .name = isPrimary ? "Internal display"
                                                               : "External display",
                                             .deviceProductInfo = std::nullopt};
        }();
    }
    // 这边还没有开始设定,因此此处if语句直接返回true,为PhysicalDisplay分配内存空间
    if (!isConnected(info->id)) {
        allocatePhysicalDisplay(hwcDisplayId, info->id);
    }
    return info;
}

如上述的分析,此处初始化一个DisplayIdentificationInfo对象,然后同时会为刚刚初始化出来的DisplayId对应在frameworks层分配一个Display对象的内存空间

void HWComposer::allocatePhysicalDisplay(hal::HWDisplayId hwcDisplayId, DisplayId displayId) {
    // 此前均未有设定,因此此处设定mInternalHwcDisplayId为Display驱动返回的displayId
    if (!mInternalHwcDisplayId) {
        mInternalHwcDisplayId = hwcDisplayId;
    }
    // ...... else无法走入,此处代码省略
    
    // 初始化一个Display对象
    auto& displayData = mDisplayData[displayId];
    auto newDisplay =
            std::make_unique<HWC2::impl::Display>(*mComposer.get(), mCapabilities, hwcDisplayId,
                                                  hal::DisplayType::PHYSICAL);
    // 此处不仅设置newDisplay.mIsConnected = true
    // 同时会从Display驱动处加载显示设备对应的配置
    newDisplay->setConnected(true);
    displayData.hwcDisplay = std::move(newDisplay);
    mPhysicalDisplayIdMap[hwcDisplayId] = displayId;
}
classDiagram
class Display {
-Hwc2::Composer:mComposer
-unordered_set<hal::Capability>& mCapabilities
-hal::HWDisplayId mId
-hal::DisplayType mType
}
class HWComposer {
-std::unordered_map<DisplayId, DisplayData> mDisplayData
+allocatePhysicalDisplay(hal::HWDisplayId hwcDisplayId, DisplayId displayId)
-std::unique_ptr<android::Hwc2::Composer> mComposer
}
Display o-- Composer
HWComposer o-- Composer

从代码和类关系来看,此处会初始化mDisplayData[displayId]对应的数据,并且将mPhysicalDisplayIdMap[hwcDisplayId]和displayId进行对应

至此,hwcDisplayId所对应的frameworks对应的displayId和Display对象均已经初始化完成,并且和Display驱动侧的对应的显示设备ID进行一一对应起来

Scheduler指针对象初始化,以及SurfaceFlinger的两个EventThread创建

回到SurfaceFlinger::processDisplayHotplugEventsLocked函数中,会通过调用SurfaceFlinger::initScheduler函数来做相应的操作

void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
    // ...... 当Scheduler已经创建,此处直接返回,此处第一次进入,代码省略
	// 注意,此处传入的参数是frameworks层对应的displayId
	// 此处从驱动侧获取显示对应的配置,并获取对应的有效的配置
    auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
    mRefreshRateConfigs =
            std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
                                                                    primaryDisplayId),
                                                            currentConfig);
	// 初始化RefreshRateStats
    mRefreshRateStats =
            std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
                                                          currentConfig, hal::PowerMode::OFF);
    mRefreshRateStats->setConfigMode(currentConfig);
	// 初始化PhaseConfiguration对象
    mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);

    // start the EventThread
    // 1. 初始化Scheduler对象
    mScheduler =
            getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
                                         *mRefreshRateConfigs, *this);
	// 2. 初始化两个ConnectionHandle对象
    mAppConnectionHandle =
            mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
                                         impl::EventThread::InterceptVSyncsCallback());
    mSfConnectionHandle =
            mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
                                         [this](nsecs_t timestamp) {
                                             mInterceptor->saveVSyncEvent(timestamp);
                                         });
	// 3. 设置EventQueue的ConnectionHandle
    mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
    mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
                            mPhaseConfiguration->getCurrentOffsets());
	// 4. 启动一个RegionSamplingThread对象
    mRegionSamplingThread =
            new RegionSamplingThread(*this, *mScheduler,
                                     RegionSamplingThread::EnvironmentTimingTunables());
    // Dispatch a config change request for the primary display on scheduler
    // initialization, so that the EventThreads always contain a reference to a
    // prior configuration.
    //
    // This is a bit hacky, but this avoids a back-pointer into the main SF
    // classes from EventThread, and there should be no run-time binder cost
    // anyway since there are no connected apps at this point.
    // 5. 设置VSYNC信号周期
    const nsecs_t vsyncPeriod =
            mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
    mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, primaryDisplayId.value,
                                              currentConfig, vsyncPeriod);
}

初始化Scheduler指针对象

// 从DefaultFactory中通过createScheduler函数初始化
// 第一个参数为SurfaceFlinger::initScheduler函数传入的第一个参数
// 第二个参数为此前初始化的RefreshRateConfigs,它的刷新率数据通过Display驱动获取
// 第三个参数为SurfaceFlinger对象
// 第四个参数为true
// 第五个参数为false
Scheduler::Scheduler(impl::EventControlThread::SetVSyncEnabledFunction function,
                     const scheduler::RefreshRateConfigs& refreshRateConfig,
                     ISchedulerCallback& schedulerCallback, bool useContentDetectionV2,
                     bool useContentDetection)
      : mSupportKernelTimer(sysprop::support_kernel_idle_timer(false)),
        mPrimaryDispSync(createDispSync(mSupportKernelTimer)),   // 创建一个DispSync指针对象
        // 创建一个EventControlThread指针对象,注意其传入参数为SurfaceFlinger::initScheduler函数传入的第一个参数
        mEventControlThread(new impl::EventControlThread(std::move(function))),
        mSchedulerCallback(schedulerCallback),
        mRefreshRateConfigs(refreshRateConfig),
        mUseContentDetection(useContentDetection),
        mUseContentDetectionV2(useContentDetectionV2) {
    using namespace sysprop;

    if (mUseContentDetectionV2) {
        // 初始化一个LayerHistory
        // 这个类主要用作保存创建过的Layer图层
        mLayerHistory = std::make_unique<scheduler::impl::LayerHistoryV2>(refreshRateConfig);
    }
    // ...... else分支无法进入,此处省略
    const int setIdleTimerMs = property_get_int32("debug.sf.set_idle_timer_ms", 0);

    // ...... 默认不进入,代码省略
}
classDiagram
class Scheduler {
-std::unique_ptr<DispSync>:mPrimaryDispSync
-std::unique_ptr<EventControlThread>:mEventControlThread
-ISchedulerCallback&:mSchedulerCallback
-std::unique_ptr<LayerHistory>:mLayerHistory
-createDispSync(bool)
-createConnection(std::unique_ptr<EventThread>)
-setVsyncPeriod(nsecs_t period)
}
class VSyncReactor {
-std::unique_ptr<VSyncDispatch>:mDispatch
-std::unique_ptr<VSyncTracker>:mTracker
}
class EventControlThread {
-SetVSyncEnabledFunction:mSetVSyncEnabled
-threadMain()
+setVsyncEnabled(bool enabled)
}
Scheduler o-- EventControlThread
DispSync <|-- VSyncReactor
VSyncTracker <|-- VSyncPredictor
Scheduler o-- VSyncReactor
VSyncReactor o-- VSyncPredictor
VSyncDispatch <|-- VSyncDispatchTimerQueue
VSyncReactor o-- VSyncDispatchTimerQueue
Scheduler o-- LayerHistoryV2

从代码和类图中可以看到,此处主要

  1. 初始化VSyncReactor指针对象,该类继承自DispSync
  2. 初始化一个EvenControlThread指针对象,上述这两个类均和VSYNC信号有关,此处我们暂时不分析,待后续分析时再行确认
  3. 初始化一个LayerHistoryV2指针对象,该类继承自LayerHistory,这个类的主要作用是保存创建过的Layer图层信息

初始化两个ConnectionHandle

通过调用Scheduler::createConnection函数初始化ConnectionHandle对象

Scheduler::ConnectionHandle Scheduler::createConnection(
        const char* connectionName, nsecs_t phaseOffsetNs,
        impl::EventThread::InterceptVSyncsCallback interceptCallback) {
    // 初始化一个DispSyncSource指针对象
    auto vsyncSource = makePrimaryDispSyncSource(connectionName, phaseOffsetNs);
    // 初始化一个EventThread指针对象
    auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource),
                                                           std::move(interceptCallback));
    // 调用同名函数初始化
    return createConnection(std::move(eventThread));
}

std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(const char* name,
                                                                  nsecs_t phaseOffsetNs) {
    return std::make_unique<DispSyncSource>(mPrimaryDispSync.get(), phaseOffsetNs,
                                            true /* traceVsync */, name);
}

Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
    // 设置ConnectionHandle索引
    const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
    ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);

    auto connection =
            createConnectionInternal(eventThread.get(), ISurfaceComposer::eConfigChangedSuppress);

    mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
    return handle;
}
classDiagram
class DispSyncSource {
-DispSync*:mDispSync
-char*:mName
-bool:mTraceVsync
+getName()
+setVSyncEnabled(bool enable)
+setCallback(VSyncSource::Callback* callback)
-onDispSyncEvent(nsecs_t, nsecs_t)
-VSyncSource::Callback*:mCallback
}
class EventThread {
-std::unique_ptr<VSyncSource>:mVSyncSource
-InterceptVSyncsCallback:mInterceptVSyncsCallback
-onVSyncEvent(nsecs_t, nsecs_t)
+createEventConnection(ResyncCallback, ISurfaceComposer::ConfigChanged)
+registerDisplayEventConnection(const sp<EventThreadConnection>&)
}
class Scheduler {
-unordered_map<ConnectionHandle, Connection>:mConnections
-createConnection(std::unique_ptr<EventThread>)
-createConnectionInternal(EventThread*, ISurfaceComposer::ConfigChanged)
-makePrimaryDispSyncSource(const char*, nsecs_t)
}
class EventThreadConnection {
+ResyncCallback:resyncCallback
+const ISurfaceComposer::ConfigChanged:mConfigChanged
+VSyncRequest:vsyncRequest
-EventThread* const:mEventThread
+postEvent(const DisplayEventReceiver::Event&)
+setVsyncRate(uint32_t)
-onFirstRef()
-gui::BitTube:mChannel
}
class Connection {
sp<EventThreadConnection>:connection
std::unique_ptr<EventThread>:thread
}
Scheduler o-- Connection
BnDisplayEventConnection <|-- EventThreadConnection
EventThread o-- DispSyncSource
EventThreadConnection o-- EventThread
Connection -- EventThread
Connection -- EventThreadConnection

由上述的代码和类关系图可以知道,这边主要的步骤是

  1. 由makePrimaryDispSyncSource函数生成一个DispSyncSource指针对象,这个指针对象有一个参数mDispSync指向Scheduler初始化过程中创建的VSyncReactor指针对象,该对象的类继承自DispSync类
  2. 初始化一个EventThread的指针对象,这个EventThread指针对象包含一个参数名为mVSyncSource的指针指向刚刚创建的DispSyncSource对象,同时有一个参数名为mInterceptVSyncsCallback对象,其为一个方法的索引,为SurfaceFlinger中通过Scheduler的createConnection函数的最后一个参数传入的函数索引
  3. 通过上述创建的EventThread指针对象调用其createEventConnection函数创建一个EventThreadConnection指针对象,这个指针对象中包含一个参数名为mEventThread的指针指向刚刚创建的EventThread对象,同时有一个mConfigChanged定义为ISurfaceComposer::eConfigChangedSuppress,还有一个参数名为resyncCallback的函数索引为Scheduler::createConnectionInternal函数中调用EventThread::createEventConnection时传入的第一个参数对应的函数
  4. EventThreadConnection在初始化的过程中,会调用EventThread的registerDisplayEventConnection函数来注册,实际上,就是将上述的EventThreadConnection添加到EventThread::mDisplayEventConnections中
  5. 在EvnetThread和EventThreadConnection初始化完成后,将其组成一个Scheduler::Connection结构体对象,使用初始化的ConnectionHandle索引为key,结构体对象为Value,添加到Scheduler::mConnections无序MAP中
  6. Scheduler::createConnection函数返回上述对应的ConnectionHandle索引

SurfaceFlinger::MessageQueue设置EventConnection链接

mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));

由前述的代码分析,

Scheduler::getEventConnection(mSfConnectionHandle)

函数最终会返回对应的名称为sf的EventThreadConnection指针对象

void MessageQueue::setEventConnection(const sp<EventThreadConnection>& connection) {
    if (mEventTube.getFd() >= 0) {
        mLooper->removeFd(mEventTube.getFd());
    }

    mEvents = connection;
    mEvents->stealReceiveChannel(&mEventTube);
    mLooper->addFd(mEventTube.getFd(), 0, Looper::EVENT_INPUT, MessageQueue::cb_eventReceiver,
                   this);
}

然后MessageQueue::setEventConnection会将其mEvents参数指向该EventThreadConnection对象,同时通过Looper::addFd将sf对应的EventConnectionThread的mReceiveFd添加到SurfaceFlinger::MessageQueue中

VSyncModulator对象初始化

mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
                            mPhaseConfiguration->getCurrentOffsets());
                            
VSyncModulator::VSyncModulator(IPhaseOffsetControl& phaseOffsetControl,
                               Scheduler::ConnectionHandle appConnectionHandle,
                               Scheduler::ConnectionHandle sfConnectionHandle,
                               const OffsetsConfig& config)
      : mPhaseOffsetControl(phaseOffsetControl),
        mAppConnectionHandle(appConnectionHandle),
        mSfConnectionHandle(sfConnectionHandle),
        mOffsetsConfig(config) {
    // ...... 功能无关代码,省略
}
classDiagram
class SurfaceFlinger {
-std::optional<scheduler::VSyncModulator>:mVSyncModulator
}
class VSyncModulator {
-IPhaseOffsetControl&:mPhaseOffsetControl
-const ConnectionHandle:mAppConnectionHandle
-const ConnectionHandle:mSfConnectionHandle
-OffsetsConfig:mOffsetsConfig
}
IPhaseOffsetControl <|-- Scheduler
VSyncModulator o-- Scheduler
SurfaceFlinger o-- VSyncModulator

由类图可以清晰看出类之间的关系

DisplayDeviceState对象创建和保存

回到SurfaceFlinger::processDisplayHotplugEventsLocked函数中,创建一个DisplayDeviceState对象

DisplayDeviceState state;
state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
                  event.hwcDisplayId};
state.isSecure = true; // All physical displays are currently considered secure.
state.displayName = info->name;

sp<IBinder> token = new BBinder();
mCurrentState.displays.add(token, state); // 添加DisplayDeviceState
mPhysicalDisplayTokens.emplace(displayId, std::move(token)); 

这边主要是初始化一个DisplayDeviceState对象,然后将其分别通过

  1. 以新初始化的BBinder指针对象为key,以DisplayDeviceState对象为value添加到mCurrentState.displays中
  2. 将displayId和上述的BBinder指针对象组成键值对添加到mPhysicalDisplayTokens中

显示设备变化事件处理

最后会引起显示设备事件触发

processDisplayChangesLocked();
void SurfaceFlinger::processDisplayChangesLocked() {
    // here we take advantage of Vector's copy-on-write semantics to
    // improve performance by skipping the transaction entirely when
    // know that the lists are identical
    const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
    const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
    if (!curr.isIdenticalTo(draw)) {
        mVisibleRegionsDirty = true;

        // ...... 既非添加也非更新,此处代码省略

        // find displays that were added
        // (ie: in current state but not in drawing state)
        for (size_t i = 0; i < curr.size(); i++) {
            const wp<IBinder>& displayToken = curr.keyAt(i);
            if (draw.indexOfKey(displayToken) < 0) {
                // 运行添加事件
                processDisplayAdded(displayToken, curr[i]);
            }
        }
    }
    mDrawingState.displays = mCurrentState.displays;
}

void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
                                         const DisplayDeviceState& state) {
    int width = 0;
    int height = 0;
    ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
    if (state.physical) {
        // 从Display驱动获取有效地配置
        const auto& activeConfig =
                getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
        width = activeConfig->getWidth();
        height = activeConfig->getHeight();
        pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
    }
    // ...... else条件不满足,此处代码省略

    compositionengine::DisplayCreationArgsBuilder builder;
    if (const auto& physical = state.physical) {
        builder.setPhysical({physical->id, physical->type});
    }
    builder.setPixels(ui::Size(width, height));
    builder.setPixelFormat(pixelFormat);
    builder.setIsSecure(state.isSecure);
    builder.setLayerStackId(state.layerStack);
    builder.setPowerAdvisor(&mPowerAdvisor);
    builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
    builder.setName(state.displayName);
    // createDisplay
    const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());

    sp<compositionengine::DisplaySurface> displaySurface;
    sp<IGraphicBufferProducer> producer;
    sp<IGraphicBufferProducer> bqProducer;
    sp<IGraphicBufferConsumer> bqConsumer;
    // 初始化bqProducer和bqConsumer
    getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);

    std::optional<DisplayId> displayId = compositionDisplay->getId();

    if (state.isVirtual()) {
        // ...... 不满足条件,省略代码
    } else {
        // ...... 日志判断,省略代码
        // 初始化一个FramebufferSurface指针对象
        displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
                                                maxGraphicsWidth, maxGraphicsHeight);
        producer = bqProducer;
    }

    LOG_FATAL_IF(!displaySurface);
    const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
                                                       displaySurface, producer);
    mDisplays.emplace(displayToken, display);
    if (!state.isVirtual()) {
        LOG_FATAL_IF(!displayId);
        dispatchDisplayHotplugEvent(displayId->value, true);
    }

    if (display->isPrimary()) {
        mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
    }
}

其中总体的调用关系如下

sequenceDiagram
SurfaceFlinger --> SurfaceFlinger : processDisplayHotplugEventsLocked
SurfaceFlinger --> SurfaceFlinger : processDisplayChangesLocked
SurfaceFlinger --> SurfaceFlinger : processDisplayAdded
SurfaceFlinger --> CompositionEngine : createDisplay
CompositionEngine --> Display : createDisplay
Display --> Display : createDisplayTemplated
Display --> Output : createOutputTemplated
Output --> Output : new
Display --> Display : setConfiguration
SurfaceFlinger --> DefaultFactory : createBufferQueue
DefaultFactory --> BufferQueue : new
BufferQueue --> BufferQueueCore : new
BufferQueue --> BufferQueueProducer : new
BufferQueue --> BufferQueueConsumer : new
SurfaceFlinger --> FramebufferSurface : new
SurfaceFlinger --> SurfaceFlinger : setupNewDisplayDeviceInternal
SurfaceFlinger --> DefaultFactory:createNativeWindowSurface
DefaultFactory --> NativeWindowSurface : createNativeWindowSurface
NativeWindowSurface --> NativeWindowSurface : new
SurfaceFlinger --> DefaultFactory : createDisplayDevice
DefaultFactory --> DisplayDevice : new
SurfaceFlinger --> SurfaceFlinger : dispatchDisplayHotplugEvent
SurfaceFlinger --> Scheduler : onHotplugReceived
Scheduler --> EventThread : onHotplugReceived
SurfaceFlinger --> Scheduler : onPrimaryDisplayAreaChanged
classDiagram
ConsumerBase <|-- FramebufferSurface
DisplaySurface <|-- FramebufferSurface
Output <|-- Display
DisplayDevice o-- Display
Display o-- RenderSurface
RenderSurface o-- FramebufferSurface
class FramebufferSurface {
-HWComposer&:mHwc
-const DisplayId:mDisplayId
}
class ConsumerBase {
#sp<IGraphicBufferConsumer>:mConsumer
}
class DisplayDevice {
-sp<SurfaceFlinger>:mFlinger
-wp<IBinder>:mDisplayToken
-int32_t:mSequenceId
-std::optional<DisplayConnectionType>:mConnectionType
-std::shared_ptr<compositionengine::Display>:mCompositionDisplay
-ui::Rotation:mPhysicalOrientation
}
class RenderSurface {
-compositionengine::CompositionEngine&:mCompositionEngine
-compositionengine::Display&:mDisplay
-sp<ANativeWindow>:mNativeWindow
-sp<GraphicBuffer>:mGraphicBuffer
-sp<DisplaySurface>:mDisplaySurface
+queueBuffer(base::unique_fd readyFence)
+dequeueBuffer(base::unique_fd* bufferFence)
+createRenderSurface()
}
class Display {
+createRenderSurface(const RenderSurfaceCreationArgs&)
}
class Output {
+setRenderSurface(std::unique_ptr<compositionengine::RenderSurface>)
-std::unique_ptr<compositionengine::RenderSurface> mRenderSurface
}

在这边会做如下的几个操作

  1. 通过CompositionEngine::createDisplay函数会创建一个android::compositionengine::impl::Display对象,其定义于/frameworks/native/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h中,其中参数使用上述代码中传入的参数
  2. 通过DefaultFactory::createBufferQueue函数初始化BufferQueueProducer指针对象和BufferQueueComsumer指针对象,通过BufferQueueComsumer指针对象作为参数,创建一个FramebufferSurface指针对象
  3. 通过SurfaceFlinger::setupNewDisplayDeviceInternal函数,以上述初始化的BufferQueueProducer指针对象和FramebufferSurface指针对象作为参数创建一个DisplayDevice指针对象
  4. 将mDisplayToken作为key,刚刚创建的DisplayDevice指针对象作为value,组成键值对,添加到mDisplays集合Map中
  5. 然后通过SurfaceFlinger::dispatchDisplayHotplugEvent函数,由Scheduler指针对象向"app"和"sf"对应的EventThreadConnection中发送onHotplugReceived回调函数
  6. 更新显示区域

总结

  1. SurfaceFlinger::init函数中,会调用到HWComposer::setConfiguration函数,在这个函数运行结束后,Display驱动会发送信号给frameworks,并且由SurfaceFlinger::onHotplugReceive函数回调
  2. 在SurfaceFlinger::onHotplugReceive函数中,会调用SurfaceFlinger::processDisplayHotplugEventsLocked函数来运行添加默认显示设备的事件
  3. 在SurfaceFlinger::processDisplayHotplugEventsLocked函数的起初,会通过HWComposer::onHotplug函数初始化一个Display对象,并且将其设置为SurfaceFlinger::mDisplayData[displayId].hwcDisplay,同时在SurfaceFlinger::mPhysicalDisplayIdMap中将hwcDisplayId和displayId进行对应
  4. 此后初始化一个Scheduler指针对象,在这个指针对象初始化的时候,初始化其参数mPrimaryDispSync指向一个VSyncReactor对象,其继承于DispSync类,同时初始化参数mEventControlThread指向初始化的EventControlThread对象
  5. 然后创建两个ConnectionHandle索引,这两个索引分别对应sf和app,ConnectionHandle索引在Scheduler::mConnections中对应一个Connection结构体对象,这个结构体对象中包含EventThreadConnection和EventThread对象
  6. SurfaceFlinger::mEventQueue将上述sf的ConnectionHandle对应的EventThreadConnection添加到Looper中响应事件
  7. 此后又初始化了一个VSyncModulator指针对象
  8. 在SurfaceFlinger中创建DisplayDeviceState对象,并且初始化一个BBinder和这个DisplayDeviceState对象组成键值对添加到mCurrentState.displays中,同时使用displayId和上述初始化的BBinder对象作为键值对,添加到mPhysicalDisplayTokens中
  9. 触发设备添加事件SurfaceFlinger::processDisplayAdded,在这个函数中,会初始化DisplayDevice指针对象,创建FramebufferSurface画布等