上篇博客分析到SurfaceFlinger收到了VSync信号后,调用了handleMessageRefresh函数,这篇博客主要就是分析这个函数,我们先看看它的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
void
SurfaceFlinger::handleMessageRefresh() {
ATRACE_CALL();
static
nsecs_t previousExpectedPresent =
0
;
nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(
0
);
static
bool previousFrameMissed =
false
;
bool frameMissed = (expectedPresent == previousExpectedPresent);
if
(frameMissed != previousFrameMissed) {
ATRACE_INT(
"FrameMissed"
, static_cast<
int
>(frameMissed));
}
previousFrameMissed = frameMissed;
if
(CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
// Latch buffers, but don't send anything to HWC, then signal another
// wakeup for the next vsync
preComposition();
repaintEverything();
}
else
{
preComposition();
rebuildLayerStacks();
setUpHWComposer();
doDebugFlashRegions();
doComposition();
postComposition();
}
previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(
0
);
}</
int
>
|
我们主要看下下面几个函数。
1
2
3
4
5
6
|
preComposition();
rebuildLayerStacks();
setUpHWComposer();
doDebugFlashRegions();
doComposition();
postComposition();
|
一、preComposition函数
我们先来看第一个函数preComposition
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
void
SurfaceFlinger::preComposition()
{
bool needExtraInvalidate =
false
;
const
LayerVector& layers(mDrawingState.layersSortedByZ);
const
size_t count = layers.size();
for
(size_t i=
0
; i<count -=
""
if
=
""
>onPreComposition()) {
needExtraInvalidate =
true
;
}
}
if
(needExtraInvalidate) {
signalLayerUpdate();
}
}
</count>
|
上面函数先是调用了mDrawingState的layersSortedByZ来得到上次绘图的Layer层列表。并不是所有的Layer都会参与屏幕图像的绘制,因此SurfaceFlinger用state对象来记录参与绘制的Layer对象。
记得在之前的博客,我们分析过createLayer函数来创建Layer,创建之后会调用addClientLayer函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
status_t SurfaceFlinger::createLayer(
const
String8& name,
const
sp<client>& client,
uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
sp<ibinder>* handle, sp<igraphicbufferproducer>* gbp)
{
//ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
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;
}
status_t result = NO_ERROR;
sp<layer> layer;
switch
(flags & ISurfaceComposerClient::eFXSurfaceMask) {
case
ISurfaceComposerClient::eFXSurfaceNormal:
result = createNormalLayer(client,
name, w, h, flags, format,
handle, gbp, &layer);
break
;
case
ISurfaceComposerClient::eFXSurfaceDim:
result = createDimLayer(client,
name, w, h, flags,
handle, gbp, &layer);
break
;
default
:
result = BAD_VALUE;
break
;
}
if
(result != NO_ERROR) {
return
result;
}
result = addClientLayer(client, *handle, *gbp, layer);
if
(result != NO_ERROR) {
return
result;
}
setTransactionFlags(eTransactionNeeded);
return
result;
}</layer></igraphicbufferproducer></ibinder></client>
|
我们来看下addClientLayer函数,这里会把Layer对象放在mCurrentState的layersSortedByZ对象中。而mDrawingState和mCurrentState什么关系呢?在后面我们会介绍,mDrawingState代表上一次绘图时的状态,处理完之后会把mCurrentState赋给mDrawingState。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
status_t SurfaceFlinger::addClientLayer(
const
sp<client>& client,
const
sp<ibinder>& handle,
const
sp<igraphicbufferproducer>& gbc,
const
sp<layer>& lbc)
{
// add this layer to the current state list
{
Mutex::Autolock _l(mStateLock);
if
(mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
return
NO_MEMORY;
}
mCurrentState.layersSortedByZ.add(lbc);
mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
}
// attach this layer to the client
client->attachLayer(handle, lbc);
return
NO_ERROR;
}</layer></igraphicbufferproducer></ibinder></client>
|
回到preComposition函数,遍历所有的Layer对象,调用其onPreComposition函数来检测Layer层中的图像是否有变化。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
void
SurfaceFlinger::preComposition()
{
bool needExtraInvalidate =
false
;
const
LayerVector& layers(mDrawingState.layersSortedByZ);
const
size_t count = layers.size();
for
(size_t i=
0
; i<count -=
""
if
=
""
>onPreComposition()) {
needExtraInvalidate =
true
;
}
}
if
(needExtraInvalidate) {
signalLayerUpdate();
}
}</count>
|
1.1 每个Layer的onFrameAvailable函数
onPreComposition函数来根据mQueuedFrames来判断图像是否发生了变化,或者是mSidebandStreamChanged。
1
2
3
4
|
bool Layer::onPreComposition() {
mRefreshPending =
false
;
return
mQueuedFrames >
0
|| mSidebandStreamChanged;
}
|
当Layer所对应的Surface更新图像后,它所对应的Layer对象的onFrameAvailable函数会被调用来通知这种变化。
我们看Layer的onFirstRef函数,先调用BufferQueue::createBufferQueue来获取一个Buffer的消费者和生产者。然后新建了一个MonitoredProducer和一个SurfaceFlingerConsumer
1
2
3
4
5
6
7
8
9
10
|
void
Layer::onFirstRef() {
// Creates a custom BufferQueue for SurfaceFlingerConsumer to use
sp<igraphicbufferproducer> producer;
sp<igraphicbufferconsumer> consumer;
BufferQueue::createBufferQueue(&producer, &consumer);
mProducer =
new
MonitoredProducer(producer, mFlinger);
mSurfaceFlingerConsumer =
new
SurfaceFlingerConsumer(consumer, mTextureName);
mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(
0
));
mSurfaceFlingerConsumer->setContentsChangedListener(
this
);
mSurfaceFlingerConsumer->setName(mName);</igraphicbufferconsumer></igraphicbufferproducer>
|
我们再来看SurfaceFlingerConsumer的setContentsChangedListener函数
1
2
3
4
5
6
|
void
SurfaceFlingerConsumer::setContentsChangedListener(
const
wp<contentschangedlistener>& listener) {
setFrameAvailableListener(listener);
Mutex::Autolock lock(mMutex);
mContentsChangedListener = listener;
}</contentschangedlistener>
|
上面函数是调用了基类ConsumerBase的setFrameAvailableListener函数,将listener赋给了mFrameAvailableListener。
1
2
3
4
5
6
|
void
ConsumerBase::setFrameAvailableListener(
const
wp<frameavailablelistener>& listener) {
CB_LOGV(
"setFrameAvailableListener"
);
Mutex::Autolock lock(mMutex);
mFrameAvailableListener = listener;
}</frameavailablelistener>
|
而最终在其onFrameAvailable函数中调用了listener->onFrameAvailable函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
void
ConsumerBase::onFrameAvailable(
const
BufferItem& item) {
CB_LOGV(
"onFrameAvailable"
);
sp<frameavailablelistener> listener;
{
// scope for the lock
Mutex::Autolock lock(mMutex);
listener = mFrameAvailableListener.promote();
}
if
(listener != NULL) {
CB_LOGV(
"actually calling onFrameAvailable"
);
listener->onFrameAvailable(item);
}
}</frameavailablelistener>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
void
Layer::onFrameAvailable(
const
BufferItem& item) {
// Add this buffer from our internal queue tracker
{
// Autolock scope
Mutex::Autolock lock(mQueueItemLock);
// Reset the frame number tracker when we receive the first buffer after
// a frame number reset
if
(item.mFrameNumber ==
1
) {
mLastFrameNumberReceived =
0
;
}
// Ensure that callbacks are handled in order
while
(item.mFrameNumber != mLastFrameNumberReceived +
1
) {
status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
ms2ns(
500
));
if
(result != NO_ERROR) {
ALOGE(
"[%s] Timed out waiting on callback"
, mName.string());
}
}
mQueueItems.push_back(item);
android_atomic_inc(&mQueuedFrames);
// Wake up any pending callbacks
mLastFrameNumberReceived = item.mFrameNumber;
mQueueItemCondition.broadcast();
}
mFlinger->signalLayerUpdate();
}
|
同样在SurfaceFlinger的preComposition函数中当有Layer的图像改变了,最后也会调用SurfaceFlinger的signalLayerUpdate函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
void
SurfaceFlinger::preComposition()
{
bool needExtraInvalidate =
false
;
const
LayerVector& layers(mDrawingState.layersSortedByZ);
const
size_t count = layers.size();
for
(size_t i=
0
; i<count -=
""
if
=
""
>onPreComposition()) {
needExtraInvalidate =
true
;
}
}
if
(needExtraInvalidate) {
signalLayerUpdate();
}
}</count>
|
SurfaceFlinger::signalLayerUpdate是调用了MessageQueue的invalidate函数
1
2
3
|
void
SurfaceFlinger::signalLayerUpdate() {
mEventQueue.invalidate();
}
|
调用了handler的dispatchInvalidate函数,
1
2
3
4
5
6
7
|
void
MessageQueue::invalidate() {
#
if
INVALIDATE_ON_VSYNC
mEvents->requestNextVsync();
#
else
mHandler->dispatchInvalidate();
#endif
}
|
Handler::dispatchInvalidate只是发送了一个消息
1
2
3
4
5
|
void
MessageQueue::Handler::dispatchInvalidate() {
if
((android_atomic_or(eventMaskInvalidate, &mEventMask) & eventMaskInvalidate) ==
0
) {
mQueue.mLooper->sendMessage(
this
, Message(MessageQueue::INVALIDATE));
}
}
|
最后处理还是调用了SurfaceFlinger的onMessageReceived函数。
1
2
3
4
|
case
INVALIDATE:
android_atomic_and(~eventMaskInvalidate, &mEventMask);
mQueue.mFlinger->onMessageReceived(message.what);
break
;
|
我们再来看看SurfaceFlinger的onMessageReceived函数对NVALIDATE的处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
void
SurfaceFlinger::onMessageReceived(int32_t what) {
ATRACE_CALL();
switch
(what) {
......
case
MessageQueue::INVALIDATE: {
bool refreshNeeded = handleMessageTransaction();
refreshNeeded |= handleMessageInvalidate();
refreshNeeded |= mRepaintEverything;
if
(refreshNeeded) {
// Signal a refresh if a transaction modified the window state,
// a new buffer was latched, or if HWC has requested a full
// repaint
signalRefresh();
}
break
;
|
我们先来看下handleMessageTransaction和handleMessageInvalidate函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
bool SurfaceFlinger::handleMessageTransaction() {
uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
if
(transactionFlags) {
handleTransaction(transactionFlags);
return
true
;
}
return
false
;
}
bool SurfaceFlinger::handleMessageInvalidate() {
ATRACE_CALL();
return
handlePageFlip();
}
|
handleMessageInvalidate函数中调用了handlePageFlip函数,这个函数将会处理Layer中的缓冲区,把更新过的图像缓冲区切换到前台,等待VSync信号更新到FrameBuffer。
1.2 绘制流程
具体完整的绘制流程如图。
用户进程更新Surface图像,将导致SurfaceFlinger中的Layer发送invalidate消息,处理该消息会调用handleTransaction函数和handlePageFilp函数来更新Layer对象。一旦VSync信号到来,再调用rebuildlayerStacks setUpHWComposer doComposition postComposition函数将所有Layer的图像混合后更新到显示设备上去。
二、handleTransaction handPageFlip更新Layer对象
在上一节中的绘图的流程中,我们看到了handleTransaction和handPageFlip这两个函数通常是在用户进程更新Surface图像时会调用,来更新Layer对象。这节就主要讲解这两个函数。
2.1handleTransaction函数
handleTransaction函数的参数是transactionFlags,不过函数中没有使用这个参数,而是通过getTransactionFlags(eTransactionMask)来重新对transactionFlags赋值,然后使用它作为参数来调用函数handleTransactionLocked。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
void
SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
{
ATRACE_CALL();
State drawingState(mDrawingState);
Mutex::Autolock _l(mStateLock);
const
nsecs_t now = systemTime();
mDebugInTransaction = now;
transactionFlags = getTransactionFlags(eTransactionMask);
//产生一个新的transactionFlags变量
handleTransactionLocked(transactionFlags);
mLastTransactionTime = systemTime() - now;
mDebugInTransaction =
0
;
invalidateHwcGeometry();
}
|
getTransactionFlags函数的参数是eTransactionMask只是屏蔽其他位。
1
2
3
|
uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
return
android_atomic_and(~flags, &mTransactionFlags) & flags;
}
|
handleTransactionLocked函数会调用每个Layer类的doTransaction函数,在分析handleTransactionLocked函数之前,我们先看看Layer类 的doTransaction函数。
2.2 Layer的doTransaction函数
下面是Layer的doTransaction函数代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
uint32_t Layer::doTransaction(uint32_t flags) {
ATRACE_CALL();
const
Layer::State& s(getDrawingState());
//上次绘制的State对象
const
Layer::State& c(getCurrentState());
//当前使用的State对象
const
bool sizeChanged = (c.requested.w != s.requested.w) ||
//如果两个对象的大小不相等,说明Layer的尺寸发生变化
(c.requested.h != s.requested.h);
if
(sizeChanged) {
//如果Layer的尺寸发生变化,就要改变Surface的缓冲区的尺寸
mSurfaceFlingerConsumer->setDefaultBufferSize(
c.requested.w, c.requested.h);
}
if
(!isFixedSize()) {
//如果Layer不是固定尺寸的类型,比较它的实际大小和要求的改变大小
const
bool resizePending = (c.requested.w != c.active.w) ||
(c.requested.h != c.active.h);
if
(resizePending && mSidebandStream == NULL) {
//如果两者不一样,flags加上不更新Geometry标志
flags |= eDontUpdateGeometryState;
}
}
if
(flags & eDontUpdateGeometryState) {
}
else
{
//如果没有eDontUpdateGeometryState标志,更新active的值为request
Layer::State& editCurrentState(getCurrentState());
editCurrentState.active = c.requested;
}
if
(s.active != c.active) {
// 如果当前state的active和以前的State的active不等,设置更新标志
flags |= Layer::eVisibleRegion;
}
if
(c.sequence != s.sequence) {
//如果当前state的sequence和以前state的sequence不等,设置更新标志
flags |= eVisibleRegion;
this
->contentDirty =
true
;
const
uint8_t type = c.transform.getType();
mNeedsFiltering = (!c.transform.preserveRects() ||
(type >= Transform::SCALE));
}
// Commit the transaction
commitTransaction();
//将mCurrentState的值赋给mDrawingState
return
flags;
}
|
Layer类中的两个类型为Layer::State的成员变量mDrawingState、mCurrentState,我们来看下Layer::State类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
struct State {
Geometry active;
//实际大小
Geometry requested;
//用户大小
uint32_t z;
//Layer的Z轴值
uint32_t layerStack;
//和显示设备的关联值
uint8_t alpha;
//Layer的透明度
uint8_t flags;
//Layer的标志
uint8_t reserved[
2
];
int32_t sequence;
//序列值,Layer的属性变化一次,这个值就加1
Transform transform;
// the transparentRegion hint is a bit special, it's latched only
// when we receive a buffer -- this is because it's "content"
// dependent.
Region activeTransparentRegion;
//实际的透明区域
Region requestedTransparentRegion;
//用户社会中的透明区域
};
|
这里为什么要两个对象呢?Layer对象在绘制图形时,使用的是mDrawingState变量,用户调用接口设置Layer对象属性是,设置的值保存在mCurrentState对象中,这样就不会因为用户的操作而干扰Layer对象的绘制了。
Layer的doTransaction函数据你是比较这两个变量,如果有不同的地方,说明在上次绘制以后,用户改变的Layer的设置,要把这种变化通过flags返回。
State的结构中有两个Geometry字段,active和requested。他们表示layer的尺寸,其中requested保存是用户设置的尺寸,而active保存的值通过计算后的实际尺寸。
State中的z字段的值就是Layer在显示轴的位置,值越小位置越靠下。
layerStack字段是用户指定的一个值,用户可以给DisplayDevice也指定一个layerStack值,只有Layer对象和DisplayDevice对象的layerStack相等,这个Layer才能在这个显示设备上输出,这样的好处是可以让显示设备只显示某个Surface的内容。例如,可以让HDMI显示设备只显示手机上播放视频的Surface窗口,但不显示Activity窗口。
sequence字段是个序列值,每当用户调用了Layer的接口,例如setAlpha、setSize或者setLayer等改变Layer对象属性的哈数,这个值都会加1。因此在doTransaction函数中能通过比较sequence值来判断Layer的属性值有没有变化。
doTransaction函数最后会调用commitTransaction函数,就是把mCurrentState赋值给mDrawingState
1
2
3
|
void
Layer::commitTransaction() {
mDrawingState = mCurrentState;
}
|