题外话

刚刚开始着笔写作这篇文章时,正好看电视在采访一位92岁的考古学家,在他的日记中有这样一句话,写在这里与君共勉“不要等待幸运的降临,要去努力的掌握知识”。如此朴实的一句话,此时此刻,正适合我们。


1 前言

回到前面的文章:Android 12(S) 图形显示系统 - 示例应用(二)  ,在上一篇文章中已经讲解了应用如何与SurfaceFlinger建立连接和通信,接下来就要去创建Surface了,当然在此之前,还有获取屏幕Display信息的操作,这不是关注的重点,先不展开讲解。
// create the native surface
sp<SurfaceControl> surfaceControl = surfaceComposerClient->createSurface(mName,
resolution.getWidth(),
resolution.getHeight(), PIXEL_FORMAT_RGBA_8888,
ISurfaceComposerClient::eFXSurfaceBufferState,
/*parent*/ nullptr);

注:本片涉及的代码

/frameworks/native/libs/gui/SurfaceComposerClient.cpp

/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

/frameworks/native/services/surfaceflinger/Client.cpp

/frameworks/native/libs/gui/ISurfaceComposer.cpp


2 createSurface的流程

先把类图贴这里,待会分析流程便于查看数据的流向
 

SurfaceComposerClient::createSurface

代码如下,比较简单,使用时需要传递一个名字(name),指定宽高信息,指定格式(format)等,返回一个SurfaceControl的指针,这个方法中调用了createSurfaceChecked

* /frameworks/native/libs/gui/SurfaceComposerClient.cpp

sp<SurfaceControl> SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h,
PixelFormat format, uint32_t flags,
const sp<IBinder>& parentHandle,
LayerMetadata metadata,
uint32_t* outTransformHint) {
sp<SurfaceControl> s;
createSurfaceChecked(name, w, h, format, &s, flags, parentHandle, std::move(metadata),
outTransformHint);
return s;
}

SurfaceComposerClient::createSurfaceChecked

这个方法的核心是 mClient->createSurface ,前面讲过(sp<ISurfaceComposerClient>  mClient)是Client的代理客户端,最终调用到服务端 Client::createSurface

这个方法中还有两个变量:

sp<IBinder> handle  == 这个代表什么? ==> SurfaceFlinger中创建的Layer的句柄或标识

sp<IGraphicBufferProducer> gbp == 他又是谁?==>这个gbp貌似已经没有实际用途了,BLASTBufferQueue分担了任务

* /frameworks/native/libs/gui/SurfaceComposerClient.cpp

status_t SurfaceComposerClient::createSurfaceChecked(const String8& name, uint32_t w, uint32_t h,
PixelFormat format,
sp<SurfaceControl>* outSurface, uint32_t flags,
const sp<IBinder>& parentHandle,
LayerMetadata metadata,
uint32_t* outTransformHint) {
sp<SurfaceControl> sur;
status_t err = mStatus; if (mStatus == NO_ERROR) {
sp<IBinder> handle;
sp<IGraphicBufferProducer> gbp; uint32_t transformHint = 0;
int32_t id = -1;
err = mClient->createSurface(name, w, h, format, flags, parentHandle, std::move(metadata),
&handle, &gbp, &id, &transformHint); if (outTransformHint) {
*outTransformHint = transformHint;
}
ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err));
if (err == NO_ERROR) {
*outSurface =
new SurfaceControl(this, handle, gbp, id, w, h, format, transformHint, flags);
}
}
return err;
}
 

Client::createSurface

Binder IPC 跨进程,一路飞奔,直接执行到了Client::createSurface函数中,先看代码:
*  /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, int32_t* outLayerId,
uint32_t* outTransformHint) {
// We rely on createLayer to check permissions.
return mFlinger->createLayer(name, this, w, h, format, flags, std::move(metadata), handle, gbp,
parentHandle, outLayerId, nullptr, outTransformHint);
}
上面这段代码是不是很简单,前面文章中也有提到Client对象中持有执行SurfaceFlinger的指针 sp<SurfaceFlinger> mFlinger
SurfaceFlinger隆重登场,呼叫 mFlinger->createLayer 。

SurfaceFlinger::createLayer

瞅瞅createLayer中都干了哪些事情呢?
* /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, int32_t* outLayerId,
const sp<Layer>& parentLayer, uint32_t* outTransformHint) {
if (int32_t(w|h) < 0) {
ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
int(w), int(h));
return BAD_VALUE;
} ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
"Expected only one of parentLayer or parentHandle to be non-null. "
"Programmer error?"); status_t result = NO_ERROR; sp<Layer> layer; std::string uniqueName = getUniqueLayerName(name.string()); switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
case ISurfaceComposerClient::eFXSurfaceBufferQueue:
case ISurfaceComposerClient::eFXSurfaceBufferState: {
result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
std::move(metadata), handle, &layer);
std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
if (pendingBufferCounter) {
std::string counterName = layer->getPendingBufferCounterName();
mBufferCountTracker.add((*handle)->localBinder(), counterName,
pendingBufferCounter);
}
} break;
case ISurfaceComposerClient::eFXSurfaceEffect:
// check if buffer size is set for color layer.
if (w > 0 || h > 0) {
ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
int(w), int(h));
return BAD_VALUE;
} result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
std::move(metadata), handle, &layer);
break;
case ISurfaceComposerClient::eFXSurfaceContainer:
// check if buffer size is set for container layer.
if (w > 0 || h > 0) {
ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
int(w), int(h));
return BAD_VALUE;
}
result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
std::move(metadata), handle, &layer);
break;
default:
result = BAD_VALUE;
break;
} if (result != NO_ERROR) {
return result;
} bool addToRoot = callingThreadHasUnscopedSurfaceFlingerAccess();
result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer, addToRoot,
outTransformHint);
if (result != NO_ERROR) {
return result;
}
mInterceptor->saveSurfaceCreation(layer); setTransactionFlags(eTransactionNeeded);
*outLayerId = layer->sequence;
return result;
}

1. 检查宽高数值是否合法,宽/高不应为负值;

2. 检查parentLayer/parentHandle,对于我们的应用来说,没有parent,两者都为 null;

3. 获取一个独一无二的Layer name,即不能有重名的Layer;

4. 根据flags去创建对应类型的Layer ⇒ createBufferStateLayer or createEffectLayer or createContainerLayer

Surface创建标志 SurfaceFlinger方法 Layer实例 简单说明
eFXSurfaceBufferQueue createBufferStateLayer BufferStateLayer

Creates a normal surface.

标准的Surface

eFXSurfaceBufferState
eFXSurfaceEffect createEffectLayer EffectLayer

Creates a effect surface which represents a solid color and or shadows.

纯色或阴影的显示效果的Surface

eFXSurfaceContainer createContainerLayer ContainerLayer

Creates a container surface. This surface will have no buffers and will only be used as a container for other surfaces, or for its InputInfo.

创建surface容器。此surface没有缓冲区,仅用作其他surfaces或InputInfo的容器。

 
Layer的详细知识我们之后再介绍,目前先以熟悉流程为主。
 

Tips:

有意思的一点是 BufferQueueLayer 貌似不再有实际用途了


 
5. 呼叫SurfaceFlinger::addClientLayer方法:
> 将新创建的Layer加入到 mCreatedLayers 这个列表中;
> client->attachLayer(handle, lbc)将新创建的Layer加入到对应的Client的 mLayers;
> setTransactionState 为后续SurfaceFlinger去做一些更新设置状态信息
 
6. Layer创建完成后,调用setTransactionFlags函数,告诉SurfaceFlinger,新增加了Layer,有新的显示,有很多显示数据需要去更新。SurfaceFlinger根据flag,决定是否需要换醒服务。
    比如addClientLayer时设置一些Transaction State
> 因为有设置 composerState.state.what = layer_state_t::eLayerCreated;  所以最终会call到 SurfaceFlinger::setClientStateLocked ==> SurfaceFlinger::handleLayerCreatedLocked
> SurfaceFlinger::handleLayerCreatedLocked中将新创建的Layer添加到mCurrentState的layer列表中,按照Z-order排序 , mGraphicBufferProducerList保存了当前的所有Layer内容的生产者

感觉这里讲解的还是迷迷糊糊,云里雾里,其实我自己也很多疑惑

Surface or Layer创建完成,应用得到了什么?

回过头再瞅一眼 SurfaceComposerClient::createSurfaceChecked 这个函数的代码,客户端主要获取到以下几个信息:

sp<IBinder> handle;
sp<IGraphicBufferProducer> gbp;
uint32_t transformHint = 0;
int32_t id = -1;
 

Layer handle

这个handle是在创建Layer时赋值的

status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
uint32_t w, uint32_t h, uint32_t flags,
LayerMetadata metadata, sp<IBinder>* handle,
sp<Layer>* outLayer) {
LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
args.textureName = getNewTexture();
sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
*handle = layer->getHandle();
*outLayer = layer; return NO_ERROR;
}
 
其中调用了Layer::getHandle()
sp<IBinder> Layer::getHandle() {
Mutex::Autolock _l(mLock);
if (mGetHandleCalled) {
ALOGE("Get handle called twice" );
return nullptr;
}
mGetHandleCalled = true;
return new Handle(mFlinger, this);
}
 
再来看看Handle的定义,它就是一个BBinder对象,可以通过Binder IPC机制传递给客户端
    /*
* The layer handle is just a BBinder object passed to the client
* (remote process) -- we don't keep any reference on our side such that
* the dtor is called when the remote side let go of its reference.
*
* LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
* this layer when the handle is destroyed.
*/
class Handle : public BBinder, public LayerCleaner {
public:
Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
: LayerCleaner(flinger, layer), owner(layer) {} wp<Layer> owner;
};
 
我把它暂且理解为 sp<IBinder> handle  ==  SurfaceFlinger中创建的Layer的句柄或标识
 
最后所有在客户端获取到的Layer信息都被封装到一个SurfaceControl对象中,并返回给应用来使用。
if (err == NO_ERROR) {
*outSurface =
new SurfaceControl(this, handle, gbp, id, w, h, format, transformHint, flags);
}
 
 

3 事务处理

再返回查看应用的代码,执行完 surfaceComposerClient->createSurface 创建好一个Layer图层后,便去设置Layer的一些状态:
SurfaceComposerClient::Transaction{}
.setLayer(surfaceControl, std::numeric_limits<int32_t>::max())
.show(surfaceControl)
.apply();
 
这里利用了Transaction类来完成状态信息的传递,那它是如何通知到SurfaceFlinger的呢?
先看一下Transaction类中都定义了哪些内容和功能:下面类图并没有把全部方法都列出
 
可以看到Transaction中提供大量方法,用于设置图像显示的属性等状态,比如show/hide/setPosition
 
你应该已经注意到了,Transaction中有两个非常重要的成员:mComposerStates和mDisplayStates,这两个成员分别用于处理两种不同类型的事务:合成相关事务 和 显示屏相关事务
 
 
ComposerState
* /frameworks/native/libs/gui/include/gui/LayerState.h

struct ComposerState {
layer_state_t state;
status_t write(Parcel& output) const;
status_t read(const Parcel& input);
};
ComposerState中主要包含成员 layer_state_t ,read/write函数用于BinderIPC 通信时封装和解析数据
 
layer_state_t
Used to communicate layer information between SurfaceFlinger and its clients.
用于在SurfaceFlinger和客户端之间传递layer信息。其定义可以参见   /frameworks/native/libs/gui/include/gui/LayerState.h
 
其中成员 what 用于标记layer的哪些状态/属性发生了变化,可能的变化有:
    enum {
ePositionChanged = 0x00000001,
eLayerChanged = 0x00000002,
eSizeChanged = 0x00000004,
eAlphaChanged = 0x00000008,
eMatrixChanged = 0x00000010,
eTransparentRegionChanged = 0x00000020,
eFlagsChanged = 0x00000040,
eLayerStackChanged = 0x00000080,
eReleaseBufferListenerChanged = 0x00000400,
eShadowRadiusChanged = 0x00000800,
eLayerCreated = 0x00001000,
eBufferCropChanged = 0x00002000,
eRelativeLayerChanged = 0x00004000,
eReparent = 0x00008000,
eColorChanged = 0x00010000,
eDestroySurface = 0x00020000,
eTransformChanged = 0x00040000,
eTransformToDisplayInverseChanged = 0x00080000,
eCropChanged = 0x00100000,
eBufferChanged = 0x00200000,
eAcquireFenceChanged = 0x00400000,
eDataspaceChanged = 0x00800000,
eHdrMetadataChanged = 0x01000000,
eSurfaceDamageRegionChanged = 0x02000000,
eApiChanged = 0x04000000,
eSidebandStreamChanged = 0x08000000,
eColorTransformChanged = 0x10000000,
eHasListenerCallbacksChanged = 0x20000000,
eInputInfoChanged = 0x40000000,
eCornerRadiusChanged = 0x80000000,
eDestinationFrameChanged = 0x1'00000000,
eCachedBufferChanged = 0x2'00000000,
eBackgroundColorChanged = 0x4'00000000,
eMetadataChanged = 0x8'00000000,
eColorSpaceAgnosticChanged = 0x10'00000000,
eFrameRateSelectionPriority = 0x20'00000000,
eFrameRateChanged = 0x40'00000000,
eBackgroundBlurRadiusChanged = 0x80'00000000,
eProducerDisconnect = 0x100'00000000,
eFixedTransformHintChanged = 0x200'00000000,
eFrameNumberChanged = 0x400'00000000,
eBlurRegionsChanged = 0x800'00000000,
eAutoRefreshChanged = 0x1000'00000000,
eStretchChanged = 0x2000'00000000,
eTrustedOverlayChanged = 0x4000'00000000,
};
 
比如setBuffer时设置eBufferChanged标记位
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBuffer(...) {
layer_state_t* s = getLayerState(sc);
...
s->what |= layer_state_t::eBufferChanged;
...
}
 
 
DisplayState

struct DisplayState {
enum {
eSurfaceChanged = 0x01,
eLayerStackChanged = 0x02,
eDisplayProjectionChanged = 0x04,
eDisplaySizeChanged = 0x08
}; DisplayState();
void merge(const DisplayState& other); uint32_t what;
sp<IBinder> token;
sp<IGraphicBufferProducer> surface;
uint32_t layerStack; // These states define how layers are projected onto the physical display.
//
// Layers are first clipped to `layerStackSpaceRect'. They are then translated and
// scaled from `layerStackSpaceRect' to `orientedDisplaySpaceRect'. Finally, they are rotated
// according to `orientation', `width', and `height'.
//
// For example, assume layerStackSpaceRect is Rect(0, 0, 200, 100), orientedDisplaySpaceRect is
// Rect(20, 10, 420, 210), and the size of the display is WxH. When orientation is 0, layers
// will be scaled by a factor of 2 and translated by (20, 10). When orientation is 1, layers
// will be additionally rotated by 90 degrees around the origin clockwise and translated by (W,
// 0).
ui::Rotation orientation = ui::ROTATION_0;
Rect layerStackSpaceRect;
Rect orientedDisplaySpaceRect; uint32_t width, height; status_t write(Parcel& output) const;
status_t read(const Parcel& input);
};
 
Display的状态有4个,也就是
    enum {
eSurfaceChanged = 0x01, // surface改变了
eLayerStackChanged = 0x02, // layer stack改变了
eDisplayProjectionChanged = 0x04, // display projecttion改变了
eDisplaySizeChanged = 0x08 // display size改变了
};
 
其中成员 DispalyState::what,就是用以标记哪些属性改变了,有多个属性改变的时候,加上对应的mark标记位即可。
比如setDisplaySize时设置eDisplaySizeChanged标记位
void SurfaceComposerClient::Transaction::setDisplaySize(const sp<IBinder>& token, uint32_t width, uint32_t height) {
DisplayState& s(getDisplayState(token));
s.width = width;
s.height = height;
s.what |= DisplayState::eDisplaySizeChanged;
}

在我们的应用中,调用了setLayer/show/apply,我们看看Transaction是如何把状态/属性信息传递给SurfaceFlinger的.

setLayer,设置Layer的z-order

SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setLayer(
const sp<SurfaceControl>& sc, int32_t z) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
s->what |= layer_state_t::eLayerChanged;
s->what &= ~layer_state_t::eRelativeLayerChanged;
s->z = z; registerSurfaceControlForCallback(sc);
return *this;
}

getLayerState,就是根据SurfaceCotrol对象去找对应的layer_state_t。

layer_state_t* SurfaceComposerClient::Transaction::getLayerState(const sp<SurfaceControl>& sc) {
auto handle = sc->getLayerStateHandle(); if (mComposerStates.count(handle) == 0) {
// we don't have it, add an initialized layer_state to our list
ComposerState s; s.state.surface = handle;
s.state.layerId = sc->getLayerId(); mComposerStates[handle] = s;
} return &(mComposerStates[handle].state);
}

文章前面讲解SurfaceComposerClient::createSurface时,我们知晓SurfaceFlinger创建好Layer后返回给客户端Layer handle和id,这些Layer信息都被封装到一个SurfaceControl对象,SurfaceControl::getLayerStateHandle返回的就是这个Layer handle

sp<IBinder> SurfaceControl::getLayerStateHandle() const
{
return mHandle;
}

然后判断这个layer hanlde是否在mComposerStates中,如果没有则创建对应的ComposerState并加入

我们看,setLayer时,增加标识what是layer_state_t::eLayerChanged,而对应的值保存到layer_state_t 中。你应该注意到了设置看起来没有立即生效,

同样,show时,也是将对应的标识加到what中,而是否显示的标识存放在layer_state_t的flag中。

SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::show(
const sp<SurfaceControl>& sc) {
return setFlags(sc, 0, layer_state_t::eLayerHidden);
} SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFlags(
const sp<SurfaceControl>& sc, uint32_t flags,
uint32_t mask) {
layer_state_t* s = getLayerState(sc);
if (!s) {
mStatus = BAD_INDEX;
return *this;
}
if ((mask & layer_state_t::eLayerOpaque) || (mask & layer_state_t::eLayerHidden) ||
(mask & layer_state_t::eLayerSecure) || (mask & layer_state_t::eLayerSkipScreenshot) ||
(mask & layer_state_t::eEnableBackpressure)) {
s->what |= layer_state_t::eFlagsChanged;
}
s->flags &= ~mask;
s->flags |= (flags & mask);
s->mask |= mask; registerSurfaceControlForCallback(sc);
return *this;
}

最后调用apply,使得设置生效

status_t SurfaceComposerClient::Transaction::apply(bool synchronous) {
...
sp<ISurfaceComposer> sf(ComposerService::getComposerService()); ...
cacheBuffers(); Vector<ComposerState> composerStates;
Vector<DisplayState> displayStates; for (auto const& kv : mComposerStates){
composerStates.add(kv.second);
} displayStates = std::move(mDisplayStates); ...
sf->setTransactionState(mFrameTimelineInfo, composerStates, displayStates, flags, applyToken,
mInputWindowCommands, mDesiredPresentTime, mIsAutoTimestamp,
{} /*uncacheBuffer - only set in doUncacheBufferTransaction*/,
hasListenerCallbacks, listenerCallbacks, mId);
mId = generateId(); // Clear the current states and flags
clear();
...
}

apply时,最重要的就是调用sf->setTransactionState,Binder IPC一路飞奔到了SurfaceFlinger::setTransactionState

status_t SurfaceFlinger::setTransactionState(...) {
ATRACE_CALL();
......
IPCThreadState* ipc = IPCThreadState::self();
const int originPid = ipc->getCallingPid();
const int originUid = ipc->getCallingUid();
TransactionState state{frameTimelineInfo, states,
displays, flags,
applyToken, inputWindowCommands,
desiredPresentTime, isAutoTimestamp,
uncacheBuffer, postTime,
permissions, hasListenerCallbacks,
listenerCallbacks, originPid,
originUid, transactionId}; // Check for incoming buffer updates and increment the pending buffer count.
state.traverseStatesWithBuffers([&](const layer_state_t& state) {
mBufferCountTracker.increment(state.surface->localBinder());
});
queueTransaction(state); // Check the pending state to make sure the transaction is synchronous.
if (state.transactionCommittedSignal) {
waitForSynchronousTransaction(*state.transactionCommittedSignal);
} return NO_ERROR;
}

SurfaceFlinger把信息封装到一个TransactionState变量中:

    TransactionState state{frameTimelineInfo,  states,
displays, flags,
applyToken, inputWindowCommands,
desiredPresentTime, isAutoTimestamp,
uncacheBuffer, postTime,
permissions, hasListenerCallbacks,
listenerCallbacks, originPid,
originUid, transactionId};

然后放置到待处理的Transaction队列中: SurfaceFlinger::queueTransaction

void SurfaceFlinger::queueTransaction(TransactionState& state) {
Mutex::Autolock _l(mQueueLock); ... mTransactionQueue.emplace(state);
ATRACE_INT("TransactionQueue", mTransactionQueue.size()); setTransactionFlags(eTransactionFlushNeeded, schedule, state.applyToken);
}

SurfaceFlinger::setTransactionFlags中在 满足一定条件时 调用signalTransaction触发执行 invalidate 操作

uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, TransactionSchedule schedule,
const sp<IBinder>& token) {
uint32_t old = mTransactionFlags.fetch_or(flags);
modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, token);
if ((old & flags) == 0) signalTransaction();
return old;
} void SurfaceFlinger::signalTransaction() {
mScheduler->resetIdleTimer();
mPowerAdvisor.notifyDisplayUpdateImminent();
mEventQueue->invalidate();
}

上一篇文章 Android 12(S) 图形显示系统 - SurfaceFlinger的启动和消息队列处理机制(四)

我们分析消息处理机制时对 invalidate 的执行介绍过

// 第一步

void SurfaceFlinger::onMessageReceived(int32_t what, int64_t vsyncId, nsecs_t expectedVSyncTime) {
switch (what) {
case MessageQueue::INVALIDATE: {
onMessageInvalidate(vsyncId, expectedVSyncTime);
break;
}
}
} // 第二步
void SurfaceFlinger::onMessageInvalidate(int64_t vsyncId, nsecs_t expectedVSyncTime) {
...
refreshNeeded = handleMessageTransaction();
...
} // 第三步
bool SurfaceFlinger::handleMessageTransaction() {
ATRACE_CALL(); if (getTransactionFlags(eTransactionFlushNeeded)) {
flushTransactionQueues();
}
...
} // 第四步
void SurfaceFlinger::flushTransactionQueues() {
...
// Now apply all transactions.
for (const auto& transaction : transactions) {
applyTransactionState(transaction.frameTimelineInfo, transaction.states,
transaction.displays, transaction.flags,
transaction.inputWindowCommands, transaction.desiredPresentTime,
transaction.isAutoTimestamp, transaction.buffer,
transaction.postTime, transaction.permissions,
transaction.hasListenerCallbacks, transaction.listenerCallbacks,
transaction.originPid, transaction.originUid, transaction.id);
if (transaction.transactionCommittedSignal) {
mTransactionCommittedSignals.emplace_back(
std::move(transaction.transactionCommittedSignal));
}
}
...
} // 第五步
void SurfaceFlinger::applyTransactionState(...) {
...
for (const DisplayState& display : displays) {
transactionFlags |= setDisplayStateLocked(display);
} for (const ComposerState& state : states) {
clientStateFlags |=
setClientStateLocked(frameTimelineInfo, state, desiredPresentTime, isAutoTimestamp,
postTime, permissions, listenerCallbacksWithSurfaces);
} ...
} // 第六步 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {}
uint32_t SurfaceFlinger::setClientStateLocked(){}

跋山涉水,走到了setClientStateLocked/setDisplayStateLocked

setDisplayStateLocked

uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
if (index < 0) return 0; uint32_t flags = 0;
DisplayDeviceState& state = mCurrentState.displays.editValueAt(index); const uint32_t what = s.what;
if (what & DisplayState::eSurfaceChanged) {
if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
state.surface = s.surface;
flags |= eDisplayTransactionNeeded;
}
}
....
}

setDisplayStateLocked中会把我们在客户端设置的标志为信息解析出来存储到mCurrentState中

setClientStateLocked

uint32_t SurfaceFlinger::setClientStateLocked(){
.... if (what & layer_state_t::eLayerChanged) {
// NOTE: index needs to be calculated before we update the state
const auto& p = layer->getParent();
if (p == nullptr) {
ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
if (layer->setLayer(s.z) && idx >= 0) { // setLayer
mCurrentState.layersSortedByZ.removeAt(idx);
mCurrentState.layersSortedByZ.add(layer);
// we need traversal (state changed)
// AND transaction (list changed)
flags |= eTransactionNeeded|eTraversalNeeded;
}
} else {
if (p->setChildLayer(layer, s.z)) {
flags |= eTransactionNeeded|eTraversalNeeded;
}
}
} .... }

setClientStateLocked中同样会把我们在客户端设置的标志为信息解析出来,然后设置到对应的Layer中去,这里就是调用了layer->setLayer,z-order信息存储到了layer的mDrawingState中

bool Layer::setLayer(int32_t z) {
if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
mDrawingState.sequence++;
mDrawingState.z = z;
mDrawingState.modified = true; mFlinger->mSomeChildrenChanged = true; // Discard all relative layering.
if (mDrawingState.zOrderRelativeOf != nullptr) {
sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
if (strongRelative != nullptr) {
strongRelative->removeZOrderRelative(this);
}
setZOrderRelativeOf(nullptr);
}
setTransactionFlags(eTransactionNeeded);
return true;
}

至此createSurface的流程基本就讲完了。


隐隐约约,迷迷糊糊感觉还是很多事情没讲透彻,比如设置下来的信息 存储到 mDrawingState or mCurrentState 后,这些信息又是什么时候确实被利用的呢?走了怎么样的流程?

哈哈,我现在只能说下次绘制图形时就会用了(嘻嘻)

4 总结

本文结合NativeSurface应用,讲解了创建Surface的流程,SurfaceFlinger中显示的数据都是通过Layer进行封装,介绍了创建Layer的过程。最后,介绍了事务处理的流程,客户端设置的参数信息怎么从Client端传到SurfaceFlinger的。
 
 

 
 
 

 
保持一份好心情

 
 
 

Android 12(S) 图形显示系统 - createSurface的流程(五)的更多相关文章

  1. Android 12(S) 图形显示系统 - BufferQueue/BLASTBufferQueue之初识(六)

    题外话 你有没有听见,心里有一声咆哮,那一声咆哮,它好像在说:我就是要从后面追上去! 写文章真的好痛苦,特别是自己对这方面的知识也一知半解就更加痛苦了.这已经是这个系列的第六篇了,很多次都想放弃了,但 ...

  2. Android 12(S) 图形显示系统 - 初识ANativeWindow/Surface/SurfaceControl(七)

    题外话 "行百里者半九十",是说步行一百里路,走过九十里,只能算是走了一半.因为步行越接近目的地,走起来越困难.借指凡事到了接近成功,往往是最吃力.最艰难的时段.劝人做事贵在坚持, ...

  3. Android 12(S) 图形显示系统 - 简单聊聊 SurfaceView 与 BufferQueue的关联(十三)

    必读: Android 12(S) 图形显示系统 - 开篇 一.前言 前面的文章中,讲解的内容基本都是从我们提供的一个 native demo Android 12(S) 图形显示系统 - 示例应用( ...

  4. Android 12(S) 图形显示系统 - BufferQueue的工作流程(八)

    题外话 最近总有一个感觉:在不断学习中,越发的感觉自己的无知,自己是不是要从"愚昧之巅"掉到"绝望之谷"了,哈哈哈 邓宁-克鲁格效应 一.前言 前面的文章中已经 ...

  5. Android 12(S) 图形显示系统 - BufferQueue的工作流程(九)

    题外话 Covid-19疫情的强烈反弹,小区里检测出了无症状感染者.小区封闭管理,我也不得不居家办公了.既然这么大把的时间可以光明正大的宅家里,自然要好好利用,八个字 == 努力工作,好好学习 一.前 ...

  6. Android 12(S) 图形显示系统 - BufferQueue的工作流程(十)

    题外话 疫情隔离在家,周末还在努力学习的我  ..... 一.前言 上一篇文章中,有基本讲清楚Producer一端的处理逻辑,最后也留下了一个疑问: Consumer是什么时候来消费数据的?他是自己主 ...

  7. Android 12(S) 图形显示系统 - 示例应用(二)

    1 前言 为了更深刻的理解Android图形系统抽象的概念和BufferQueue的工作机制,这篇文章我们将从Native Level入手,基于Android图形系统API写作一个简单的图形处理小程序 ...

  8. Android 12(S) 图形显示系统 - 基本概念(一)

    1 前言 Android图形系统是系统框架中一个非常重要的子系统,与其它子系统一样,Android 框架提供了各种用于 2D 和 3D 图形渲染的 API供开发者使用来创建绚丽多彩的应用APP.图形渲 ...

  9. Android 12(S) 图形显示系统 - 应用建立和SurfaceFlinger的沟通桥梁(三)

    1 前言 上一篇文章中我们已经创建了一个Native示例应用,从使用者的角度了解了图形显示系统API的基本使用,从这篇文章开始我们将基于这个示例应用深入图形显示系统API的内部实现逻辑,分析运作流程. ...

随机推荐

  1. Chapter 8 Selection Bias

    目录 8.1 The structure of selection bias 8.2 Examples of selection bias 8.3 Selection bias and confoun ...

  2. MySQL8.0的下载与安装

    下载 进入官网的下载页面 点击下图中的链接 可以选择上边的 Community Server ,那样会下载压缩包,这里我选择下边的 Installer for Windows ,下载的是安装包 点击下 ...

  3. Capstone CS5267|CS5267参数|CS5267规格书

    CS5267 USB Type-C to HDMI2.0b 4k@60Hz Converter with PD3.0 Support 1.CS5267概述 Capstone CS5267是一款高性能T ...

  4. sping练习,在Eclipse搭建的Spring开发环境中,使用工厂方式创建Bean对象,将创建的Bean对象输出到控制台。

    相关 知识 >>> 相关 练习 >>> 实现要求: 在Eclipse搭建的Spring开发环境中,使用工厂方式创建Bean对象,将创建的Bean对象输出到控制台.要 ...

  5. 使用.NET 6开发TodoList应用(17)——实现数据塑形

    系列导航及源代码 使用.NET 6开发TodoList应用文章索引 需求 在查询的场景中,还有一类需求不是很常见,就是在前端请求中指定返回的字段,所以关于搜索的最后一个主题我们就来演示一下关于数据塑形 ...

  6. openmesh - src - trimesh delete and add elements

    openmesh - src - trimesh delete and add elements openmesh 版本 8.1 About 本文主要介绍openmesh的如下接口 add_verte ...

  7. 您应该知道的35个绝对重要的Linux命令

    https://mp.weixin.qq.com/s?__biz=MzU3NTgyODQ1Nw==&mid=2247499293&idx=2&sn=1353b78d6ad01d ...

  8. PowerShell 管道符之Select的使用方法【一】

    之前我文章中我们略微提到过管道符的操作,但并不多,这篇主要讲解一下详细的使用方法 假设我们要对数组中的数字1-10中我想要从右往左换句话说就是从字符串最后一个字开始倒过来往前数截取6个子字符串时可以这 ...

  9. jave 数据类型 float 的 正确赋值

    1.前言 float 是单精度浮点型 ,有效数字8位 ,在机内存占4个字节  [double 是双精度浮点型 ,有效数字16位 ,在机内存占8个字节 ] 2.赋值 float  a=1.3  会编译报 ...

  10. JS 利用新浪接口通过IP地址获取当前所在城市

    <html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">< ...