SurfaceFlinger 服务起点在 init.rc 中。boot Action 中最后 class_start 命令启动了分类为 core 的所有服务,这其中就包括 surfaceflinger。
system/core/rootdir/init.rc
on boot
......
class_start core
......
service surfaceflinger /system/bin/surfaceflinger
class core
user system
group graphics drmrpc
onrestart restart zygote
writepid /dev/cpuset/system-background/tasks
现在来确定 surfaceflinger 服务源码位置。在以下 Android.mk 中,我们发现起点位于 main_surfaceflinger.cpp。
frameworks/native/services/surfaceflinger/Android.mk
###############################################################
# build surfaceflinger's executable
include $(CLEAR_VARS)
LOCAL_CLANG := true
LOCAL_LDFLAGS := -Wl,--version-script,art/sigchainlib/version-script.txt -Wl,--export-dynamic
LOCAL_CFLAGS := -DLOG_TAG=\"SurfaceFlinger\"
LOCAL_CPPFLAGS := -std=c++11
LOCAL_SRC_FILES := \
main_surfaceflinger.cpp
LOCAL_SHARED_LIBRARIES := \
libsurfaceflinger \
libcutils \
liblog \
libbinder \
libutils \
libdl
LOCAL_WHOLE_STATIC_LIBRARIES := libsigchain
LOCAL_MODULE := surfaceflinger
ifdef TARGET_32_BIT_SURFACEFLINGER
LOCAL_32_BIT_ONLY := true
endif
LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
include $(BUILD_EXECUTABLE)
###############################################################
重点关注 SurfaceFlinger 实例化,以及 init() 方法,其 run() 方法在《Android 源码 图形系统之 relayoutWindow》一节中已经介绍过了。
frameworks/native/services/surfaceflinger/main_surfaceflinger.cpp
using namespace android;
int main(int, char**) {
// 在以自己的进程启动 SF 时,将绑定程序线程数限制为4。
ProcessState::self()->setThreadPoolMaxThreadCount(4);
// 启动线程池
sp<ProcessState> ps(ProcessState::self());
ps->startThreadPool();
// 实例化 SurfaceFlinger
sp<SurfaceFlinger> flinger = new SurfaceFlinger();
setpriority(PRIO_PROCESS, 0, PRIORITY_URGENT_DISPLAY);
set_sched_policy(0, SP_FOREGROUND);
// 在客户端连接之前初始化
flinger->init();
// 发布 surface flinger
sp<IServiceManager> sm(defaultServiceManager());
sm->addService(String16(SurfaceFlinger::getServiceName()), flinger, false);
// 在此线程中运行
flinger->run();
return 0;
}
SurfaceFlinger 类无参构造器中初始化了一系列参数。onFirstRef() 方法中初始化了 mEventQueue(MessageQueue)。
frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
SurfaceFlinger::SurfaceFlinger()
: BnSurfaceComposer(),
mTransactionFlags(0),
mTransactionPending(false),
mAnimTransactionPending(false),
mLayersRemoved(false),
mRepaintEverything(0),
mRenderEngine(NULL),
mBootTime(systemTime()),
mVisibleRegionsDirty(false),
mHwWorkListDirty(false),
mAnimCompositionPending(false),
mDebugRegion(0),
mDebugDDMS(0),
mDebugDisableHWC(0),
mDebugDisableTransformHint(0),
mDebugInSwapBuffers(0),
mLastSwapBufferTime(0),
mDebugInTransaction(0),
mLastTransactionTime(0),
mBootFinished(false),
mForceFullDamage(false),
mPrimaryHWVsyncEnabled(false),
mHWVsyncAvailable(false),
mDaltonize(false),
mHasColorMatrix(false),
mHasPoweredOff(false),
mFrameBuckets(),
mTotalTime(0),
mLastSwapTime(0)
{
ALOGI("SurfaceFlinger is starting");
// 调试的东西……
char value[PROPERTY_VALUE_MAX];
property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
mGpuToCpuSupported = !atoi(value);
property_get("debug.sf.drop_missed_frames", value, "0");
mDropMissedFrames = atoi(value);
property_get("debug.sf.showupdates", value, "0");
mDebugRegion = atoi(value);
property_get("debug.sf.ddms", value, "0");
mDebugDDMS = atoi(value);
if (mDebugDDMS) {
if (!startDdmConnection()) {
// 启动失败,DDMS 调试未启用
mDebugDDMS = 0;
}
}
ALOGI_IF(mDebugRegion, "showupdates enabled");
ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
}
void SurfaceFlinger::onFirstRef()
{
mEventQueue.init(this);
}
MessageQueue::init(…) 方法中初始化了 mFlinger、mLooper 和 mHandler。
frameworks/native/services/surfaceflinger/MessageQueue.cpp
void MessageQueue::init(const sp<SurfaceFlinger>& flinger)
{
mFlinger = flinger;
mLooper = new Looper(true);
mHandler = new Handler(*this);
}
SurfaceFlinger 初始化工作在代码中已经详细注释过了。
frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
void SurfaceFlinger::init() {
ALOGI( "SurfaceFlinger's main thread ready to run. "
"Initializing graphics H/W...");
Mutex::Autolock _l(mStateLock);
// 为默认显示初始化 EGL
mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(mEGLDisplay, NULL, NULL);
// 启动 EventThread
sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
vsyncPhaseOffsetNs, true, "app");
mEventThread = new EventThread(vsyncSrc);
sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
sfVsyncPhaseOffsetNs, true, "sf");
mSFEventThread = new EventThread(sfVsyncSrc);
mEventQueue.setEventThread(mSFEventThread);
// 初始化 H/W composer 对象。下面可能有也可能没有实际的硬件 composer。
mHwc = new HWComposer(this,
*static_cast<HWComposer::EventHandler *>(this));
// 为给定的显示/配置获得一个 RenderEngine 渲染引擎(不会失败)
mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
// 检索被选择/创建的 EGL 上下文
mEGLContext = mRenderEngine->getEGLContext();
LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
"couldn't create EGLContext");
// 初始化非虚拟显示
for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
// 设置已经连接的显示器
if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
// 目前,所有非虚拟显示都被认为是安全的。
bool isSecure = true;
createBuiltinDisplayLocked(type);
wp<IBinder> token = mBuiltinDisplays[i];
sp<IGraphicBufferProducer> producer;
sp<IGraphicBufferConsumer> consumer;
// 创建 BufferQueue
BufferQueue::createBufferQueue(&producer, &consumer,
new GraphicBufferAlloc());
sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
consumer);
int32_t hwcId = allocateHwcDisplayId(type);
sp<DisplayDevice> hw = new DisplayDevice(this,
type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
fbs, producer,
mRenderEngine->getEGLConfig());
if (i > DisplayDevice::DISPLAY_PRIMARY) {
// FIXME: currently we don't get blank/unblank requests
// for displays other than the main display, so we always
// assume a connected display is unblanked.
ALOGD("marking display %zu as acquired/unblanked", i);
hw->setPowerMode(HWC_POWER_MODE_NORMAL);
}
mDisplays.add(token, hw);
}
}
// 使 GLContext 为最新,以便我们在创建图层时可以创建纹理(这可能在渲染某些东西之前发生)
getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
mEventControlThread = new EventControlThread(this);
mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
// 如果没有 HWComposer,设置一个假的垂直同步周期
if (mHwc->initCheck() != NO_ERROR) {
mPrimaryDispSync.setPeriod(16666667);
}
// 初始化我们的绘制状态
mDrawingState = mCurrentState;
// 设置初始条件(如取消默认设备)
initializeDisplays();
// 开始启动动画
startBootAnim();
}