Android6.0 显示系统(一) Surface创建

之前在分析Activity的时候,我们分析过Surface创建。这个系列的博客是讲述显示系统,这里再系统的分析下Surface创建过程。

之前我们分析在Activity在调用attach方法时,建立ViewRootImpl,以及创建其Surface过程,还有在WMS中创建Surface的过程。

这篇博客我们通过另外一个方式分析,但是其实质是一样的。


一、应用层创建Surface

应用开发中很少直接使用Surface,因为每个Activity中已经创建好了各自的Surface对象(就是之前博客分析的在ViewRootImpl通过WMS创建的),通常只有一些特殊应用才需要在Activity之外创建Surface,例如照相机、视频播放应用。通常这些应用也是通过创建SurfaceView来使用Surface。在应用中不直接创建一个可用的Surface对象,或者说直接创建出来的Surface对象也没用,因为这样的Surface不能和SurfaceFlinger之间有关联。

下面我们就来看下SurfaceView是如何创建Surface的,在SurfaceView有两个Surface一个mSurface表示正在用的,另一个mNewSurface代表我们要切换的。

[cpp]  view plain  copy
  1. final Surface mSurface = new Surface();       // Current surface in use  
  2. final Surface mNewSurface = new Surface();    // New surface we are switching to  

至于Surface的构造函数没什么代码,我们就不看了。

我们再来看SurfaceView的updateWindow函数,也是调用了WindowSession的relayout函数,和之前Activity创建Surface的流程一样,这里获取到mNewSurface,再把mNewSurface的数据复制到mSurface中。

[cpp]  view plain  copy
  1. protected void updateWindow(boolean force, boolean redrawNeeded) {  
  2.     ......  
  3.     relayoutResult = mSession.relayout(mWindow, mWindow.mSeq, mLayout, mWidth, mHeight,  
  4.     visible ? VISIBLE : GONE,  
  5.     WindowManagerGlobal.RELAYOUT_DEFER_SURFACE_DESTROY,  
  6.     mWinFrame, mOverscanInsets, mContentInsets,  
  7.     mVisibleInsets, mStableInsets, mOutsets, mConfiguration,  
  8.     mNewSurface);  
  9.     ......  
  10.     mSurface.transferFrom(mNewSurface);  
  11.     ......  
  12. }  

mSession对象是IWindowSession,它是WMS中Session的代理对象。下面这是IWindowSession.aidl文件中relayout函数的定义,我们可以看到outSurface的参数前面有一个out代表这是一个返回参数,从WMS获取这个对象的。而返回数据都是通过Parcel来传递的。那下面我们来看看Surface的readFromParcel函数。

[cpp]  view plain  copy
  1. int relayout(IWindow window, int seq, in WindowManager.LayoutParams attrs,  
  2.         int requestedWidth, int requestedHeight, int viewVisibility,  
  3.         int flags, out Rect outFrame, out Rect outOverscanInsets,  
  4.         out Rect outContentInsets, out Rect outVisibleInsets, out Rect outStableInsets,  
  5.         out Rect outOutsets, out Configuration outConfig, out Surface outSurface);  

我们来看下Surface的readFromParcel函数,前面是参数检查,后面先是调用了nativeReadFromParcel函数来重新创建一个native层的Surface,然后调用setNativeObjectLocked来保存这个native层的Surface到mNativeObject对象

[cpp]  view plain  copy
  1. public void readFromParcel(Parcel source) {  
  2.     if (source == null) {  
  3.         throw new IllegalArgumentException("source must not be null");  
  4.     }  
  5.   
  6.     synchronized (mLock) {  
  7.         // nativeReadFromParcel() will either return mNativeObject, or  
  8.         // create a new native Surface and return it after reducing  
  9.         // the reference count on mNativeObject.  Either way, it is  
  10.         // not necessary to call nativeRelease() here.  
  11.         mName = source.readString();  
  12.         setNativeObjectLocked(nativeReadFromParcel(mNativeObject, source));  
  13.     }  
  14. }  

我们来看JNI层的nativeReadFromParcel函数,这个函数在android_view_Surface.cpp中,会将Parcel对象中读取一个Binder对象,并且用它创建一个c层的Surface,并且返回。这里我们还不清楚这个Binder是什么。

[cpp]  view plain  copy
  1. static jlong nativeReadFromParcel(JNIEnv* env, jclass clazz,  
  2.         jlong nativeObject, jobject parcelObj) {  
  3.     Parcel* parcel = parcelForJavaObject(env, parcelObj);//将数据解析成parcel  
  4.     if (parcel == NULL) {  
  5.         doThrowNPE(env);  
  6.         return 0;  
  7.     }  
  8.   
  9.     sp<Surface> self(reinterpret_cast<Surface *>(nativeObject));  
  10.     sp<IBinder> binder(parcel->readStrongBinder());  
  11.   
  12.     // update the Surface only if the underlying IGraphicBufferProducer  
  13.     // has changed.  
  14.     if (self != NULL //和原来的相同  
  15.             && (IInterface::asBinder(self->getIGraphicBufferProducer()) == binder)) {  
  16.         // same IGraphicBufferProducer, return ourselves  
  17.         return jlong(self.get());  
  18.     }  
  19.   
  20.     sp<Surface> sur;  
  21.     sp<IGraphicBufferProducer> gbp(interface_cast<IGraphicBufferProducer>(binder));  
  22.     if (gbp != NULL) {  
  23.         // we have a new IGraphicBufferProducer, create a new Surface for it  
  24.         sur = new Surface(gbp, true);//创建一个Surface  
  25.         // and keep a reference before passing to java  
  26.         sur->incStrong(&sRefBaseOwner);  
  27.     }  
  28.   
  29.     if (self != NULL) {  
  30.         // and loose the java reference to ourselves  
  31.         self->decStrong(&sRefBaseOwner);  
  32.     }  
  33.   
  34.     return jlong(sur.get());  
  35. }  

我们来看Surface,我们把binder对象保存在mGraphicBufferProducer中了。

[cpp]  view plain  copy
  1. Surface::Surface(  
  2.         const sp<IGraphicBufferProducer>& bufferProducer,  
  3.         bool controlledByApp)  
  4.     : mGraphicBufferProducer(bufferProducer),  
  5.       mGenerationNumber(0)  



二、WMS中Surface的创建过程

用户进程中调用Session类的relayout接口来获取WMS创建的Surface。而Session类的relayout接口实际上后面调用了WMS的relayout的relayoutWindow方法。

我们来看下WMS的relayoutWindow函数,显示调用了winAnimator的createSurfaceLocked方法得到一个SurfaceControl对象,并使用它作为参数调整Surface类的copyFrom方法。

[cpp]  view plain  copy
  1. public int relayoutWindow(Session session, IWindow client, int seq,  
  2.         WindowManager.LayoutParams attrs, int requestedWidth,  
  3.         int requestedHeight, int viewVisibility, int flags,  
  4.         Rect outFrame, Rect outOverscanInsets, Rect outContentInsets,  
  5.         Rect outVisibleInsets, Rect outStableInsets, Rect outOutsets, Configuration outConfig,  
  6.         Surface outSurface) {  
  7.         ......  
  8.         SurfaceControl surfaceControl = winAnimator.createSurfaceLocked();  
  9.                 if (surfaceControl != null) {  
  10.                     outSurface.copyFrom(surfaceControl);  
  11.                 }  
  12.         ......  

我们先来看Surface的copyFrom方法,这个方法其实很简单只是把SurfaceControl的native层的SurfaceControl的Surface复制到Surface的mNativeObject

[cpp]  view plain  copy
  1. public void copyFrom(SurfaceControl other) {  
  2.     if (other == null) {  
  3.         throw new IllegalArgumentException("other must not be null");  
  4.     }  
  5.   
  6.     long surfaceControlPtr = other.mNativeObject;  
  7.     if (surfaceControlPtr == 0) {  
  8.         throw new NullPointerException(  
  9.                 "SurfaceControl native object is null. Are you using a released SurfaceControl?");  
  10.     }  
  11.     long newNativeObject = nativeCreateFromSurfaceControl(surfaceControlPtr);  
  12.   
  13.     synchronized (mLock) {  
  14.         if (mNativeObject != 0) {  
  15.             nativeRelease(mNativeObject);  
  16.         }  
  17.         setNativeObjectLocked(newNativeObject);  
  18.     }  
  19. }  

nativeCreateFromSurfaceControl方法是把native层的SurfaceControl的surface传出去。

[cpp]  view plain  copy
  1. static jlong nativeCreateFromSurfaceControl(JNIEnv* env, jclass clazz,  
  2.         jlong surfaceControlNativeObj) {  
  3.     /* 
  4.      * This is used by the WindowManagerService just after constructing 
  5.      * a Surface and is necessary for returning the Surface reference to 
  6.      * the caller. At this point, we should only have a SurfaceControl. 
  7.      */  
  8.   
  9.     sp<SurfaceControl> ctrl(reinterpret_cast<SurfaceControl *>(surfaceControlNativeObj));  
  10.     sp<Surface> surface(ctrl->getSurface());//获取Surface  
  11.     if (surface != NULL) {  
  12.         surface->incStrong(&sRefBaseOwner);  
  13.     }  
  14.     return reinterpret_cast<jlong>(surface.get());//这个get方法是强指针的方法,获取其指针而已  
  15. }  

再来看看SurfaceControl的getSurface方法。

[cpp]  view plain  copy
  1. sp<Surface> SurfaceControl::getSurface() const  
  2. {  
  3.     Mutex::Autolock _l(mLock);  
  4.     if (mSurfaceData == 0) {  
  5.         // This surface is always consumed by SurfaceFlinger, so the  
  6.         // producerControlledByApp value doesn't matter; using false.  
  7.         mSurfaceData = new Surface(mGraphicBufferProducer, false);  
  8.     }  
  9.     return mSurfaceData;  
  10. }  


2.1 SurfaceControl的创建

下面我们再来看看SurfaceControl的创建,下面SurfaceTrace是SurfaceControl的一个子类。

[cpp]  view plain  copy
  1. SurfaceControl createSurfaceLocked() {  
  2.     ......  
  3.     mSurfaceControl = new SurfaceTrace(  
  4.     mSession.mSurfaceSession,  
  5.     attrs.getTitle().toString(),  
  6.     width, height, format, flags);  
  7.     ......  

我们先看下SurfaceTrace的构造函数,先调用了父类的构造函数

[cpp]  view plain  copy
  1. public SurfaceTrace(SurfaceSession s,  
  2.                String name, int w, int h, int format, int flags)  
  3.            throws OutOfResourcesException {  
  4.     super(s, name, w, h, format, flags);  
  5.     mName = name != null ? name : "Not named";  
  6.     mSize.set(w, h);  
  7.     synchronized (sSurfaces) {  
  8.         sSurfaces.add(0, this);  
  9.     }  
  10. }  

我们再来看SurfaceControl的构造函数,就是调用了nativeCreate来新建一个mNativeObject对象。前面我们看过通过这个对象就可以获取native层的Surface。

[cpp]  view plain  copy
  1. public SurfaceControl(SurfaceSession session,  
  2.         String name, int w, int h, int format, int flags)  
  3.                 throws OutOfResourcesException {  
  4.     if (session == null) {  
  5.         throw new IllegalArgumentException("session must not be null");  
  6.     }  
  7.     if (name == null) {  
  8.         throw new IllegalArgumentException("name must not be null");  
  9.     }  
  10.   
  11.     if ((flags & SurfaceControl.HIDDEN) == 0) {  
  12.         Log.w(TAG, "Surfaces should always be created with the HIDDEN flag set "  
  13.                 + "to ensure that they are not made visible prematurely before "  
  14.                 + "all of the surface's properties have been configured.  "  
  15.                 + "Set the other properties and make the surface visible within "  
  16.                 + "a transaction.  New surface name: " + name,  
  17.                 new Throwable());  
  18.     }  
  19.   
  20.     mName = name;  
  21.     mNativeObject = nativeCreate(session, name, w, h, format, flags);  
  22.     if (mNativeObject == 0) {  
  23.         throw new OutOfResourcesException(  
  24.                 "Couldn't allocate SurfaceControl native object");  
  25.     }  
  26.   
  27.     mCloseGuard.open("release");  
  28. }  

我们来看SurfaceControl的nativeCreate的JNI对应的方法,先用SurfaceSession获取SurfaceComposerClient,然后调用createSurface方法,获取SurfaceControl。

[cpp]  view plain  copy
  1. static jlong nativeCreate(JNIEnv* env, jclass clazz, jobject sessionObj,  
  2.         jstring nameStr, jint w, jint h, jint format, jint flags) {  
  3.     ScopedUtfChars name(env, nameStr);  
  4.     sp<SurfaceComposerClient> client(android_view_SurfaceSession_getClient(env, sessionObj));  
  5.     sp<SurfaceControl> surface = client->createSurface(  
  6.             String8(name.c_str()), w, h, format, flags);  
  7.     if (surface == NULL) {  
  8.         jniThrowException(env, OutOfResourcesException, NULL);  
  9.         return 0;  
  10.     }  
  11.     surface->incStrong((void *)nativeCreate);  
  12.     return reinterpret_cast<jlong>(surface.get());  
  13. }  

我们来看android_view_SurfaceSession_getClient就是获取SurfaceSession的mNativeObject对象,也就是SurfaceComposerClient对象。

[cpp]  view plain  copy
  1. sp<SurfaceComposerClient> android_view_SurfaceSession_getClient(  
  2.         JNIEnv* env, jobject surfaceSessionObj) {  
  3.     return reinterpret_cast<SurfaceComposerClient*>(  
  4.             env->GetLongField(surfaceSessionObj, gSurfaceSessionClassInfo.mNativeClient));  
  5. }  


2.2  SurfaceSession创建

那么Session的成员变量mSurfaceSession又是什么时候创建的?

之前在分析ViewRootImpl的setView时候,会调用Session的addToDisplay函数,在这个函数调用了PKMS的addWindow函数,而在addWindow方法,后面会创建一个WindowState对象,然后调用了其attach方法。

[cpp]  view plain  copy
  1. ......  
  2. WindowState win = new WindowState(this, session, client, token,  
  3.         attachedWindow, appOp[0], seq, attrs, viewVisibility, displayContent);  
  4. ......  
  5. win.attach();  

我们来看下这个WindowState的attach方法,调用了Session的windowAddedLocked方法。

[cpp]  view plain  copy
  1. void attach() {  
  2.     if (WindowManagerService.localLOGV) Slog.v(  
  3.         TAG, "Attaching " + this + " token=" + mToken  
  4.         + ", list=" + mToken.windows);  
  5.     mSession.windowAddedLocked();  
  6. }  

在Session的windowAddedLocked方法中创建了SurfaceSession对象。

[cpp]  view plain  copy
  1. void windowAddedLocked() {  
  2.     if (mSurfaceSession == null) {  
  3.         if (WindowManagerService.localLOGV) Slog.v(  
  4.             WindowManagerService.TAG, "First window added to " + this + ", creating SurfaceSession");  
  5.         mSurfaceSession = new SurfaceSession();  
  6.         if (WindowManagerService.SHOW_TRANSACTIONS) Slog.i(  
  7.                 WindowManagerService.TAG, "  NEW SURFACE SESSION " + mSurfaceSession);  
  8.         mService.mSessions.add(this);  
  9.         if (mLastReportedAnimatorScale != mService.getCurrentAnimatorScale()) {  
  10.             mService.dispatchNewAnimatorScaleLocked(this);  
  11.         }  
  12.     }  
  13.     mNumWindow++;  
  14. }  
在SurfaceSession构造函数中直接调用了nativeCreate JNI函数。

[cpp]  view plain  copy
  1. public SurfaceSession() {  
  2.     mNativeClient = nativeCreate();  
  3. }  

我们来看下这个JNI函数,创建了一个SurfaceComposerClient对象

[cpp]  view plain  copy
  1. static jlong nativeCreate(JNIEnv* env, jclass clazz) {  
  2.     SurfaceComposerClient* client = new SurfaceComposerClient();  
  3.     client->incStrong((void*)nativeCreate);  
  4.     return reinterpret_cast<jlong>(client);  
  5. }  


2.3 SurfaceComposerClient连接SurfaceFlinger

SurfaceComposerClient对象的构造函数也没有什么,因为SurfaceComposerClient类也是RefBase类派生的,所以我们来看下onFirstRef函数。

[cpp]  view plain  copy
  1. SurfaceComposerClient::SurfaceComposerClient()  
  2.     : mStatus(NO_INIT), mComposer(Composer::getInstance())  
  3. {  
  4. }  
  5.   
  6. void SurfaceComposerClient::onFirstRef() {  
  7.     sp<ISurfaceComposer> sm(ComposerService::getComposerService());  
  8.     if (sm != 0) {  
  9.         sp<ISurfaceComposerClient> conn = sm->createConnection();  
  10.         if (conn != 0) {  
  11.             mClient = conn;  
  12.             mStatus = NO_ERROR;  
  13.         }  
  14.     }  
  15. }  

onFirstRef函数先调用了ComposerService的getComposerService方法来获取一个ISurfaceComposer的指针,然后调用它的createConnection来得到一个ISurfaceComposerClient的指针,并且保存在mClient成员变量中。

最后我们知道在SurfaceControl中是调用SurfaceComposerClient的createSurface来得到Surface对象的。

我们再来看ComposerService::getComposerService函数,调用了connectLocked函数

[cpp]  view plain  copy
  1. /*static*/ sp<ISurfaceComposer> ComposerService::getComposerService() {  
  2.     ComposerService& instance = ComposerService::getInstance();  
  3.     Mutex::Autolock _l(instance.mLock);  
  4.     if (instance.mComposerService == NULL) {  
  5.         ComposerService::getInstance().connectLocked();  
  6.         assert(instance.mComposerService != NULL);  
  7.         ALOGD("ComposerService reconnected");  
  8.     }  
  9.     return instance.mComposerService;  
  10. }  

connectLocked函数只是获取SurfaceFlinger的Binder对象,然后保存在mComposerService。

[cpp]  view plain  copy
  1. void ComposerService::connectLocked() {  
  2.     const String16 name("SurfaceFlinger");  
  3.     while (getService(name, &mComposerService) != NO_ERROR) {  
  4.         usleep(250000);  
  5.     }  
  6.     ......  

所以最后在SurfaceComposerClient的onFirstRef函数中,先是获取SurfaceFlinger的Binder对象,然后调用函数createConnection函数,最终也是到SurfaceFlinger的createConnection函数。我们来看SurfaceFlinger的createConnection函数,创建一个client对象(这也是一个Binder服务),最后返回这个对象。而返回的对象保存在SurfaceComposerClient类的mClient成员变量中。这样每一个连接都会有一个新的Client对象。

[cpp]  view plain  copy
  1. sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()  
  2. {  
  3.     sp<ISurfaceComposerClient> bclient;  
  4.     sp<Client> client(new Client(this));  
  5.     status_t err = client->initCheck();  
  6.     if (err == NO_ERROR) {  
  7.         bclient = client;  
  8.     }  
  9.     return bclient;  
  10. }  


最后在SurfaceComposerClient中创建Surface,也是调用了mClient的createSurface,就到SurfaceFlinger的Client对象的createSurface函数了,获取了handle和gbp对象就创建了SurfaceControl对象。

[cpp]  view plain  copy
  1. sp<SurfaceControl> SurfaceComposerClient::createSurface(  
  2.         const String8& name,  
  3.         uint32_t w,  
  4.         uint32_t h,  
  5.         PixelFormat format,  
  6.         uint32_t flags)  
  7. {  
  8.     sp<SurfaceControl> sur;  
  9.     if (mStatus == NO_ERROR) {  
  10.         sp<IBinder> handle;  
  11.         sp<IGraphicBufferProducer> gbp;  
  12.         status_t err = mClient->createSurface(name, w, h, format, flags,  
  13.                 &handle, &gbp);  
  14.         ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err));  
  15.         if (err == NO_ERROR) {  
  16.             sur = new SurfaceControl(this, handle, gbp);  
  17.         }  
  18.     }  
  19.     return sur;  
  20. }  

我们再来看SurfaceControl对象的构造函数就是初始化各种变量。

[cpp]  view plain  copy
  1. SurfaceControl::SurfaceControl(  
  2.         const sp<SurfaceComposerClient>& client,  
  3.         const sp<IBinder>& handle,  
  4.         const sp<IGraphicBufferProducer>& gbp)  
  5.     : mClient(client), mHandle(handle), mGraphicBufferProducer(gbp)  
  6. {  
  7. }  
最后通过getSurface来新建一个Surface对象,Surface对象一个重要的参数是mGraphicBufferProducer,而这个对象的一个参数就是gbp
[cpp]  view plain  copy
  1. sp<Surface> SurfaceControl::getSurface() const  
  2. {  
  3.     Mutex::Autolock _l(mLock);  
  4.     if (mSurfaceData == 0) {  
  5.         // This surface is always consumed by SurfaceFlinger, so the  
  6.         // producerControlledByApp value doesn't matter; using false.  
  7.         mSurfaceData = new Surface(mGraphicBufferProducer, false);  
  8.     }  
  9.     return mSurfaceData;  
  10. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值