首页 > 其他分享 >【framework】surfaceflinger启动流程

【framework】surfaceflinger启动流程

时间:2023-03-19 17:22:36浏览次数:48  
标签:... init 流程 surfaceflinger system framework SurfaceFlinger display

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 创建流程

img

(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 初始化流程

img

(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

相关文章

  • java的流程控制-break continue
    breakcontinuebreak:在任何循环语句的主体部分,均可用break控制循环的流程。break用于强行退出循环,不执行循环中剩余的语句。(break也在switch语句中使用) continue:在......
  • Vue.js props配置(微信收款确认流程)
    视频直接修改外来数据props会产生警告props配置项1.功能:让组件接收外部传过来的数据2.传递数据:```<Demoname="xxx"/>```3.接收数据:1.第一种方式(只接收......
  • java流程控制
    java流程控制Scanner对象通过新建Scanner类来获取用户的输入基本语法:Scannerscanner=newScanner(system.in)Stringstr=scanner.nextLine(),inti=scanner.ne......
  • python安装robotframework的一些常见的错误
    python安装robotframework的一些常见的错误首先的电脑环境是x86的,然后下载的python版本起初是3.10.1的在cmd中出入pipinstallrobotframwork是没有问题的,但是在输入下......
  • 【Python从入门到进阶】10、流程控制语句-循环语句(for-while)
    接上篇《9、流程控制语句-条件语句(if-else)》上一篇我们学习了Python的控制流语句的概念,以及其中的条件语句(if/else),本篇我们来学习控制流语句中的循环语句(for/while)。......
  • 逻辑备份与online ddl流程
    逻辑备份:6步   onlineddl:5步 ......
  • 请你详细说说类加载流程,类加载机制及自定义类加载器
    当程序使用某个类时,如果该类还未被加载到内存中,则JVM会通过加载、链接、初始化三个步骤对该类进行类加载。加载类加载指的是将类的class文件读入内存,并为之创建一个java.......
  • nanoFramework
    nanoFramework01:GettingstartedwithnanoFramework!08:.NETnanoFrameworkGPIO,I2C,SPIandotherIOsupport......
  • (3) MasaFramework 入门第三篇,使用MasaFramework
    首先我们需要创建一个MasaFramework模板的项目,项目名称TokenDemo,项目类型如图所示删除Web/TokenDemo.Admin项目,新建MasaBlazorPro项目模板项目,项目位置在src/Web项目......
  • Selenium 4.x Grid各组件功能和执行流程
    Node注册的时候,是通过EventBus向Distributor发消息一个请求来了之后,会经过Router(Router也是唯一一个向外暴露的组件),Router就像路由器一样,判断Session是否存在......