1 前言
surfaceflinger 的作用是合成来自 WMS 的 Surface 数据,并发送到显示设备。
SurfaceFlinger 服务不同于 AMS、WMS、IMP、PMS、DMS 等服务,主要区别如下:
- AMS 等由 SystemServer.java 拉起,SurfaceFlinger 由 main.cpp(init 进程) 拉起;
- AMS 等运行在 system_server 进程中,SurfaceFlinger 运行在 surface_flinger 进程中;
- AMS 等启动过程中涉及到的类主要在 Java 层,SurfaceFlinger 启动过程中涉及到的类主要在 Native 层。
2 源码分析
2.1 SurfaceFlinger 创建流程
(1)main
/system/core/init/main.cpp
int main(int argc, char** argv) {
...
if (argc > 1) {
...
if (!strcmp(argv[1], "second_stage")) {
return SecondStageMain(argc, argv);
}
}
return FirstStageMain(argc, argv);
}
(2)SecondStageMain
/system/core/init/init.cpp
int SecondStageMain(int argc, char** argv) {
...
property_init(); //初始化属性服务
...
LoadBootScripts(am, sm); //加载启动脚本
..
return 0;
}
属性服务类似于 Windows 平台的注册表管理器,属性以键值对的形式呈现,如:ro.xxx.xxx = value。
(3)LoadBootScripts
/system/core/init/init.cpp
static void LoadBootScripts(ActionManager& action_manager, ServiceList& service_list) {
Parser parser = CreateParser(action_manager, service_list);
std::string bootscript = GetProperty("ro.boot.init_rc", "");
if (bootscript.empty()) {
parser.ParseConfig("/init.rc"); //解析 init.rc 配置文件
...
} else {
parser.ParseConfig(bootscript);
}
}
(4)class_start
/system/core/rootdir/init.rc
on boot
...
# Start standard binderized HAL daemons
class_start hal
class_start core //启动 classname 为 core 的 Service
init.rc 是一个配置文件,由 Android 初始化语言(Android Init Language)编写的脚本,主要包含 5 种类型语句:Action、Command、Service、Option 和 Import。
(5)surfaceflinger
/frameworks/native/services/surfaceflinger/surfaceflinger.rc
service surfaceflinger /system/bin/surfaceflinger
class core animation
user system
group graphics drmrpc readproc
onrestart restart zygote
writepid /dev/stune/foreground/tasks
socket pdx/system/vr/display/client stream 0666 system graphics u:object_r:pdx_display_client_endpoint_socket:s0
socket pdx/system/vr/display/manager stream 0666 system graphics u:object_r:pdx_display_manager_endpoint_socket:s0
socket pdx/system/vr/display/vsync stream 0666 system graphics u:object_r:pdx_display_vsync_endpoint_socket:s0
服务名:surfaceflinger,执行程序路径:/system/bin/surfaceflinger,类名:core(init.rc 文件中 class_start 启动了 core)。
(6)main
/frameworks/native/services/surfaceflinger/main_surfaceflinger.cpp
int main(int, char**) {
...
// 初始化 Hal 硬件抽象层的图元生成器服务
startGraphicsAllocatorService();
// 设置最大 binder 线程数
ProcessState::self()->setThreadPoolMaxThreadCount(4);
sp<ProcessState> ps(ProcessState::self());
ps->startThreadPool();
// 实例化 surfaceflinger
sp<SurfaceFlinger> flinger = surfaceflinger::createSurfaceFlinger();
...
// 初始化 surfaceflinger
flinger->init();
// 将 flinger 添加到 ServiceManager 进程中
sp<IServiceManager> sm(defaultServiceManager());
sm->addService(String16(SurfaceFlinger::getServiceName()), flinger, false, IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL | IServiceManager::DUMP_FLAG_PROTO);
...
//启动 DisplayService
startDisplayService();
// 启动 surfaceflinger
flinger->run();
...
return 0;
}
(7)createSurfaceFlinger
/frameworks/native/services/surfaceflinger/SurfaceFlingerFactory.cpp
namespace android::surfaceflinger {
sp<SurfaceFlinger> createSurfaceFlinger() {
class Factory final : public surfaceflinger::Factory {
public:
...
std::unique_ptr<EventControlThread> createEventControlThread(
std::function<void(bool)> setVSyncEnabled) override {
return std::make_unique<android::impl::EventControlThread>(setVSyncEnabled);
}
std::unique_ptr<HWComposer> createHWComposer(const std::string& serviceName) override {
return std::make_unique<android::impl::HWComposer>(
std::make_unique<Hwc2::impl::Composer>(serviceName));
}
std::unique_ptr<MessageQueue> createMessageQueue() override {
return std::make_unique<android::impl::MessageQueue>();
}
...
};
static Factory factory;
return new SurfaceFlinger(factory);
}
} // namespace android::surfaceflinger
(8)SurfaceFlinger
/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
: mFactory(factory),
mPhaseOffsets(mFactory.createPhaseOffsets()),
mInterceptor(mFactory.createSurfaceInterceptor(this)),
mTimeStats(mFactory.createTimeStats()),
mEventQueue(mFactory.createMessageQueue()),
mCompositionEngine(mFactory.createCompositionEngine()) {}
SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
hasSyncFramework = running_without_sync_framework(true);
dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
maxVirtualDisplaySize = max_virtual_display_dimension(0); //最大虚拟屏个数
useVrFlinger = use_vr_flinger(false);
maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
hasWideColorDisplay = has_wide_color_display(false);
useColorManagement = use_color_management(false);
...
}
2.2 SurfaceFlinger 初始化流程
(1)init
/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
void SurfaceFlinger::init() {
...
mScheduler = getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); }, mRefreshRateConfigs);
auto resyncCallback = mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
// 初始化 App 的 ConnectionHandle
mAppConnectionHandle = mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(), resyncCallback, impl::EventThread::InterceptVSyncsCallback());
// 初始化 SF 的 ConnectionHandle
mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(), resyncCallback, [this](nsecs_t timestamp) {
mInterceptor->saveVSyncEvent(timestamp);
});
// 将 mSfConnectionHandle 对应的 EventThreadConnection 注入 mEventQueue
mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
...
mRegionSamplingThread = new RegionSamplingThread(*this, *mScheduler, RegionSamplingThread::EnvironmentTimingTunables());
...
// 创建 GLESRenderEngine 渲染引擎
mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat), renderEngineFeature, maxFrameBufferAcquiredBuffers));
...
mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
// 将 this 封装到 ComposerCallbackBridge,再注入到 IComposerClient 的实现类中
mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
// 处理初始热插拔事件和由此导致的 Display 的改变
processDisplayHotplugEventsLocked();
const auto display = getDefaultDisplayDeviceLocked();
...
if (useVrFlinger) {
...
mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(), getHwComposer().fromPhysicalDisplayId(*display->getId()).value_or(0),
vrFlingerRequestDisplayCallback);
...
}
// 初始化绘制状态
mDrawingState = mCurrentState;
// 调用 onInitializeDisplays,初始化 Display 的宽高等信息
initializeDisplays();
getRenderEngine().primeCache();
...
mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
...
mScheduler->setChangeRefreshRateCallback([this](RefreshRateType type, Scheduler::ConfigEvent event) {
Mutex::Autolock lock(mStateLock);
setRefreshRateTo(type, event);
});
mScheduler->setGetVsyncPeriodCallback([this] {
Mutex::Autolock lock(mStateLock);
return getVsyncPeriod();
});
mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
...
}
说明:
1)每个 ConnectionHandle 对象里有个 id,作为 Scheduler 对象中 mConnections 属性(map<id, Connection>)的键值,Connection 对象中又包含 ConnectionHandle、EventThreadConnection、EventThread 3个属性。
2)mScheduler->getEventConnection(mSfConnectionHandle) 中,以 mSfConnectionHandle 的 id 为键值,在 Scheduler 的 mConnections(unordered_map<int64_t, Connection>)中找到对应的Connection,并返回其 EventThreadConnection 成员属性。
3)getHwComposer().registerCallback() 中,依次调用 HwComposer、Device 的 registerCallback() 方法,并在 Device 中 将 SurfaceFlinger 对象封装到 ComposerCallbackBridge 中;对于封装后的对象,依次调用 Composer、IComposerClient 的 registerCallback() 方法,注入到 IComposerClient 的实现类中。
(2)startDisplayService
/frameworks/native/services/surfaceflinger/main_surfaceflinger.cpp
static status_t startDisplayService() {
...
sp<IDisplayService> displayservice = new DisplayService();
status_t err = displayservice->registerAsService();
...
return err;
}
(3)run
/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
void SurfaceFlinger::run() {
do {
waitForEvent();
} while (true);
}
(4)waitForEvent
/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
void SurfaceFlinger::waitForEvent() {
mEventQueue->waitMessage();
}
声明:本文转自【framework】surfaceflinger启动流程
标签:...,init,流程,surfaceflinger,system,framework,SurfaceFlinger,display From: https://www.cnblogs.com/zhyan8/p/17233685.html