//frameworks/native/services/surfacefilinger/main_SurfaceFlinger.cpp
intmain(int,char**){signal(SIGPIPE,SIG_IGN);hardware::configureRpcThreadpool(1/* maxThreads */,false/* callerWillJoin */);startGraphicsAllocatorService();// When SF is launched in its own process, limit the number of
// binder threads to 4.
ProcessState::self()->setThreadPoolMaxThreadCount(4);// Set uclamp.min setting on all threads, maybe an overkill but we want
// to cover important threads like RenderEngine.
if(SurfaceFlinger::setSchedAttr(true)!=NO_ERROR){ALOGW("Couldn't set uclamp.min: %s\n",strerror(errno));}// The binder threadpool we start will inherit sched policy and priority
// of (this) creating thread. We want the binder thread pool to have
// SCHED_FIFO policy and priority 1 (lowest RT priority)
// Once the pool is created we reset this thread's priority back to
// original.
intnewPriority=0;intorigPolicy=sched_getscheduler(0);structsched_paramorigSchedParam;interrorInPriorityModification=sched_getparam(0,&origSchedParam);if(errorInPriorityModification==0){intpolicy=SCHED_FIFO;newPriority=sched_get_priority_min(policy);structsched_paramparam;param.sched_priority=newPriority;errorInPriorityModification=sched_setscheduler(0,policy,¶m);}// start the thread pool
//构建ProcessState全局对象gProcess,打开binder驱动,建立链接
//在驱动内部创建该进程的binder_proc,binder_thread结构,保存该进程的进程信息和线程信息,并加入驱动的红黑树队列中。
//获取驱动的版本信息,把该进程最多可同时启动的线程告诉驱动,并保存到改进程的binder_proc结构中
//把设备文件/dev/binder映射到内存中
sp<ProcessState>ps(ProcessState::self());ps->startThreadPool();// Reset current thread's policy and priority
if(errorInPriorityModification==0){errorInPriorityModification=sched_setscheduler(0,origPolicy,&origSchedParam);}else{ALOGE("Failed to set SurfaceFlinger binder threadpool priority to SCHED_FIFO");}// instantiate surfaceflinger
// 实例化surfaceflinger
sp<SurfaceFlinger>flinger=surfaceflinger::createSurfaceFlinger();// Set the minimum policy of surfaceflinger node to be SCHED_FIFO.
// So any thread with policy/priority lower than {SCHED_FIFO, 1}, will run
// at least with SCHED_FIFO policy and priority 1.
if(errorInPriorityModification==0){flinger->setMinSchedulerPolicy(SCHED_FIFO,newPriority);}//设置优先级
setpriority(PRIO_PROCESS,0,PRIORITY_URGENT_DISPLAY);//把SF的自身调用限制在4线程
set_sched_policy(0,SP_FOREGROUND);// Put most SurfaceFlinger threads in the system-background cpuset
// Keeps us from unnecessarily using big cores
// Do this after the binder thread pool init
if(cpusets_enabled())set_cpuset_policy(0,SP_SYSTEM);// initialize before clients can connect
// 在客户端连接之前进行初始化
flinger->init();// publish surface flinger
// 将surfaceflinger放入servicemanager
sp<IServiceManager>sm(defaultServiceManager());sm->addService(String16(SurfaceFlinger::getServiceName()),flinger,false,IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL|IServiceManager::DUMP_FLAG_PROTO);// publish gui::ISurfaceComposer, the new AIDL interface
sp<SurfaceComposerAIDL>composerAIDL=newSurfaceComposerAIDL(flinger);sm->addService(String16("SurfaceFlingerAIDL"),composerAIDL,false,IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL|IServiceManager::DUMP_FLAG_PROTO);startDisplayService();// dependency on SF getting registered above
if(SurfaceFlinger::setSchedFifo(true)!=NO_ERROR){ALOGW("Couldn't set to SCHED_FIFO: %s",strerror(errno));}// run surface flinger in this thread
// 运行surfaceflinger这个线程
flinger->run();return0;}
//frameworks/native/services/surfaceflinger/Surfaceflinger.cpp
SurfaceFlinger::SurfaceFlinger(Factory&factory):SurfaceFlinger(factory,SkipInitialization){ALOGI("SurfaceFlinger is starting");hasSyncFramework=running_without_sync_framework(true);dispSyncPresentTimeOffset=present_time_offset_from_vsync_ns(0);useHwcForRgbToYuv=force_hwc_copy_for_virtual_displays(false);maxFrameBufferAcquiredBuffers=max_frame_buffer_acquired_buffers(2);maxGraphicsWidth=std::max(max_graphics_width(0),0);maxGraphicsHeight=std::max(max_graphics_height(0),0);hasWideColorDisplay=has_wide_color_display(false);mDefaultCompositionDataspace=static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));mWideColorGamutCompositionDataspace=static_cast<ui::Dataspace>(wcg_composition_dataspace(hasWideColorDisplay?Dataspace::DISPLAY_P3:Dataspace::V0_SRGB));defaultCompositionDataspace=mDefaultCompositionDataspace;wideColorGamutCompositionDataspace=mWideColorGamutCompositionDataspace;defaultCompositionPixelFormat=static_cast<ui::PixelFormat>(default_composition_pixel_format(ui::PixelFormat::RGBA_8888));wideColorGamutCompositionPixelFormat=static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));mColorSpaceAgnosticDataspace=static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));mLayerCachingEnabled=[]{constboolenable=android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);returnbase::GetBoolProperty(std::string("debug.sf.enable_layer_caching"),enable);}();useContextPriority=use_context_priority(true);mInternalDisplayPrimaries=sysprop::getDisplayNativePrimaries();// debugging stuff...
charvalue[PROPERTY_VALUE_MAX];property_get("ro.bq.gpu_to_cpu_unsupported",value,"0");mGpuToCpuSupported=!atoi(value);property_get("ro.build.type",value,"user");mIsUserBuild=strcmp(value,"user")==0;mDebugFlashDelay=base::GetUintProperty("debug.sf.showupdates"s,0u);// DDMS debugging deprecated (b/120782499)
property_get("debug.sf.ddms",value,"0");intdebugDdms=atoi(value);ALOGI_IF(debugDdms,"DDMS debugging not supported");property_get("debug.sf.enable_gl_backpressure",value,"0");mPropagateBackpressureClientComposition=atoi(value);ALOGI_IF(mPropagateBackpressureClientComposition,"Enabling backpressure propagation for Client Composition");property_get("ro.surface_flinger.supports_background_blur",value,"0");boolsupportsBlurs=atoi(value);mSupportsBlur=supportsBlurs;ALOGI_IF(!mSupportsBlur,"Disabling blur effects, they are not supported.");property_get("ro.sf.blurs_are_expensive",value,"0");mBlursAreExpensive=atoi(value);constsize_tdefaultListSize=ISurfaceComposer::MAX_LAYERS;autolistSize=property_get_int32("debug.sf.max_igbp_list_size",int32_t(defaultListSize));mMaxGraphicBufferProducerListSize=(listSize>0)?size_t(listSize):defaultListSize;mGraphicBufferProducerListSizeLogThreshold=std::max(static_cast<int>(0.95*static_cast<double>(mMaxGraphicBufferProducerListSize)),1);property_get("debug.sf.luma_sampling",value,"1");mLumaSampling=atoi(value);property_get("debug.sf.disable_client_composition_cache",value,"0");mDisableClientCompositionCache=atoi(value);property_get("debug.sf.predict_hwc_composition_strategy",value,"1");mPredictCompositionStrategy=atoi(value);property_get("debug.sf.treat_170m_as_sRGB",value,"0");mTreat170mAsSrgb=atoi(value);// We should be reading 'persist.sys.sf.color_saturation' here
// but since /data may be encrypted, we need to wait until after vold
// comes online to attempt to read the property. The property is
// instead read after the boot animation
if(base::GetBoolProperty("debug.sf.treble_testing_override"s,false)){// Without the override SurfaceFlinger cannot connect to HIDL
// services that are not listed in the manifests. Considered
// deriving the setting from the set service name, but it
// would be brittle if the name that's not 'default' is used
// for production purposes later on.
ALOGI("Enabling Treble testing override");android::hardware::details::setTrebleTestingOverride(true);}mRefreshRateOverlaySpinner=property_get_bool("sf.debug.show_refresh_rate_overlay_spinner",0);if(!mIsUserBuild&&base::GetBoolProperty("debug.sf.enable_transaction_tracing"s,true)){mTransactionTracing.emplace();}mIgnoreHdrCameraLayers=ignore_hdr_camera_layers(false);}
//frameworks/native/services/surfaceflinger/Surfaceflinger.cpp
voidSurfaceFlinger::init(){ALOGI("SurfaceFlinger's main thread ready to run. ""Initializing graphics H/W...");Mutex::Autolock_l(mStateLock);// Get a RenderEngine for the given display / config (can't fail)
// TODO(b/77156734): We need to stop casting and use HAL types when possible.
// Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
//获取给定显示/配置的 RenderEngine,并且设置一些参数
autobuilder=renderengine::RenderEngineCreationArgs::Builder().setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat)).setImageCacheSize(maxFrameBufferAcquiredBuffers).setUseColorManagerment(useColorManagement).setEnableProtectedContext(enable_protected_contents(false)).setPrecacheToneMapperShaderOnly(false).setSupportsBackgroundBlur(mSupportsBlur).setContextPriority(useContextPriority?renderengine::RenderEngine::ContextPriority::REALTIME:renderengine::RenderEngine::ContextPriority::MEDIUM);if(autotype=chooseRenderEngineTypeViaSysProp()){builder.setRenderEngineType(type.value());}mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(builder.build()));mMaxRenderTargetSize=std::min(getRenderEngine().getMaxTextureSize(),getRenderEngine().getMaxViewportDims());// Set SF main policy after initializing RenderEngine which has its own policy.
if(!SetTaskProfiles(0,{"SFMainPolicy"})){ALOGW("Failed to set main task profile");}mCompositionEngine->setTimeStats(mTimeStats);mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));mCompositionEngine->getHwComposer().setCallback(*this);ClientCache::getInstance().setRenderEngine(&getRenderEngine());enableLatchUnsignaledConfig=getLatchUnsignaledConfig();if(base::GetBoolProperty("debug.sf.enable_hwc_vds"s,false)){enableHalVirtualDisplays(true);}// Process any initial hotplug and resulting display changes.
processDisplayHotplugEventsLocked();constautodisplay=getDefaultDisplayDeviceLocked();LOG_ALWAYS_FATAL_IF(!display,"Missing primary display after registering composer callback.");constautodisplayId=display->getPhysicalId();LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(displayId),"Primary display is disconnected.");// initialize our drawing state
mDrawingState=mCurrentState;// set initial conditions (e.g. unblank default device)
initializeDisplays();mPowerAdvisor->init();charprimeShaderCache[PROPERTY_VALUE_MAX];property_get("service.sf.prime_shader_cache",primeShaderCache,"1");if(atoi(primeShaderCache)){if(setSchedFifo(false)!=NO_ERROR){ALOGW("Can't set SCHED_OTHER for primeCache");}mRenderEnginePrimeCacheFuture=getRenderEngine().primeCache();if(setSchedFifo(true)!=NO_ERROR){ALOGW("Can't set SCHED_OTHER for primeCache");}}onActiveDisplaySizeChanged(display);// Inform native graphics APIs whether the present timestamp is supported:
constboolpresentFenceReliable=!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);mStartPropertySetThread=getFactory().createStartPropertySetThread(presentFenceReliable);if(mStartPropertySetThread->Start()!=NO_ERROR){ALOGE("Run StartPropertySetThread failed!");}ALOGV("Done initializing");}
//frameworks/native/services/surfaceflinger/Surfaceflinger.cpp
voidSurfaceFlinger::processDisplayHotplugEventsLocked(){for(constauto&event:mPendingHotplugEvents){std::optional<DisplayIdentificationInfo>info=getHwComposer().onHotplug(event.hwcDisplayId,event.connection);if(!info){continue;}constautodisplayId=info->id;constautotoken=mPhysicalDisplayTokens.get(displayId);if(event.connection==hal::Connection::CONNECTED){auto[supportedModes,activeMode]=loadDisplayModes(displayId);if(!token){ALOGV("Creating display %s",to_string(displayId).c_str());DisplayDeviceStatestate;state.physical={.id=displayId,.type=getHwComposer().getDisplayConnectionType(displayId),.hwcDisplayId=event.hwcDisplayId,.deviceProductInfo=std::move(info->deviceProductInfo),.supportedModes=std::move(supportedModes),.activeMode=std::move(activeMode)};state.isSecure=true;// All physical displays are currently considered secure.
state.displayName=std::move(info->name);sp<IBinder>token=newBBinder();mCurrentState.displays.add(token,state);mPhysicalDisplayTokens.try_emplace(displayId,std::move(token));mInterceptor->saveDisplayCreation(state);}else{ALOGV("Recreating display %s",to_string(displayId).c_str());auto&state=mCurrentState.displays.editValueFor(token->get());state.sequenceId=DisplayDeviceState{}.sequenceId;// Generate new sequenceId.
state.physical->supportedModes=std::move(supportedModes);state.physical->activeMode=std::move(activeMode);if(getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()){state.physical->deviceProductInfo=std::move(info->deviceProductInfo);}}}else{ALOGV("Removing display %s",to_string(displayId).c_str());if(constssize_tindex=mCurrentState.displays.indexOfKey(token->get());index>=0){constDisplayDeviceState&state=mCurrentState.displays.valueAt(index);mInterceptor->saveDisplayDeletion(state.sequenceId);mCurrentState.displays.removeItemsAt(index);}mPhysicalDisplayTokens.erase(displayId);}processDisplayChangesLocked();}mPendingHotplugEvents.clear();}
//frameworks/native/services/surfaceflinger/Surfaceflinger.cpp
voidSurfaceFlinger::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
constKeyedVector<wp<IBinder>,DisplayDeviceState>&curr(mCurrentState.displays);constKeyedVector<wp<IBinder>,DisplayDeviceState>&draw(mDrawingState.displays);if(!curr.isIdenticalTo(draw)){mVisibleRegionsDirty=true;// find the displays that were removed
// (ie: in drawing state but not in current state)
// also handle displays that changed
// (ie: displays that are in both lists)
for(size_ti=0;i<draw.size();i++){constwp<IBinder>&displayToken=draw.keyAt(i);constssize_tj=curr.indexOfKey(displayToken);if(j<0){// in drawing state but not in current state
processDisplayRemoved(displayToken);}else{// this display is in both lists. see if something changed.
constDisplayDeviceState¤tState=curr[j];constDisplayDeviceState&drawingState=draw[i];processDisplayChanged(displayToken,currentState,drawingState);}}// find displays that were added
// (ie: in current state but not in drawing state)
for(size_ti=0;i<curr.size();i++){constwp<IBinder>&displayToken=curr.keyAt(i);if(draw.indexOfKey(displayToken)<0){processDisplayAdded(displayToken,curr[i]);}}}mDrawingState.displays=mCurrentState.displays;}
//frameworks/native/services/surfaceflinger/Surfaceflinger.cpp
voidSurfaceFlinger::processDisplayRemoved(constwp<IBinder>&displayToken){autodisplay=getDisplayDeviceLocked(displayToken);if(display){display->disconnect();if(display->isVirtual()){releaseVirtualDisplay(display->getVirtualId());}else{dispatchDisplayHotplugEvent(display->getPhysicalId(),false);}}mDisplays.erase(displayToken);if(display&&display->isVirtual()){static_cast<void>(mScheduler->schedule([display=std::move(display)]{// Destroy the display without holding the mStateLock.
// This is a temporary solution until we can manage transaction queues without
// holding the mStateLock.
// With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
// client. When the IGBP is disconnected, its buffer cache in SF will be cleared
// via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
// ends up running on the main thread causing a deadlock since setTransactionstate
// will try to acquire the mStateLock. Instead we extend the lifetime of
// DisplayDevice and destroy it in the main thread without holding the mStateLock.
// The display will be disconnected and removed from the mDisplays list so it will
// not be accessible.
}));}}
//frameworks/native/services/surfaceflinger/Surfaceflinger.cpp
voidSurfaceFlinger::processDisplayChanged(constwp<IBinder>&displayToken,constDisplayDeviceState¤tState,constDisplayDeviceState&drawingState){constsp<IBinder>currentBinder=IInterface::asBinder(currentState.surface);constsp<IBinder>drawingBinder=IInterface::asBinder(drawingState.surface);// Recreate the DisplayDevice if the surface or sequence ID changed.
if(currentBinder!=drawingBinder||currentState.sequenceId!=drawingState.sequenceId){getRenderEngine().cleanFramebufferCache();if(constautodisplay=getDisplayDeviceLocked(displayToken)){display->disconnect();if(display->isVirtual()){releaseVirtualDisplay(display->getVirtualId());}}mDisplays.erase(displayToken);if(constauto&physical=currentState.physical){getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId,physical->id);}processDisplayAdded(displayToken,currentState);if(currentState.physical){constautodisplay=getDisplayDeviceLocked(displayToken);setPowerModeInternal(display,hal::PowerMode::ON);// TODO(b/175678251) Call a listener instead.
if(currentState.physical->hwcDisplayId==getHwComposer().getPrimaryHwcDisplayId()){updateInternalDisplayVsyncLocked(display);}}return;}if(constautodisplay=getDisplayDeviceLocked(displayToken)){if(currentState.layerStack!=drawingState.layerStack){display->setLayerStack(currentState.layerStack);}if(currentState.flags!=drawingState.flags){display->setFlags(currentState.flags);}if((currentState.orientation!=drawingState.orientation)||(currentState.layerStackSpaceRect!=drawingState.layerStackSpaceRect)||(currentState.orientedDisplaySpaceRect!=drawingState.orientedDisplaySpaceRect)){display->setProjection(currentState.orientation,currentState.layerStackSpaceRect,currentState.orientedDisplaySpaceRect);if(isDisplayActiveLocked(display)){mActiveDisplayTransformHint=display->getTransformHint();}}if(currentState.width!=drawingState.width||currentState.height!=drawingState.height){display->setDisplaySize(currentState.width,currentState.height);if(isDisplayActiveLocked(display)){onActiveDisplaySizeChanged(display);}}}}
//frameworks/native/services/surfaceflinger/Surfaceflinger.cpp
voidSurfaceFlinger::processDisplayAdded(constwp<IBinder>&displayToken,constDisplayDeviceState&state){ui::Sizeresolution(0,0);ui::PixelFormatpixelFormat=static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);if(state.physical){resolution=state.physical->activeMode->getResolution();pixelFormat=static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);}elseif(state.surface!=nullptr){intstatus=state.surface->query(NATIVE_WINDOW_WIDTH,&resolution.width);ALOGE_IF(status!=NO_ERROR,"Unable to query width (%d)",status);status=state.surface->query(NATIVE_WINDOW_HEIGHT,&resolution.height);ALOGE_IF(status!=NO_ERROR,"Unable to query height (%d)",status);intformat;status=state.surface->query(NATIVE_WINDOW_FORMAT,&format);ALOGE_IF(status!=NO_ERROR,"Unable to query format (%d)",status);pixelFormat=static_cast<ui::PixelFormat>(format);}else{// Virtual displays without a surface are dormant:
// they have external state (layer stack, projection,
// etc.) but no internal state (i.e. a DisplayDevice).
return;}compositionengine::DisplayCreationArgsBuilderbuilder;if(constauto&physical=state.physical){builder.setId(physical->id);}else{builder.setId(acquireVirtualDisplay(resolution,pixelFormat));}builder.setPixels(resolution);builder.setIsSecure(state.isSecure);builder.setPowerAdvisor(mPowerAdvisor.get());builder.setName(state.displayName);autocompositionDisplay=getCompositionEngine().createDisplay(builder.build());compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);sp<compositionengine::DisplaySurface>displaySurface;sp<IGraphicBufferProducer>producer;sp<IGraphicBufferProducer>bqProducer;sp<IGraphicBufferConsumer>bqConsumer;getFactory().createBufferQueue(&bqProducer,&bqConsumer,/*consumerIsSurfaceFlinger =*/false);if(state.isVirtual()){constautodisplayId=VirtualDisplayId::tryCast(compositionDisplay->getId());LOG_FATAL_IF(!displayId);autosurface=sp<VirtualDisplaySurface>::make(getHwComposer(),*displayId,state.surface,bqProducer,bqConsumer,state.displayName);displaySurface=surface;producer=std::move(surface);}else{ALOGE_IF(state.surface!=nullptr,"adding a supported display, but rendering ""surface is provided (%p), ignoring it",state.surface.get());constautodisplayId=PhysicalDisplayId::tryCast(compositionDisplay->getId());LOG_FATAL_IF(!displayId);displaySurface=sp<FramebufferSurface>::make(getHwComposer(),*displayId,bqConsumer,state.physical->activeMode->getResolution(),ui::Size(maxGraphicsWidth,maxGraphicsHeight));producer=bqProducer;}LOG_FATAL_IF(!displaySurface);autodisplay=setupNewDisplayDeviceInternal(displayToken,std::move(compositionDisplay),state,displaySurface,producer);if(display->isPrimary()){initScheduler(display);}if(!state.isVirtual()){dispatchDisplayHotplugEvent(display->getPhysicalId(),true);}mDisplays.try_emplace(displayToken,std::move(display));}
//frameworks/native/services/surfaceflinger/Surfaceflinger.cpp
std::unique_ptr<scheduler::Scheduler>mScheduler;voidSurfaceFlinger::initScheduler(constsp<DisplayDevice>&display){if(mScheduler){// If the scheduler is already initialized, this means that we received
// a hotplug(connected) on the primary display. In that case we should
// update the scheduler with the most recent display information.
ALOGW("Scheduler already initialized, updating instead");mScheduler->setRefreshRateConfigs(display->holdRefreshRateConfigs());return;}constautocurrRefreshRate=display->getActiveMode()->getFps();mRefreshRateStats=std::make_unique<scheduler::RefreshRateStats>(*mTimeStats,currRefreshRate,hal::PowerMode::OFF);mVsyncConfiguration=getFactory().createVsyncConfiguration(currRefreshRate);mVsyncModulator=sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());usingFeature=scheduler::Feature;scheduler::FeatureFlagsfeatures;if(sysprop::use_content_detection_for_refresh_rate(false)){features|=Feature::kContentDetection;}if(base::GetBoolProperty("debug.sf.show_predicted_vsync"s,false)){features|=Feature::kTracePredictedVsync;}if(!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s,false)&&!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)){features|=Feature::kPresentFences;}// 创建Scheduler对象
mScheduler=std::make_unique<scheduler::Scheduler>(static_cast<ICompositor&>(*this),static_cast<ISchedulerCallback&>(*this),features);{autoconfigs=display->holdRefreshRateConfigs();if(configs->kernelIdleTimerController().has_value()){features|=Feature::kKernelIdleTimer;}mScheduler->createVsyncSchedule(features);mScheduler->setRefreshRateConfigs(std::move(configs));}setVsyncEnabled(false);mScheduler->startTimers();constautoconfigs=mVsyncConfiguration->getCurrentConfigs();constnsecs_tvsyncPeriod=currRefreshRate.getPeriodNsecs();mAppConnectionHandle=mScheduler->createConnection("app",mFrameTimeline->getTokenManager(),/*workDuration=*/configs.late.appWorkDuration,/*readyDuration=*/configs.late.sfWorkDuration,impl::EventThread::InterceptVSyncsCallback());mSfConnectionHandle=mScheduler->createConnection("appSf",mFrameTimeline->getTokenManager(),/*workDuration=*/std::chrono::nanoseconds(vsyncPeriod),/*readyDuration=*/configs.late.sfWorkDuration,[this](nsecs_ttimestamp){mInterceptor->saveVSyncEvent(timestamp);});mScheduler->initVsync(mScheduler->getVsyncDispatch(),*mFrameTimeline->getTokenManager(),configs.late.sfWorkDuration);mRegionSamplingThread=newRegionSamplingThread(*this,RegionSamplingThread::EnvironmentTimingTunables());mFpsReporter=newFpsReporter(*mFrameTimeline,*this);// Dispatch a mode 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.
mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle,display->getActiveMode());}
//frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp
classEventThread:publicandroid::EventThread,privateVSyncSource::Callback{EventThread::EventThread(std::unique_ptr<VSyncSource>vsyncSource,android::frametimeline::TokenManager*tokenManager,InterceptVSyncsCallbackinterceptVSyncsCallback,ThrottleVsyncCallbackthrottleVsyncCallback,GetVsyncPeriodFunctiongetVsyncPeriodFunction):mVSyncSource(std::move(vsyncSource)),mTokenManager(tokenManager),mInterceptVSyncsCallback(std::move(interceptVSyncsCallback)),mThrottleVsyncCallback(std::move(throttleVsyncCallback)),mGetVsyncPeriodFunction(std::move(getVsyncPeriodFunction)),mThreadName(mVSyncSource->getName()){LOG_ALWAYS_FATAL_IF(getVsyncPeriodFunction==nullptr,"getVsyncPeriodFunction must not be null");mVSyncSource->setCallback(this);//设置VsyncSource回调
mThread=std::thread([this]()NO_THREAD_SAFETY_ANALYSIS{std::unique_lock<std::mutex>lock(mMutex);//创建一个线程
threadMain(lock);//调用threadMain方法,接收回调消息
});pthread_setname_np(mThread.native_handle(),mThreadName);pid_ttid=pthread_gettid_np(mThread.native_handle());// Use SCHED_FIFO to minimize jitter
constexprintEVENT_THREAD_PRIORITY=2;structsched_paramparam={0};param.sched_priority=EVENT_THREAD_PRIORITY;if(pthread_setschedparam(mThread.native_handle(),SCHED_FIFO,¶m)!=0){ALOGE("Couldn't set SCHED_FIFO for EventThread");}set_sched_policy(tid,SP_FOREGROUND);}}