SurfaceFlinger深入之Layer创建与渲染

一切的开始resumeActivity

在Activity第一次执行resume的时候,会将DecorView添加到WindowManager中,由此开始了Activity视图显示的第一步。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
...
final Activity a = r.activity;
...
if (r.window == null && !a.mFinished && willBeVisible) {
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
...
if (a.mVisibleFromClient) {
if (!a.mWindowAdded) {
a.mWindowAdded = true;
wm.addView(decor, l);
} else {
...
}
}
...
}
...
}

WindowManager.addView

WindowManagerImpl最终会调用到WindowManagerGlobal中,在WindowManagerGlobal中会创建一个ViewRootImpl对象,每个DecorView都会有对应的ViewRootImpl对象,而一个Window中可以有多个DecorView。

ViewRootImpl负责与WMS通信,通过其维护的IWindowSession对象来与WMS进行通信。

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
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
...
ViewRootImpl root;
View panelParentView = null;

synchronized (mLock) {
...
root = new ViewRootImpl(view.getContext(), display);

view.setLayoutParams(wparams);

mViews.add(view);
mRoots.add(root);
mParams.add(wparams);

// do this last because it fires off messages to start doing things
try {
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) {
...
throw e;
}
}
}

ViewRootImpl.setView

通过WindowSession与WMS通信,将Window对象交给WMS,WMS通过Window对象与ViewRootImpl通信。

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
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
synchronized (this) {
if (mView == null) {
mView = view;
...
// If the application owns the surface, don't enable hardware acceleration
if (mSurfaceHolder == null) {
// While this is supposed to enable only, it can effectively disable
// the acceleration too.
// 开启硬件渲染
enableHardwareAcceleration(attrs);
...
}
...
// Schedule the first layout -before- adding to the window
// manager, to make sure we do the relayout before receiving
// any other events from the system.
// post一次渲染请求,等待SF连接成功后调用
requestLayout();
...
try {
...
// 将mWindow添加到WMS上,WMS使用其与应用端进行通信,具体操作会对应到ViewRootImpl中
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
}
...
}
}
}

WMS.addWindow

SurfaceSession对应着C层的SurfaceComposerClient,该对象是用来与SurfaceFlinger进行通信的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public int addWindow(Session session, IWindow client, int seq,
WindowManager.LayoutParams attrs, int viewVisibility, int displayId,
Rect outContentInsets, Rect outStableInsets, Rect outOutsets,
InputChannel outInputChannel) {
...
final WindowState win = new WindowState(this, session, client, token, parentWindow,
appOp[0], seq, attrs, viewVisibility, session.mUid,
session.mCanAddInternalSystemWindow);
...
// 创建SurfaceSession(),保存在应用端的WindowSession中,用来与SurfaceFlinger通信
win.attach();
// WindowMap管理所有添加到WMS上的Window
mWindowMap.put(client.asBinder(), win);
...
win.mToken.addWindow(win);
...
return res;
}

连接SF

SurfaceSession维护了C层的SurfaceComposerClient对象

1
2
3
public SurfaceSession() {
mNativeClient = nativeCreate();
}
1
2
3
4
5
6
static jlong nativeCreate(JNIEnv* env, jclass clazz) {
// 创建SurfaceComposerClient对象
SurfaceComposerClient* client = new SurfaceComposerClient();
client->incStrong((void*)nativeCreate);
return reinterpret_cast<jlong>(client);
}
SurfaceComposerClient.onFirstRef

在SurfaceComposerClient对象被第一次强引用的时候(引用计数器变为1),会触发该方法。在该方法里从SF中请求一个Client连接对象,通过该Client对象与SF通信。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void SurfaceComposerClient::onFirstRef() {
sp<ISurfaceComposer> sm(ComposerService::getComposerService());
if (sm != 0) {
auto rootProducer = mParent.promote();
sp<ISurfaceComposerClient> conn;
// 创建与SF的连接,通过返回的ISurfaceComposerClient对象与SF进行通信
conn = (rootProducer != nullptr) ? sm->createScopedConnection(rootProducer) :
sm->createConnection();
if (conn != 0) {
mClient = conn;
mStatus = NO_ERROR;
}
}
}
SF.createConnection
1
2
3
sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
return initClient(new Client(this));
}

ViewRootImpl.doTraversal创建和渲染

ViewRootImpl.relayoutWindow创建Layer

与SF建立连接后,上面post的渲染请求被执行,会通知WMS进行relayout,在该方法的最后一个参数是Surface,这个Surface是在ViewRootImpl创建的时候就创建好的,目前只是一个空壳子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
final Surface mSurface = new Surface();

private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
boolean insetsPending) throws RemoteException {
...
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,
mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
mPendingStableInsets, mPendingOutsets, mPendingBackDropFrame,
mPendingMergedConfiguration, mSurface);
...
return relayoutResult;
}
WMS.relayoutWindow

Java层的SurfaceControl对应着C层的SurfaceControl,SurfaceControl负责与SF进行通信。

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
public int relayoutWindow(Session session, IWindow client, int seq,
WindowManager.LayoutParams attrs, int requestedWidth,
int requestedHeight, int viewVisibility, int flags,
Rect outFrame, Rect outOverscanInsets, Rect outContentInsets,
Rect outVisibleInsets, Rect outStableInsets, Rect outOutsets, Rect outBackdropFrame,
MergedConfiguration mergedConfiguration, Surface outSurface) {

synchronized(mWindowMap) {
WindowState win = windowForClientLocked(session, client, false);
...
if (shouldRelayout) {
...
try {
// 创建SurfaceControl对象,SurfaceControl对象负责与SF进行通信
result = createSurfaceControl(outSurface, result, win, winAnimator);
} catch (Exception e) {
...
return 0;
}

}
...
}

return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private int createSurfaceControl(Surface outSurface, int result, WindowState win,
WindowStateAnimator winAnimator) {

WindowSurfaceController surfaceController;
try {
// 创建Java层和C层SurfaceControl
surfaceController = winAnimator.createSurfaceLocked(win.mAttrs.type, win.mOwnerUid);
}
if (surfaceController != null) {
// 创建C层Surface,并关联Java层Surface
surfaceController.getSurface(outSurface);
}
return result;
}
创建SurfaceControl
创建Java层SurfaceControl
1
2
3
4
5
6
7
8
9
10
public SurfaceControl(SurfaceSession session, String name, int w, int h, int format, int flags,
SurfaceControl parent, int windowType, int ownerUid)
throws OutOfResourcesException {

mName = name;
// 创建C层SurfaceControl
mNativeObject = nativeCreate(session, name, w, h, format, flags,
parent != null ? parent.mNativeObject : 0, windowType, ownerUid);

}
创建C层SurfaceControl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static jlong nativeCreate(JNIEnv* env, jclass clazz, jobject sessionObj,
jstring nameStr, jint w, jint h, jint format, jint flags, jlong parentObject,
jint windowType, jint ownerUid) {
// 获取到SurfaceSession对象,用来与SF通信
sp<SurfaceComposerClient> client(android_view_SurfaceSession_getClient(env, sessionObj));
SurfaceControl *parent = reinterpret_cast<SurfaceControl*>(parentObject);
// 创建SurfaceControl
sp<SurfaceControl> surface = client->createSurface(
String8(name.c_str()), w, h, format, flags, parent, windowType, ownerUid);
if (surface == NULL) {
jniThrowException(env, OutOfResourcesException, NULL);
return 0;
}

surface->incStrong((void *)nativeCreate);
return reinterpret_cast<jlong>(surface.get());
}
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
sp<SurfaceControl> SurfaceComposerClient::createSurface(
const String8& name,
uint32_t w,
uint32_t h,
PixelFormat format,
uint32_t flags,
SurfaceControl* parent,
uint32_t windowType,
uint32_t ownerUid)
{
sp<SurfaceControl> sur;
if (mStatus == NO_ERROR) {
sp<IBinder> handle;
sp<IBinder> parentHandle;
sp<IGraphicBufferProducer> gbp;

if (parent != nullptr) {
parentHandle = parent->getHandle();
}
// 请求SF创建Layer,并返回该Layer的IGraphicBufferProducer
status_t err = mClient->createSurface(name, w, h, format, flags, parentHandle,
windowType, ownerUid, &handle, &gbp);
if (err == NO_ERROR) {
// 创建SurfaceControl,gbp对象会交给Surface对象,Surface对象通过gbp与Layer进行Buffer的通信
sur = new SurfaceControl(this, handle, gbp);
}
}
return sur;
}
SF.createLayer

在SurfaceFlinger中,Surface对应的概念叫Layer。

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
status_t SurfaceFlinger::createLayer(
const String8& name,
const sp<Client>& client,
uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
{

sp<Layer> layer;

String8 uniqueName = getUniqueLayerName(name);

switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
case ISurfaceComposerClient::eFXSurfaceNormal:
result = createNormalLayer(client,
uniqueName, w, h, flags, format,
handle, gbp, &layer);
break;
case ISurfaceComposerClient::eFXSurfaceDim:
result = createDimLayer(client,
uniqueName, w, h, flags,
handle, gbp, &layer);
break;
default:
result = BAD_VALUE;
break;
}
...
result = addClientLayer(client, *handle, *gbp, layer, *parent);
...
return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void Layer::onFirstRef() {
// Creates a custom BufferQueue for SurfaceFlingerConsumer to use
sp<IGraphicBufferProducer> producer;
sp<IGraphicBufferConsumer> consumer;
BufferQueue::createBufferQueue(&producer, &consumer, true);
// mProducer就是交给Surface中维护的gbp对象,所以Surface就是BufferQueue的生产者
mProducer = new MonitoredProducer(producer, mFlinger, this);
// 而SurfaceFlinger是BufferQueue的消费者
mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
mSurfaceFlingerConsumer->setContentsChangedListener(this);
mSurfaceFlingerConsumer->setName(mName);

if (mFlinger->isLayerTripleBufferingDisabled()) {
mProducer->setMaxDequeuedBufferCount(2);
}

const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
updateTransformHint(hw);
}
创建Surface
Surface.copyFrom

通过SurfaceControl创建C层的Surface,并关联到Java层Surface中。

最终创建完成后,SurfaceControl用SurfaceComposerClient与SurfaceFlinger通信。Surface用IGraphicBufferProducer与Layer进行通信。SurfaceControl由WindowManager来控制,而Surface由ViewRootImpl来控制。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void copyFrom(SurfaceControl other) {
...
long surfaceControlPtr = other.mNativeObject;

long newNativeObject = nativeGetFromSurfaceControl(surfaceControlPtr);

synchronized (mLock) {
if (mNativeObject != 0) {
nativeRelease(mNativeObject);
}
// 关联C层Surface
setNativeObjectLocked(newNativeObject);
}
}
1
2
3
4
5
6
7
8
9
10
static jlong nativeGetFromSurfaceControl(JNIEnv* env, jclass clazz,
jlong surfaceControlNativeObj) {
// 获取SurfaceControl对象
sp<SurfaceControl> ctrl(reinterpret_cast<SurfaceControl *>(surfaceControlNativeObj));
sp<Surface> surface(ctrl->getSurface());
if (surface != NULL) {
surface->incStrong(&sRefBaseOwner);
}
return reinterpret_cast<jlong>(surface.get());
}
1
2
3
4
5
6
7
8
9
sp<Surface> SurfaceControl::generateSurfaceLocked() const
{
// This surface is always consumed by SurfaceFlinger, so the
// producerControlledByApp value doesn't matter; using false.
// 将Layer中的生产者对象gbp交给Surface来维护,Surface通过该对象来与Layer通信。
mSurfaceData = new Surface(mGraphicBufferProducer, false);

return mSurfaceData;
}

ViewRootImpl.performDraw开始渲染

在setView时,就会根据window的属性来判断是否开启了硬件渲染,如果开启了则会创建ThreadedRenderer对象。

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
private boolean draw(boolean fullRedrawNeeded) {
Surface surface = mSurface;
...
final Rect dirty = mDirty;
...
if (!dirty.isEmpty() || mIsAnimating || accessibilityFocusDirty) {
// 硬件渲染
if (mAttachInfo.mThreadedRenderer != null && mAttachInfo.mThreadedRenderer.isEnabled()) {
// If accessibility focus moved, always invalidate the root.
boolean invalidateRoot = accessibilityFocusDirty || mInvalidateRootRequested;
mInvalidateRootRequested = false;

// Draw with hardware renderer.
mIsAnimating = false;

if (mHardwareYOffset != yOffset || mHardwareXOffset != xOffset) {
mHardwareYOffset = yOffset;
mHardwareXOffset = xOffset;
invalidateRoot = true;
}

if (invalidateRoot) {
mAttachInfo.mThreadedRenderer.invalidateRoot();
}

dirty.setEmpty();

// Stage the content drawn size now. It will be transferred to the renderer
// shortly before the draw commands get send to the renderer.
final boolean updated = updateContentDrawBounds();
...

if (updated) {
requestDrawWindow();
}

useAsyncReport = true;

mAttachInfo.mThreadedRenderer.draw(mView, mAttachInfo, this);
} else {
// 软件渲染

// If we get here with a disabled & requested hardware renderer, something went
// wrong (an invalidate posted right before we destroyed the hardware surface
// for instance) so we should just bail out. Locking the surface with software
// rendering at this point would lock it forever and prevent hardware renderer
// from doing its job when it comes back.
// Before we request a new frame we must however attempt to reinitiliaze the
// hardware renderer if it's in requested state. This would happen after an
// eglTerminate() for instance.
if (mAttachInfo.mThreadedRenderer != null &&
!mAttachInfo.mThreadedRenderer.isEnabled() &&
mAttachInfo.mThreadedRenderer.isRequested() &&
mSurface.isValid()) {
// 在ThreadedRenderer初始化之前,其isEnabled方法都返回false。
// 所以在ThreadedRenderer.isRequested为true的时候,尝试初始化ThreadedRenderer,重新开始一次绘制。
try {
mAttachInfo.mThreadedRenderer.initializeIfNeeded(
mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets);
} catch (OutOfResourcesException e) {
handleOutOfResourcesException(e);
return false;
}

mFullRedrawNeeded = true;
scheduleTraversals();
return false;
}

if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset,
scalingRequired, dirty, surfaceInsets)) {
return false;
}
}
}

if (animating) {
mFullRedrawNeeded = true;
scheduleTraversals();
}
return useAsyncReport;
}
ThreadedRenderer.draw硬件渲染
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
void draw(View view, AttachInfo attachInfo, DrawCallbacks callbacks) {
final Choreographer choreographer = attachInfo.mViewRootImpl.mChoreographer;
choreographer.mFrameInfo.markDrawStart();

updateRootDisplayList(view, callbacks);

// register animating rendernodes which started animating prior to renderer
// creation, which is typical for animators started prior to first draw
if (attachInfo.mPendingAnimatingRenderNodes != null) {
final int count = attachInfo.mPendingAnimatingRenderNodes.size();
for (int i = 0; i < count; i++) {
registerAnimatingRenderNode(
attachInfo.mPendingAnimatingRenderNodes.get(i));
}
attachInfo.mPendingAnimatingRenderNodes.clear();
// We don't need this anymore as subsequent calls to
// ViewRootImpl#attachRenderNodeAnimator will go directly to us.
attachInfo.mPendingAnimatingRenderNodes = null;
}

int syncResult = syncAndDrawFrame(choreographer.mFrameInfo);
if ((syncResult & SYNC_LOST_SURFACE_REWARD_IF_FOUND) != 0) {
setEnabled(false);
attachInfo.mViewRootImpl.mSurface.release();
// Invalidate since we failed to draw. This should fetch a Surface
// if it is still needed or do nothing if we are no longer drawing
attachInfo.mViewRootImpl.invalidate();
}
if ((syncResult & SYNC_REDRAW_REQUESTED) != 0) {
attachInfo.mViewRootImpl.invalidate();
}
}
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
private void updateRootDisplayList(View view, DrawCallbacks callbacks) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "Record View#draw()");
updateViewTreeDisplayList(view);

// Consume and set the frame callback after we dispatch draw to the view above, but before
// onPostDraw below which may reset the callback for the next frame. This ensures that
// updates to the frame callback during scroll handling will also apply in this frame.
final FrameDrawingCallback callback = mNextRtFrameCallback;
mNextRtFrameCallback = null;
if (callback != null) {
setFrameCallback(callback);
}

if (mRootNodeNeedsUpdate || !mRootNode.hasDisplayList()) {
RecordingCanvas canvas = mRootNode.beginRecording(mSurfaceWidth, mSurfaceHeight);
try {
final int saveCount = canvas.save();
canvas.translate(mInsetLeft, mInsetTop);
callbacks.onPreDraw(canvas);

canvas.enableZ();
canvas.drawRenderNode(view.updateDisplayListIfDirty());
canvas.disableZ();

callbacks.onPostDraw(canvas);
canvas.restoreToCount(saveCount);
mRootNodeNeedsUpdate = false;
} finally {
mRootNode.endRecording();
}
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
syncAndDrawFrame
CanvasContext.create

ThreadedRenderer创建的时候,会对应创建一个C层的RenderProxy对象,在RenderProxy对象中会维护一个CanvasContext的上下文对象。

会根据renderType创建基于OpenGL-ES的Pipeline或者基于Vulkan的Pipeline。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
CanvasContext* CanvasContext::create(RenderThread& thread, bool translucent,
RenderNode* rootRenderNode, IContextFactory* contextFactory) {
auto renderType = Properties::getRenderPipelineType();

switch (renderType) {
case RenderPipelineType::SkiaGL:
return new CanvasContext(thread, translucent, rootRenderNode, contextFactory,
std::make_unique<skiapipeline::SkiaOpenGLPipeline>(thread));
case RenderPipelineType::SkiaVulkan:
return new CanvasContext(thread, translucent, rootRenderNode, contextFactory,
std::make_unique<skiapipeline::SkiaVulkanPipeline>(thread));
default:
LOG_ALWAYS_FATAL("canvas context type %d not supported", (int32_t)renderType);
break;
}
return nullptr;
}
CanvasContext.setSurface

ThreadedRenderer初始化的时候,会将ViewRootImpl中的Surface对象传递给CanvasContext。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void CanvasContext::setSurface(sp<Surface>&& surface) {
if (surface) {
// 创建一个Surface的包装类
mNativeSurface = new ReliableSurface{std::move(surface)};
// TODO: Fix error handling & re-shorten timeout
mNativeSurface->setDequeueTimeout(4000_ms);
} else {
mNativeSurface = nullptr;
}
...
// 是否开启了广色域RGB色彩空间
ColorMode colorMode = mWideColorGamut ? ColorMode::WideColorGamut : ColorMode::SRGB;
bool hasSurface = mRenderPipeline->setSurface(mNativeSurface.get(), mSwapBehavior, colorMode,
mRenderAheadCapacity);

...
}

RenderPipeline就是上面根据RenderType创建的pipeline对象。在OpenGLPileline中,初始化EglContext,然后根据Surface创建对应的EglSurface。

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
bool SkiaOpenGLPipeline::setSurface(ANativeWindow* surface, SwapBehavior swapBehavior,
ColorMode colorMode, uint32_t extraBuffers) {
if (mEglSurface != EGL_NO_SURFACE) {
mEglManager.destroySurface(mEglSurface);
mEglSurface = EGL_NO_SURFACE;
}

setSurfaceColorProperties(colorMode);

if (surface) {
// 初始化EglContext
mRenderThread.requireGlContext();
// 创建EglSurface
auto newSurface = mEglManager.createSurface(surface, colorMode, mSurfaceColorSpace);
if (!newSurface) {
return false;
}
mEglSurface = newSurface.unwrap();
}

if (mEglSurface != EGL_NO_SURFACE) {
const bool preserveBuffer = (swapBehavior != SwapBehavior::kSwap_discardBuffer);
mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer);
setBufferCount(surface, extraBuffers);
return true;
}

return false;
}

初始化EGL

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
void EglManager::initialize() {
...
// 获取EglDisplay
mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY, "Failed to get EGL_DEFAULT_DISPLAY! err=%s",
eglErrorString());

EGLint major, minor;
// 初始化EGL
LOG_ALWAYS_FATAL_IF(eglInitialize(mEglDisplay, &major, &minor) == EGL_FALSE,
"Failed to initialize display %p! err=%s", mEglDisplay, eglErrorString());

initExtensions();

// Now that extensions are loaded, pick a swap behavior
if (Properties::enablePartialUpdates) {
// An Adreno driver bug is causing rendering problems for SkiaGL with
// buffer age swap behavior (b/31957043). To temporarily workaround,
// we will use preserved swap behavior.
if (Properties::useBufferAge && EglExtensions.bufferAge) {
mSwapBehavior = SwapBehavior::BufferAge;
} else {
mSwapBehavior = SwapBehavior::Preserved;
}
}
// 加载EglConfig
loadConfigs();
// 创建EglContext
createContext();
// 创建用于离屏渲染的surface,pbuffer_surface。
// OpenGL-ES的surface一共有三种 window_surface、pbuffer_surface、pixmap_surface。EGL 和 OpenGL ES 支持两种绘制模式,back buffer和single buffer,window_surface和pbuffer_surface都是使用的back buffer,顾名思义,也就是一块GPU中的 buffer,当绘制完毕的时候,由于window_surface与nativewindow有关联,那么可以使用eglswapbuffer 将其转移到nativewindow上进行显示。而pbuffer_surface与nativewindow没有关联,也就无法显示。
createPBufferSurface();
// 将mPBufferSurface与EglDisplay与EglContext进行关联。在当前线程中激活mPBufferSurface。
makeCurrent(mPBufferSurface, nullptr, /* force */ true);
...
mHasWideColorGamutSupport = EglExtensions.glColorSpace && hasWideColorSpaceExtension &&
mEglConfigWideGamut != EGL_NO_CONFIG_KHR;
}

创建EglSurface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Result<EGLSurface, EGLint> EglManager::createSurface(EGLNativeWindowType window,
ColorMode colorMode,
sk_sp<SkColorSpace> colorSpace) {

bool wideColorGamut = colorMode == ColorMode::WideColorGamut && mHasWideColorGamutSupport &&
EglExtensions.noConfigContext;

EGLint attribs[] = {EGL_NONE, EGL_NONE, EGL_NONE};
...
// 根据Surface创建OpenGL-ES的surface,类型为window_surface
EGLSurface surface = eglCreateWindowSurface(
mEglDisplay, wideColorGamut ? mEglConfigWideGamut : mEglConfig, window, attribs);

...

return surface;
}
CanvasContext.draw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void CanvasContext::draw() {
SkRect dirty;
...
Frame frame = mRenderPipeline->getFrame();
setPresentTime();

SkRect windowDirty = computeDirtyRect(frame, &dirty);
// 绘制缓冲区
bool drew = mRenderPipeline->draw(frame, windowDirty, dirty, mLightGeometry, &mLayerUpdateQueue,
mContentDrawBounds, mOpaque, mLightInfo, mRenderNodes,
&(profiler()));

...
bool requireSwap = false;
// 将EglSurface中的缓冲区交换给Surface,由SurfaceFlinger消费。
bool didSwap =
mRenderPipeline->swapBuffers(frame, drew, windowDirty, mCurrentFrameInfo, &requireSwap);
...
}

SkiaOpenGLPipeline.draw

在draw方法调用之前,会调用makeCurrent方法,将上面创建的EglSurface激活。后续所有的GL操作都将作用在该EglSurface上。

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
51
52
bool SkiaOpenGLPipeline::draw(const Frame& frame, const SkRect& screenDirty, const SkRect& dirty,
const LightGeometry& lightGeometry,
LayerUpdateQueue* layerUpdateQueue, const Rect& contentDrawBounds,
bool opaque, const LightInfo& lightInfo,
const std::vector<sp<RenderNode>>& renderNodes,
FrameInfoVisualizer* profiler) {
mEglManager.damageFrame(frame, dirty);

SkColorType colorType = getSurfaceColorType();
// setup surface for fbo0
GrGLFramebufferInfo fboInfo;
fboInfo.fFBOID = 0;
if (colorType == kRGBA_F16_SkColorType) {
fboInfo.fFormat = GL_RGBA16F;
} else if (colorType == kN32_SkColorType) {
// Note: The default preference of pixel format is RGBA_8888, when other
// pixel format is available, we should branch out and do more check.
fboInfo.fFormat = GL_RGBA8;
} else {
LOG_ALWAYS_FATAL("Unsupported color type.");
}

GrBackendRenderTarget backendRT(frame.width(), frame.height(), 0, STENCIL_BUFFER_SIZE, fboInfo);

SkSurfaceProps props(0, kUnknown_SkPixelGeometry);

SkASSERT(mRenderThread.getGrContext() != nullptr);
sk_sp<SkSurface> surface(SkSurface::MakeFromBackendRenderTarget(
mRenderThread.getGrContext(), backendRT, this->getSurfaceOrigin(), colorType,
mSurfaceColorSpace, &props));

SkiaPipeline::updateLighting(lightGeometry, lightInfo);
renderFrame(*layerUpdateQueue, dirty, renderNodes, opaque, contentDrawBounds, surface,
SkMatrix::I());
layerUpdateQueue->clear();

// Draw visual debugging features
if (CC_UNLIKELY(Properties::showDirtyRegions ||
ProfileType::None != Properties::getProfileType())) {
SkCanvas* profileCanvas = surface->getCanvas();
SkiaProfileRenderer profileRenderer(profileCanvas);
profiler->draw(profileRenderer);
profileCanvas->flush();
}

// Log memory statistics
if (CC_UNLIKELY(Properties::debugLevel != kDebugDisabled)) {
dumpResourceCacheUsage();
}

return true;
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×