[Android禅修之路] Android图形系统,从Activity到Surface

语言: CN / TW / HK

theme: channing-cyan

Android图形系统,从Activity到Surface

Android禅修之路

1 从Activity到Surface

首先,我们最初见到应用程序,都是Activity界面,那么Activity界面是如何显示的呢,首先Activity的显示是通过我们调用setContentView函数触发的,这个函数会解析View的xml文件,创建View,然后每一个View树都会有一个根View,它就是ViewRootImpl

虽然这个类名是ViewRootImpl,但是它并不是一个真正的View,它更多的是管理View的显示刷新等逻辑,当我们界面需要刷新的时候,会调用ViewRootImpl的performTraversals函数,这个函数就会触发对应的刷新逻辑(刷新相关的逻辑不是本篇的重点,这里先略过,后续讲刷新的时候再详细说明)。

然后在performTraversals函数中,会调用一个很重要的函数relayoutWindow,这个函数中就会创建Surface

1.1 Surface的创建过程

首先看一下应用中Surface的创建过程

```java [frameworks/base/core/java/android/view/ViewRootImpl.java] public final class ViewRootImpl implements ViewParent, View.AttachInfo.Callbacks, ThreadedRenderer.DrawCallbacks { // 1 调用无参的构造方法创建Surface和SurfaceControl public final Surface mSurface = new Surface(); private final SurfaceControl mSurfaceControl = new SurfaceControl();

private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
        boolean insetsPending) throws RemoteException {
    // 2 通过mWindowSession的relayout处理SurfaceControl
    int relayoutResult = mWindowSession.relayout(mWindow, mSeq, params,
            (int) (mView.getMeasuredWidth() * appScale + 0.5f),
            (int) (mView.getMeasuredHeight() * appScale + 0.5f), viewVisibility,
            insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, frameNumber,
            mTmpFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
            mPendingStableInsets, mPendingOutsets, mPendingBackDropFrame, mPendingDisplayCutout,
            mPendingMergedConfiguration, mSurfaceControl, mTempInsets);
    if (mSurfaceControl.isValid()) {
        // 3 调用Surface的copyFrom,参数是SurfaceControl
        mSurface.copyFrom(mSurfaceControl);
    } else {
        destroySurface();
    }   
}

} ```

Java层的Surface是在ViewRootImpl中创建的,创建的具体步骤如下

  1. 首先调用Surface的空参数构造函数,创建出一个Surface对象
  2. 然后调用SurfaceControl的空参数构造函数,创建出一个SurfaceControl的壳对象
  3. 调用mWindowSession的relayout填充这个SurfaceControl壳对象
  4. 调用Surface的copyFrom

1.2 Surface.java的定义

Surface中定义了一个native函数,它的真正实现是在native层

```java [frameworks/base/core/java/android/view/Surface.java] public class Surface implements Parcelable { long mNativeObject;

private static native long nativeGetFromSurfaceControl(long surfaceObject,
        long surfaceControlNativeObject);

public void copyFrom(SurfaceControl other) {
    ...
    long surfaceControlPtr = other.mNativeObject;

    long newNativeObject = nativeGetFromSurfaceControl(mNativeObject, surfaceControlPtr);

    synchronized (mLock) {
        if (newNativeObject == mNativeObject) {
            return;
        }
        if (mNativeObject != 0) {
            nativeRelease(mNativeObject);
        }
        setNativeObjectLocked(newNativeObject);
    }
}

} ```

1.3 SurfaceControl.java的定义

Java层和Surface配对的还有一个SurfaceControl,它有几个构造函数,如下

```java [frameworks/base/core/java/android/view/SurfaceControl.java] public final class SurfaceControl implements Parcelable {
// 这个构造函数是空构造函数,默认调用的是这个 public SurfaceControl() { mCloseGuard.open("release"); }

public SurfaceControl(SurfaceControl other) {
    mName = other.mName;
    mWidth = other.mWidth;
    mHeight = other.mHeight;
    mNativeObject = other.mNativeObject;
    other.mCloseGuard.close();
    other.mNativeObject = 0;
    mCloseGuard.open("release");
}

// 这个构造函数是真正工作的构造函数,它会调用native层的nativeCreate
private SurfaceControl(SurfaceSession session, String name, int w, int h, int format, int flags,
    SurfaceControl parent, SparseIntArray metadata)
            throws OutOfResourcesException, IllegalArgumentException {
    if (name == null) {
        throw new IllegalArgumentException("name must not be null");
    }

    if ((flags & SurfaceControl.HIDDEN) == 0) {
        Log.w(TAG, "Surfaces should always be created with the HIDDEN flag set "
                + "to ensure that they are not made visible prematurely before "
                + "all of the surface's properties have been configured.  "
                + "Set the other properties and make the surface visible within "
                + "a transaction.  New surface name: " + name,
                new Throwable());
    }

    mName = name;
    mWidth = w;
    mHeight = h;
    Parcel metaParcel = Parcel.obtain();
    try {
        if (metadata != null && metadata.size() > 0) {
            metaParcel.writeInt(metadata.size());
            for (int i = 0; i < metadata.size(); ++i) {
                metaParcel.writeInt(metadata.keyAt(i));
                metaParcel.writeByteArray(
                        ByteBuffer.allocate(4).order(ByteOrder.nativeOrder())
                                .putInt(metadata.valueAt(i)).array());
            }
            metaParcel.setDataPosition(0);
        }
        mNativeObject = nativeCreate(session, name, w, h, format, flags,
                parent != null ? parent.mNativeObject : 0, metaParcel);
    } finally {
        metaParcel.recycle();
    }
    if (mNativeObject == 0) {
        throw new OutOfResourcesException(
                "Couldn't allocate SurfaceControl native object");
    }

    mCloseGuard.open("release");
}

...

} ```

2 SurfaceControl 的创建过程

SurfaceControl的创建分为两步

  1. 创建一个空的SurfaceControl的Java对象
  2. 调用relayoutWindow将这个空壳传递进去

SurfaceControl创建的真正逻辑就在第二步的relayoutWindow中

2.1ViewRootImpl.relayoutWindow

```java [frameworks/base/core/java/android/view/ViewRootImpl.java] public final Surface mSurface = new Surface(); // 1 private final SurfaceControl mSurfaceControl = new SurfaceControl();

public ViewRootImpl(Context context, Display display) { mContext = context; // mWindowSession其实是WindowManagerService在app进程中的一个会话对象 // 这个Session是frameworks/base/services/core/java/com/android/server/wm/Session.java // 它在每个进程中都存在一个 mWindowSession = WindowManagerGlobal.getWindowSession(); }

private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility, boolean insetsPending) throws RemoteException { // 2 调用Session的relayout函数,这个函数会调用WMS的relayoutWindow函数 int relayoutResult = mWindowSession.relayout(..., mSurfaceControl, mTempInsets); if (mSurfaceControl.isValid()) { // 3 调用Surface的copyFrom,这个函数会对Surface进行填充 mSurface.copyFrom(mSurfaceControl); } else { destroySurface(); } ```

2.2 Session的relayout

java [frameworks/base/services/core/java/com/android/server/wm/Session.java] public int relayout(...,SurfaceControl outBLASTSurfaceControl) { // 这个函数就是调用WMS的relayoutWindow int res = mService.relayoutWindow(this, window, seq, attrs, requestedWidth, requestedHeight, viewFlags, flags, frameNumber, outFrame, outContentInsets, outVisibleInsets, outStableInsets, outBackdropFrame, cutout, mergedConfiguration, outSurfaceControl, outInsetsState, outActiveControls, outSurfaceSize, outBLASTSurfaceControl); return res; }

2.3 WindowManagerService.java

SurfaceControl在创建时调用的是一个空参数的构造函数,它实际上是一个空壳对象,真正的填充是通过WMS的createSurfaceControl函数中进行的

```java [frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java] public int relayoutWindow(..., SurfaceControl outSurfaceControl, InsetsState outInsetsState) { try { result = createSurfaceControl(outSurfaceControl, result, win, winAnimator); } catch (Exception e) { } }

private int createSurfaceControl(SurfaceControl outSurfaceControl, int result, WindowState win, WindowStateAnimator winAnimator) {

WindowSurfaceController surfaceController;
try {
    // 1 调用winAnimator创建WindowSurfaceController对象,这个WindowSurfaceController
    // 对象其实内部包含SurfaceController
    // 这个winAnimator其实是WindowStateAnimator.java对象
    surfaceController = winAnimator.createSurfaceLocked(win.mAttrs.type, win.mOwnerUid);
}
if (surfaceController != null) {
    // 2 将 WindowSurfaceController 拷贝到SurfaceControl对象中,见 [3.2]
    // 调用 WindowSurfaceController 的 getSurfaceControl
    surfaceController.getSurfaceControl(outSurfaceControl);
} else {
    outSurfaceControl.release();
}

return result;

} ```

2.4 WindowStateAnimator.java

```java [frameworks/base/services/core/java/com/android/server/wm/WindowStateAnimator.java] WindowSurfaceController createSurfaceLocked(int windowType, int ownerUid) { ... try { ... // 创建WindowSurfaceController对象 mSurfaceController = new WindowSurfaceController(attrs.getTitle().toString(), width, height, format, flags, this, windowType, ownerUid); mSurfaceController.setColorSpaceAgnostic((attrs.privateFlags & WindowManager.LayoutParams.PRIVATE_FLAG_COLOR_SPACE_AGNOSTIC) != 0); setOffsetPositionForStackResize(false); mSurfaceFormat = format; w.setHasSurface(true); } ...

mLastHidden = true;
return mSurfaceController;

} ```

2.5 WindowSurfaceController.java

java [frameworks/base/services/core/java/com/android/server/wm/WindowSurfaceController.java] WindowSurfaceController(String name, int w, int h, int format, int flags, WindowStateAnimator animator, int windowType, int ownerUid) { ... final SurfaceControl.Builder b = win.makeSurface() .setParent(win.getSurfaceControl()) .setName(name) .setBufferSize(w, h) .setFormat(format) .setFlags(flags) .setMetadata(METADATA_WINDOW_TYPE, windowType) .setMetadata(METADATA_OWNER_UID, ownerUid); mSurfaceControl = b.build(); ... }

所以前面一连串的调用,最后其实就是调用到了 Java 层的 SurfaceControl 的构造函数,而 Java 层的 SurfaceControl 的构造函数,会调用到 native 层的构造函数。

2.6 SurfaceControl.build

java [frameworks/base/core/java/android/view/SurfaceControl.java] public SurfaceControl build() { if (mWidth < 0 || mHeight < 0) { throw new IllegalStateException( "width and height must be positive or unset"); } if ((mWidth > 0 || mHeight > 0) && (isColorLayerSet() || isContainerLayerSet())) { throw new IllegalStateException( "Only buffer layers can set a valid buffer size."); } //这里调用的构造函数就是真正工作的构造函数 return new SurfaceControl( mSession, mName, mWidth, mHeight, mFormat, mFlags, mParent, mMetadata); }

2.7 SurfaceControl的构造函数

```java [frameworks/base/core/java/android/view/SurfaceControl.java] private SurfaceControl(SurfaceSession session, String name, int w, int h, int format, int flags, SurfaceControl parent, SparseIntArray metadata, WeakReference localOwnerView, String callsite) throws OutOfResourcesException, IllegalArgumentException { ... try { if (metadata != null && metadata.size() > 0) { metaParcel.writeInt(metadata.size()); for (int i = 0; i < metadata.size(); ++i) { metaParcel.writeInt(metadata.keyAt(i)); metaParcel.writeByteArray( ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()) .putInt(metadata.valueAt(i)).array()); } metaParcel.setDataPosition(0); }

// 调用 native 层的构造函数 nativeCreate,拿到的 mNativeObject
// 是一个 SurfaceControl 的指针地址
    mNativeObject = nativeCreate(session, name, w, h, format, flags,
            parent != null ? parent.mNativeObject : 0, metaParcel);
} finally {
    metaParcel.recycle();
}
if (mNativeObject == 0) {
    throw new OutOfResourcesException(
            "Couldn't allocate SurfaceControl native object");
}

// 通过 SurfaceControl 指针地址,拿到对应的 SurfaceControl 的 IBinder 对象
mNativeHandle = nativeGetHandle(mNativeObject);
mCloseGuard.openWithCallSite("release", callsite);

} ```

到此,SurfaceControl 的构造函数最后拿到了一个 Java 层的 IBinder 对象。

2.8 getSurfaceControl

这里又调用了一个copyFrom,不过传入的参数是mSurfaceControl,这个mSurfaceControl是哪里来的呢,原来它就是WindowSurfaceController初始化build时的SurfaceControl (见2.5)。

```java [frameworks/base/services/core/java/com/android/server/wm/WindowSurfaceController.java] void getSurfaceControl(SurfaceControl outSurfaceControl) { outSurfaceControl.copyFrom(mSurfaceControl); }

[frameworks/base/core/java/android/view/SurfaceControl.java] public void copyFrom(SurfaceControl other) { mName = other.mName; mWidth = other.mWidth; mHeight = other.mHeight; assignNativeObject(nativeCopyFromSurfaceControl(other.mNativeObject)); } ```

3 native层的构造函数

3.1 nativeCreate

从 [2.7] 中的构造函数,我们可以看到会调用到 native。然后在 native 中,会创建一个 SurfaceComposerClient。

```cpp static jlong nativeCreate(JNIEnv* env, jclass clazz, jobject sessionObj, jstring nameStr, jint w, jint h, jint format, jint flags, jlong parentObject, jobject metadataParcel) { ScopedUtfChars name(env, nameStr); sp client;

// sessionObj 是从 Java 层传递下来的,单进程唯一,见 [2.1]
// 如果有 sessionObj 就从 sessionObj 中取,如果没有,
// 就取 SurfaceComposerClient 默认的
if (sessionObj != NULL) {
    client = android_view_SurfaceSession_getClient(env, sessionObj);
} else {
    client = SurfaceComposerClient::getDefault();
}

// 将 Java 层传递过来的指针地址,还原成 SurfaceControl 指针
SurfaceControl *parent = reinterpret_cast<SurfaceControl*>(parentObject);
sp<SurfaceControl> surface;
LayerMetadata metadata;
...

// 调用 SurfaceComposerClient 的 createSurfaceChecked。见小节[4]
status_t err = client->createSurfaceChecked(
        String8(name.c_str()), w, h, format, &surface, flags, parent, std::move(metadata));
if (err == NAME_NOT_FOUND) {
    jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
    return 0;
} else if (err != NO_ERROR) {
    jniThrowException(env, OutOfResourcesException, NULL);
    return 0;
}

surface->incStrong((void *)nativeCreate);
return reinterpret_cast<jlong>(surface.get());

} ```

3.2 WindowSurfaceController.getSurfaceControl

获取 SurfaceControl,在[2.3]中最后会调用到此处。而它其实调用的是 SurfaceControl 的 copyFrom。也就是将原本的 mSurfaceControl 拷贝到传入的 outSurfaceControl。

cpp void getSurfaceControl(SurfaceControl outSurfaceControl) { outSurfaceControl.copyFrom(mSurfaceControl, "WindowSurfaceController.getSurfaceControl"); }

3.3 SurfaceControl.copyFrom

到这里,SurfaceControl 的创建算是结束了。

cpp public void copyFrom(@NonNull SurfaceControl other, String callsite) { mName = other.mName; mWidth = other.mWidth; mHeight = other.mHeight; mLocalOwnerView = other.mLocalOwnerView; assignNativeObject(nativeCopyFromSurfaceControl(other.mNativeObject), callsite); }

3.4 nativeCopyFromSurfaceControl

```cpp static jlong nativeCopyFromSurfaceControl(JNIEnv* env, jclass clazz, jlong surfaceControlNativeObj) { sp surface(reinterpret_cast(surfaceControlNativeObj)); if (surface == nullptr) { return 0; }

sp<SurfaceControl> newSurface = new SurfaceControl(surface);
newSurface->incStrong((void *)nativeCreate);
return reinterpret_cast<jlong>(newSurface.get());

} ```

3.5 Surface.copyFrom

接下来,我们回到 [1.1] 再来看看 Surface 的 copyFrom。同样,是通过 native 实现的,具体的实现方式我们应该已经可以猜出来,和 SurfaceControl 类似了。

java [frameworks/base/core/java/android/view/Surface.java] public void copyFrom(SurfaceControl other) { ... //调用native层的实现函数 long newNativeObject = nativeGetFromSurfaceControl(mNativeObject, surfaceControlPtr); ... }

3.6 nativeGetFromSurfaceControl

```cpp [frameworks/base/core/jni/android_view_Surface.cpp] static jlong nativeGetFromSurfaceControl(JNIEnv env, jclass clazz, jlong nativeObject, jlong surfaceControlNativeObj) { // 从java层传入的两个参数,分别保存着native层Surface,SurfaceControl的指针 Surface self(reinterpret_cast(nativeObject)); sp ctrl(reinterpret_cast(surfaceControlNativeObj));

// 如果这两个指针对象的GBP相同,就什么也不做
if (self != nullptr &&
        IInterface::asBinder(self->getIGraphicBufferProducer()) ==
        IInterface::asBinder(ctrl->getIGraphicBufferProducer())) {
    return nativeObject;
}

// 否则就创建一个native层的surface,调用SurfaceControl.getSurface
sp<Surface> surface(ctrl->getSurface());
if (surface != NULL) {
    surface->incStrong(&sRefBaseOwner);
}

return reinterpret_cast<jlong>(surface.get());

} ```

3.7 SurfaceControl的getSurface

```cpp [frameworks/native/libs/gui/SurfaceControl.cpp] sp SurfaceControl::getSurface() const { Mutex::Autolock _l(mLock); if (mSurfaceData == nullptr) { // 真正的创建对象的函数 return generateSurfaceLocked(); } return mSurfaceData; }

sp SurfaceControl::generateSurfaceLocked() const { // 创建了一个Surface对象,调用了构造函数,传入了一个mGraphicBufferProducer mSurfaceData = new Surface(mGraphicBufferProducer, false); return mSurfaceData; } ```

最后,调用到了Surface的构造函数。

cpp [frameworks/native/libs/gui/Surface.cpp] Surface::Surface(const sp<IGraphicBufferProducer>& bufferProducer, bool controlledByApp) : mGraphicBufferProducer(bufferProducer), ...

到这里,Surface的创建过程算是初步完成了,这里面出现了一个很重要的对象mGraphicBufferProducer,它是通过SurfaceControl调用Surface构造函数传递进去的。具体 GraphicBufferProducer 的介绍可以看 解读SurfaceFlinger中的BufferQueue

4 SurfaceComposerClient

接下来,我们再来说说[3.1]的最后一部分,SurfaceComposerClient 的 createSurfaceChecked。

4.1 SurfaceComposerClient

前面聊到了在SurfaceComposerClient。现在我们就 SurfaceComposerClient 详细聊一聊它在图形系统中的作用。

首先,由于系统中有多个应用程序,而只有一个 SurfaceFlinger 通信,为了能够区分 SurfaceFlinger 中的应用程序,所以有了 SurfaceComposerClient。

首先看到 Client 后缀,我们下意思的想到就是 C/S 模型,关于 SurfaceComposerClient,它在图形系统中的继承关系如下。

SurfaceComposerClient和SF.png

ISurfaceComposer 是服务端 (SurfaceFlinger后面简称SF) 的接口,它的实现类分别有 * BpSurfaceComposer:它是代理类,用于客户端 App 向服务端SF 通信。 * BnSurfaceComposer:它是实现类,真正的实现者就是 SF。

ISurfaceComposerClient 是代表客户端在 SF 中的代理,它的实现类分别有 * BpSurfaceComposerClient:它是代理类,用于客户端 App 向服务端的 Client 通信。 * BnSurfaceComposerClient:它是是实现类,真正的实现者就是 Client。

每一个客户的 App 都会在 SF 中对应存在一个 Client,而每一个 Client 都会包含一个 mFlinger 对象,用来和 SF 通信。App 会先拿到 SF 的代理对象 BpSurfaceComposer,然后通过它与 SF 建立连接拿到代理类 BpSurfaceComposerClient。

最终通过 BpSurfaceComposerClient -> Client -> SF 的方式进行通信。

如图所示,就是所有 Client 提供的 api,通过这些 api,我们就可以在 App 端调用到 SF 中。

Client和SF通信.png

所以上图在多 App 时可以简化为

SurfaceComposerClient多App.png

```cpp [frameworks/native/libs/gui/ISurfaceComposer.cpp] class BpSurfaceComposer : public BpInterface

[frameworks/native/libs/gui/include/gui/ISurfaceComposer.h] class BnSurfaceComposer: public BnInterface { ```

ISurfaceComposerClient 代表的是 App,ISurfaceComposer 代表的是 SF。 接下来我们会关注两点 1. 它们是如何创建的 2. 它们是如何建立连接的

接下来看一下这个mClient是如何创建的。

在[3.1]中,SurfaceComposerClient 的创建方式有两种,它们分别是 * SurfaceComposerClient::getDefault() * android_view_SurfaceSession_getClient()

4.2 SurfaceComposerClient::getDefault()

getDefault 创建的方式很简单,就是一个单例。

cpp sp<SurfaceComposerClient> SurfaceComposerClient::getDefault() { // 这里其实就是通过一个单例来创建 SurfaceComposerClient return DefaultComposerClient::getComposerClient(); }

4.3 onFirstRef

然后,Android 的 framework 层,涉及到 Binder 通信时一般都会继承 RefBase,这时我们就要注意 onFirstRef 这个函数。

由于它是 Binder 通信,所以一定会有一个建立连接的过程,而这里的 onFirstRef 做的就是建立连接。

```cpp [frameworks/native/libs/gui/SurfaceComposerClient.cpp] void SurfaceComposerClient::onFirstRef() {

//1. 通过 ComposerService 拿到了一个 ISurfaceComposer
sp<ISurfaceComposer> sf(ComposerService::getComposerService());
if (sf != nullptr && mStatus == NO_INIT) {
    sp<ISurfaceComposerClient> conn;
    // 调用 ISurfaceComposer 的 createConnection
    conn = sf->createConnection();
    if (conn != nullptr) {
        // 对 mClient 进行赋值
        mClient = conn;
        mStatus = NO_ERROR;
    }
}

} ```

ComposerService 它是一个单例,这里通过 getComposerService 拿到一个 sp\<ISurfaceComposer> 对象。这是一个 ISurfaceComposer 的强智能指针。

前面我们已经介绍了 ISurfaceComposer,它是 SF 的借口,在 App 端会有它的代理对象。

4.4 ComposerService 的构造函数

我们先看它的构造函数,它里面只调用了 connectLocked。 cpp [frameworks/native/libs/gui/SurfaceComposerClient.cpp] ComposerService::ComposerService() : Singleton<ComposerService>() { Mutex::Autolock _l(mLock); connectLocked(); }

4.5 ComposerService::connectLocked

```cpp void ComposerService::connectLocked() { const String16 name("SurfaceFlinger");

// getService 是 ServiceManager 的函数
// 定义在 [frameworks/native/cmds/servicemanager/ServiceManager.cpp]
// 它其实就是获取 SurfaceFlinger 的 Binder 对象

// 通过Binder获取SurfaceFlinger的Binder对象
while (getService(name, &mComposerService) != NO_ERROR) {
    usleep(250000);
}

// Create the death listener.
...

// 下面是很常见的 Binder 连接的代码
mDeathObserver = new DeathObserver(*const_cast<ComposerService*>(this));
IInterface::asBinder(mComposerService)->linkToDeath(mDeathObserver);

} ```

4.6 SurfaceFlinger::createConnection

再回到 [1.2],当通过 ServiceManager 拿到 SF 的Binder 对象之后,就通过 Binder 对象和 SF 建立连接。

接下来看createConnection返回的具体对象

```cpp [frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp] sp SurfaceFlinger::createConnection() { return initClient(new Client(this)); }

static sp initClient(const sp& client) { status_t err = client->initCheck(); if (err == NO_ERROR) { return client; } return nullptr; } ```

createConnection函数也很简单,就是返回了一个Client对象,这个Client的定义如下

c [frameworks/native/services/surfaceflinger/Client.h] class Client : public BnSurfaceComposerClient

还记得我们一开始说的那4个对象吗,这个 BnSurfaceComposerClient ,其实就是 App 端对应的 ISurfaceComposerClient 的实现类。

所以,在 SurfaceComposerClient 的 onFirstRef 中创建的 mClient 对象,其实就是系统进程中的 BnSurfaceComposerClient。而它的实现类,就是 Client。

4.7 SurfaceComposerClient.createSurface

接下来再看 mClient->createSurface,它其实就是调用的 Client 的 createSurface。

cpp [frameworks/native/services/surfaceflinger/Client.cpp] status_t Client::createSurface(const String8& name, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags, const sp<IBinder>& parentHandle, LayerMetadata metadata, sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp) { // 这个mFlinger就是SurfaceFlinger return mFlinger->createLayer(name, this, w, h, format, flags, std::move(metadata), handle, gbp, parentHandle); }

createLayer其实就是创建Layer,在SurfaceFlinger中有许多种Layer,这里我们来看其中的一种比较常见的eFXSurfaceBufferQueue

cpp [frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp] status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags, LayerMetadata metadata, sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer) { ... switch (flags & ISurfaceComposerClient::eFXSurfaceMask) { case ISurfaceComposerClient::eFXSurfaceBufferQueue: result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata), format, handle, gbp, &layer); ... }

它调用了createBufferQueueLayer,在这个里面对gbp进行了初始化

```cpp [frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp] status_t SurfaceFlinger::createBufferQueueLayer(const sp& client, const String8& name, uint32_t w, uint32_t h, uint32_t flags, LayerMetadata metadata, PixelFormat& format, sp handle, sp gbp, sp* outLayer) { ...

sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
        LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
status_t err = layer->setDefaultBufferProperties(w, h, format);
if (err == NO_ERROR) {
    // 初始化gbp
    *handle = layer->getHandle();
    *gbp = layer->getProducer();
    *outLayer = layer;
}

return err;

} ```

到这里,我们终于理清了从 Activity 到 Surface 的逻辑,并且看到了 Layer 的创建。大致细节有: * SurfaceControl 的创建和 Surface 的创建 * SurfaceControl 中 SurfaceComposerClient 的创建 * SurfaceComposerClient 的 C/S 模型 * SurfaceComposerClient 中 App 端和 SF 端的通信 * SurfaceComposerClient 通过 Binder 通信的方式,调用 SF 创建 Layer