在上一篇文章Android SurfaceFlinger服務代理對象擷取過程源碼分析中介紹了應用程式擷取SurfaceFlinger中的各種遠端Binder代理對象,SurfaceFlinger為每個應用程式建立Client對象來處理應用程式的Binder請求,同時傳回Client的Binder代理對象給應用程式,這樣應用程式就可以通過該Binder代理對象來請求SurfaceFlinger建立Surface了,本文在前面章節的基礎上 分析Surface在服務端建立對應的Layer對象過程,并将BSurface遠端代理對象傳回給應用程式。
SurfaceComposerClient mSession = new SurfaceComposerClient();
sp<SurfaceControl> control= mSession->createSurface(0, dinfo.h, dinfo.w, PIXEL_FORMAT_RGB_565);
首先在應用程式端構造SurfaceComposerClient對象,在構造過程中,通過ComposerService類查詢到SurfaceFlinger服務的遠端代理對象,并通過SurfaceFlinger的遠端Binder代理對象連接配接SurfaceFlinger,擷取SurfaceFlinger為應用程式建立的Client的遠端代理對象,關于應用程式查詢SurfaceFlinger服務代理對象,應用程式連接配接SurfaceFlinger的過程請檢視Android SurfaceFlinger服務代理對象擷取過程源碼分析。得到SurfaceComposerClient對象後,就可以調用該對象的createSurface函數來建立Surface了,同時得到一個SurfaceControl對象。
sp<SurfaceControl> SurfaceComposerClient::createSurface(
DisplayID display, //顯示屏ID
uint32_t w, //圖像寬度
uint32_t h, //圖像高度
PixelFormat format,//圖形格式
uint32_t flags)//建立的Surface類型
{
String8 name;
const size_t SIZE = 128;
char buffer[SIZE];
snprintf(buffer, SIZE, "<pid_%d>", getpid());//為目前建立的Surface格式化名稱:<pid_%d>
name.append(buffer);
return SurfaceComposerClient::createSurface(name, display,w, h, format, flags);
}
将目前程序的ID号格式化為<pid_%d>的字元串來命名目前建立的Surface,然後調用SurfaceComposerClient的另一個重載函數createSurface來建立Surface
sp<SurfaceControl> SurfaceComposerClient::createSurface(
const String8& name,
DisplayID display,
uint32_t w,
uint32_t h,
PixelFormat format,
uint32_t flags)
{
sp<SurfaceControl> result;
if (mStatus == NO_ERROR) {
ISurfaceComposerClient::surface_data_t data;
//mClient為服務端Client的遠端代理對象BpSurfaceComposerClient,這裡請求服務端Client建立Surface
sp<ISurface> surface = mClient->createSurface(&data, name,display, w, h, format, flags);
if (surface != 0) {
//根據服務端傳回來的ISurface,surface_data_t及目前SurfaceComposerClient對象來構造SurfaceControl對象
result = new SurfaceControl(this, surface, data);
}
}
return result;
}
在Android SurfaceFlinger服務代理對象擷取過程源碼分析中我們知道,應用程式獲得Client的遠端代理對象BpSurfaceComposerClient後,儲存到成員變量mClient中,這裡就是通過Client的遠端代理對象BpSurfaceComposerClient向服務端的Client請求建立Surface,并得到BSurface的遠端Binder代理對象BpSurface,接着利用得到的BpSurface對象及SurfaceComposerClient對象為應用程式建立一個SurfaceControl對象。ISurface也是基于Binder程序通信架構設計的,其在Binder通信架構中的類關系圖如下:
由于ISurfaceComposerClient也是基于Binder通信架構的,是以BpSurfaceComposerClient向服務端的Client請求建立Surface的過程分為用戶端程序和服務端程序。
用戶端程序:
frameworks\native\libs\gui\ISurfaceComposerClient.cpp
virtual sp<ISurface> createSurface( surface_data_t* params,
const String8& name,
DisplayID display,
uint32_t w,
uint32_t h,
PixelFormat format,
uint32_t flags)
{
Parcel data, reply;
data.writeInterfaceToken(ISurfaceComposerClient::getInterfaceDescriptor());
data.writeString8(name);
data.writeInt32(display);
data.writeInt32(w);
data.writeInt32(h);
data.writeInt32(format);
data.writeInt32(flags);
remote()->transact(CREATE_SURFACE, data, &reply);
params->readFromParcel(reply);
return interface_cast<ISurface>(reply.readStrongBinder());
}
服務端程序:
frameworks\native\libs\gui\ISurfaceComposerClient.cpp
status_t BnSurfaceComposerClient::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code) {
case CREATE_SURFACE: {
CHECK_INTERFACE(ISurfaceComposerClient, data, reply);
surface_data_t params;
String8 name = data.readString8();
DisplayID display = data.readInt32();
uint32_t w = data.readInt32();
uint32_t h = data.readInt32();
PixelFormat format = data.readInt32();
uint32_t flags = data.readInt32();
sp<ISurface> s = createSurface(¶ms, name, display, w, h,format, flags);
params.writeToParcel(reply);
reply->writeStrongBinder(s->asBinder());
return NO_ERROR;
} break;
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
createSurface函數在BnSurfaceComposerClient的子類Client中實作
frameworks\native\services\surfaceflinger\SurfaceFlinger.cpp
sp<ISurface> Client::createSurface(
ISurfaceComposerClient::surface_data_t* params,
const String8& name,
DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
uint32_t flags)
{
//構造一個MessageCreateSurface消息
sp<MessageBase> msg = new MessageCreateSurface(mFlinger.get(),params, name, this, display, w, h, format, flags);
//将消息投遞到SurfaceFlinger的mEventQueue隊列中,并睡眠等待消息處理
mFlinger->postMessageSync(msg);
//當消息得到處理後,線程喚醒,讀取處理結果
return static_cast<MessageCreateSurface*>( msg.get() )->getResult();
}
關于SurfaceFlinger的消息隊列這裡不做分析。MessageCreateSurface消息被投遞到SurfaceFlinger的mEventQueue隊列中後,MessageCreateSurface類的handler函數被調用,用來處理MessageCreateSurface消息。
virtual bool handler() {
result = flinger->createSurface(params, name, client,display, w, h, format, flags);
return true;
}
這裡又調用SurfaceFlinger的createSurface函數來建立Surface
sp<ISurface> SurfaceFlinger::createSurface(
ISurfaceComposerClient::surface_data_t* params,
const String8& name,
const sp<Client>& client,
DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
uint32_t flags)
{
sp<LayerBaseClient> layer;
sp<ISurface> surfaceHandle;
//圖像的寬高必須大于0
if (int32_t(w|h) < 0) {
ALOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",int(w), int(h));
return surfaceHandle;
}
//根據flag來判斷請求建立的Surface類型,實際建立的是LayerBaseClient對象
sp<Layer> normalLayer;
switch (flags & eFXSurfaceMask) {
case eFXSurfaceNormal:
normalLayer = createNormalSurface(client, d, w, h, flags, format);
layer = normalLayer;
break;
case eFXSurfaceBlur:
// for now we treat Blur as Dim, until we can implement it
// efficiently.
case eFXSurfaceDim:
layer = createDimSurface(client, d, w, h, flags);
break;
case eFXSurfaceScreenshot:
layer = createScreenshotSurface(client, d, w, h, flags);
break;
}
if (layer != 0) {
//初始化LayerBaseClient對象
layer->initStates(w, h, flags);
layer->setName(name);
ssize_t token = addClientLayer(client, layer);
//從LayerBaseClient對象中取出BSurface本地對象
surfaceHandle = layer->getSurface();
if (surfaceHandle != 0) {
//初始化參數params
params->token = token;
params->identity = layer->getIdentity();
if (normalLayer != 0) {
Mutex::Autolock _l(mStateLock);
mLayerMap.add(layer->getSurfaceBinder(), normalLayer);
}
}
setTransactionFlags(eTransactionNeeded);
}
return surfaceHandle;
}
該函數首先根據應用程式發送過來的參數來讀取請求建立Surface的類型,目前Android系統定義了4種類型的Layer,即eFXSurfaceNormal、eFXSurfaceBlur、eFXSurfaceDim、eFXSurfaceScreenshot。構造完并初始化LayerBaseClient對象,最後從LayerBaseClient對象中取得BSurface本地對象,然後将BSurface對象的遠端Binder代理對象傳回給應用程式。
sp<Layer> SurfaceFlinger::createNormalSurface(
const sp<Client>& client, DisplayID display,
uint32_t w, uint32_t h, uint32_t flags,
PixelFormat& format)
{
// initialize the surfaces
switch (format) { // TODO: take h/w into account
case PIXEL_FORMAT_TRANSPARENT:
case PIXEL_FORMAT_TRANSLUCENT:
format = PIXEL_FORMAT_RGBA_8888;
break;
case PIXEL_FORMAT_OPAQUE:
#ifdef NO_RGBX_8888
format = PIXEL_FORMAT_RGB_565;
#else
format = PIXEL_FORMAT_RGBX_8888;
#endif
break;
}
#ifdef NO_RGBX_8888
if (format == PIXEL_FORMAT_RGBX_8888)
format = PIXEL_FORMAT_RGBA_8888;
#endif
//構造Layer對象
sp<Layer> layer = new Layer(this, display, client);
status_t err = layer->setBuffers(w, h, format, flags);
if (CC_LIKELY(err != NO_ERROR)) {
ALOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
layer.clear();
}
return layer;
}
該函數首先判斷圖像格式,然後構造一個Layer對象,接着為該Layer對象設定緩沖區buffer,上圖顯示了Layer類的繼承關系,在構造Layer對象時,其父類的構造函數會被依次調用。
Layer::Layer(SurfaceFlinger* flinger,
DisplayID display, const sp<Client>& client)
: LayerBaseClient(flinger, display, client),
mTextureName(-1U),
mQueuedFrames(0),
mCurrentTransform(0),
mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
mCurrentOpacity(true),
mRefreshPending(false),
mFrameLatencyNeeded(false),
mFrameLatencyOffset(0),
mFormat(PIXEL_FORMAT_NONE),
mGLExtensions(GLExtensions::getInstance()),
mOpaqueLayer(true),
mNeedsDithering(false),
mSecure(false),
mProtectedByApp(false)
{
mCurrentCrop.makeInvalid();
glGenTextures(1, &mTextureName);
}
Layer的父類LayerBaseClient構造過程:
LayerBaseClient::LayerBaseClient(SurfaceFlinger* flinger, DisplayID display,
const sp<Client>& client)
: LayerBase(flinger, display),
mHasSurface(false),
mClientRef(client),
mIdentity(uint32_t(android_atomic_inc(&sIdentity)))
{
}
LayerBaseClient的父類LayerBase的構造過程:
LayerBase::LayerBase(SurfaceFlinger* flinger, DisplayID display)
: dpy(display), contentDirty(false),
sequence(uint32_t(android_atomic_inc(&sSequence))),
mFlinger(flinger), mFiltering(false),
mNeedsFiltering(false),
mOrientation(0),
mPlaneOrientation(0),
mTransactionFlags(0),
mPremultipliedAlpha(true), mName("unnamed"), mDebug(false)
{
const DisplayHardware& hw(flinger->graphicPlane(0).displayHardware());
mFlags = hw.getFlags();
}
由于Layer繼承于RefBase類,同時實作了該類的onFirstRef函數,在前面就介紹了,當第一次強引用RefBase的子類對象,并且該子類對象實作了onFirstRef函數,onFirstRef函數會被自動調用,Layer對象也不例外:
void Layer::onFirstRef()
{
LayerBaseClient::onFirstRef();
// Creates a custom BufferQueue for SurfaceTexture to use
sp<BufferQueue> bq = new SurfaceTextureLayer();
mSurfaceTexture = new SurfaceTexture(mTextureName, true,GL_TEXTURE_EXTERNAL_OES, false, bq);
mSurfaceTexture->setConsumerUsageBits(getEffectiveUsage(0));
mSurfaceTexture->setFrameAvailableListener(new FrameQueuedListener(this));
mSurfaceTexture->setSynchronousMode(true);
#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
#warning "disabling triple buffering"
mSurfaceTexture->setBufferCountServer(2);
#else
mSurfaceTexture->setBufferCountServer(3);
#endif
}
SurfaceTextureLayer也是基于Binder通信架構設計的:
這裡就是為目前建立的Layer構造并初始化SurfaceTexture對象,該SurfaceTexture對象用來管理BufferQueue。回到SurfaceFlinger的建立 普通Surface函數createNormalSurface,構造完Layer對象後,還需根據圖像大小,格式來設定Layer對象中的buffer
status_t Layer::setBuffers( uint32_t w, uint32_t h,
PixelFormat format, uint32_t flags)
{
// this surfaces pixel format
PixelFormatInfo info;
status_t err = getPixelFormatInfo(format, &info);
if (err) {
ALOGE("unsupported pixelformat %d", format);
return err;
}
// the display's pixel format
const DisplayHardware& hw(graphicPlane(0).displayHardware());
uint32_t const maxSurfaceDims = min(hw.getMaxTextureSize(), hw.getMaxViewportDims());
// never allow a surface larger than what our underlying GL implementation
// can handle.
if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
return BAD_VALUE;
}
PixelFormatInfo displayInfo;
getPixelFormatInfo(hw.getFormat(), &displayInfo);
const uint32_t hwFlags = hw.getFlags();
mFormat = format;
mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
mProtectedByApp = (flags & ISurfaceComposer::eProtectedByApp) ? true : false;
mOpaqueLayer = (flags & ISurfaceComposer::eOpaque);
mCurrentOpacity = getOpacityForFormat(format);
mSurfaceTexture->setDefaultBufferSize(w, h);
mSurfaceTexture->setDefaultBufferFormat(format);
mSurfaceTexture->setConsumerUsageBits(getEffectiveUsage(0));
// we use the red index
int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED);
int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED);
mNeedsDithering = layerRedsize > displayRedSize;
return NO_ERROR;
}
最後傳回到SurfaceFlinger的createSurface函數設定Layer的目前狀态及名稱,同時将目前建立的Layer添加到Client的視窗清單及SurfaceFlinger維護的Z秩序清單中
layer->initStates(w, h, flags);
layer->setName(name);
ssize_t token = addClientLayer(client, layer);
将目前Layer添加的Client及SurfaceFlinger維護的清單中
ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,const sp<LayerBaseClient>& lbc)
{
// attach this layer to the client
size_t name = client->attachLayer(lbc);
Mutex::Autolock _l(mStateLock);
// add this layer to the current state list
addLayer_l(lbc);
return ssize_t(name);
}
函數調用attachLayer将目前Layer添加到目前應用程式在SurfaceFlinger中的Client的mLayers清單中
DefaultKeyedVector< size_t, wp<LayerBaseClient> > mLayers;
size_t Client::attachLayer(const sp<LayerBaseClient>& layer)
{
Mutex::Autolock _l(mLock);
size_t name = mNameGenerator++;
mLayers.add(name, layer);
return name;
}
接着調用函數addLayer_l将目前建立的Layer添加到SurfaceFlinger中
status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
{
ssize_t i = mCurrentState.layersSortedByZ.add(layer);
return (i < 0) ? status_t(i) : status_t(NO_ERROR);
}
完成Layer對象的建立及設定後,調用目前建立的Layer對象的getSurface()函數來建立一個BSurface對象,getSurface()函數實作在Layer的父類LayerBaseClient中
sp<ISurface> LayerBaseClient::getSurface()
{
sp<ISurface> s;
Mutex::Autolock _l(mLock);
LOG_ALWAYS_FATAL_IF(mHasSurface,"LayerBaseClient::getSurface() has already been called");
mHasSurface = true;
s = createSurface();
mClientSurfaceBinder = s->asBinder();
return s;
}
createSurface()用于建立一個BSurface對象,同時将建立的BSurface的Binder本地對象儲存到LayerBaseClient的父類LayerBase的成員變量mClientSurfaceBinder中。
sp<ISurface> LayerBaseClient::createSurface()
{
sp<ISurface> sur(new BSurface(mFlinger, this));
return sur;
}
層層傳回到SurfaceFlinger的createSurface函數,該函數最終傳回一個BSurface對象,最後在BnSurfaceComposerClient的onTransact函數中通過writeStrongBinder(s->asBinder())将BSurface的Binder本地對象寫入到Binder驅動中,應用程式端BpSurfaceComposerClient通過reply.readStrongBinder()從Binder驅動中讀取BSurface的Binder遠端代理對象,并通過interface_cast<ISurface>建立BSurface的遠端代理對象BpSurface,到此Surface就建立完成了,現在來總結一下Surface的整個建立過程: 1.應用程式程序通過SurfaceComposerClient對象向SurfaceFlinger請求建立Surface; 2.SurfaceComposerClient對象借助Client的遠端代理對象BpSurfaceComposerClient向Client請求建立Surface; 3.Client接收到BpSurfaceComposerClient的CREATE_SURFACE請求後,向SurfaceFlinger的事件隊列發送MessageCreateSurface消息; 4.MessageCreateSurface消息處理過程中,使用SurfaceFlinger來建立Surface; 5.SurfaceFlinger根據參數建立并初始化Layer對象; 6.建立BSurface對象,并将該對象的Binder遠端對象傳回給應用程式程序。