Android14 SurfaceFlinger Surface的创建

发布时间:2024年01月24日

viewRootImpl中有两个成员变量, 这两个变量是何时创建的, 又是何时生效的.下面我们来分析一下

ViewRootImpl.java    
@UnsupportedAppUsage
    public final Surface mSurface = new Surface();
    private final SurfaceControl mSurfaceControl = new SurfaceControl();

由relayout开始?, 首先经过WMS生成一个native的surfaceControl, 然后copy到viewRootImpl, 即mSurfaceControl

调用栈如下:

12-26 14:11:35.802  3617  6129 D jinyanmeisurface: createSurfaceChecked 
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #00 pc 0000000000105b9c  /system/lib64/libgui.so (android::SurfaceComposerClient::createSurfaceChecked(android::String8 const&, unsigned int, unsigned int, int, android::sp<android::SurfaceControl>*, int, android::sp<android::IBinder> const&, android::gui::LayerMetadata, unsigned int*)+180) (BuildId: b9005239b9414ac2dd1f0c985d49963e)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #01 pc 000000000016050c  /system/lib64/libandroid_runtime.so (android::nativeCreate(_JNIEnv*, _jclass*, _jobject*, _jstring*, int, int, int, int, long, _jobject*)+488) (BuildId: 4da5841894b299034a53a5787188d8a4)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #02 pc 0000000000227430  /apex/com.android.art/lib64/libart.so (art_quick_generic_jni_trampoline+144) (BuildId: 0b4dbd5fb17d65be6fcad4d7aaa0ef1b)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #03 pc 000000000020a28c  /apex/com.android.art/lib64/libart.so (nterp_helper+3852) (BuildId: 0b4dbd5fb17d65be6fcad4d7aaa0ef1b)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #04 pc 00000000001d254c  /system/framework/framework.jar (android.view.SurfaceControl.<init>+316)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #05 pc 000000000020a9d8  /apex/com.android.art/lib64/libart.so (nterp_helper+5720) (BuildId: 0b4dbd5fb17d65be6fcad4d7aaa0ef1b)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #06 pc 00000000001d25d8  /system/framework/framework.jar (android.view.SurfaceControl.<init>)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #07 pc 000000000020a9d8  /apex/com.android.art/lib64/libart.so (nterp_helper+5720) (BuildId: 0b4dbd5fb17d65be6fcad4d7aaa0ef1b)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #08 pc 00000000001cd3b0  /system/framework/framework.jar (android.view.SurfaceControl$Builder.build+148)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #09 pc 000000000020a2d4  /apex/com.android.art/lib64/libart.so (nterp_helper+3924) (BuildId: 0b4dbd5fb17d65be6fcad4d7aaa0ef1b)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #10 pc 0000000000151560  /system/framework/services.jar (com.android.server.wm.WindowSurfaceController.<init>+236)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #11 pc 000000000020a9d8  /apex/com.android.art/lib64/libart.so (nterp_helper+5720) (BuildId: 0b4dbd5fb17d65be6fcad4d7aaa0ef1b)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #12 pc 0000000000147584  /system/framework/services.jar (com.android.server.wm.WindowStateAnimator.createSurfaceLocked+220)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #13 pc 000000000020a2d4  /apex/com.android.art/lib64/libart.so (nterp_helper+3924) (BuildId: 0b4dbd5fb17d65be6fcad4d7aaa0ef1b)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #14 pc 000000000012e226  /system/framework/services.jar (com.android.server.wm.WindowManagerService.createSurfaceControl+26)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #15 pc 000000000211ccf4  /memfd:jit-cache (deleted) (offset 0x2000000) (com.android.server.wm.WindowManagerService.relayoutWindow+5972)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #16 pc 000000000020aa58  /apex/com.android.art/lib64/libart.so (nterp_helper+5848) (BuildId: 0b4dbd5fb17d65be6fcad4d7aaa0ef1b)
12-26 14:11:35.866  3617  6129 D jinyanmeisurface:   #17 pc 00000000000ebd2a  /system/framework/services.jar (com.android.server.wm.Session.relayout+82)

这里的SurfaceSession为addWindow时调用win.attach时创建的WMS和SurfaceFlinger的连接?

也会创建一个SurfaceComposerClient对象来连接到SurfaceFlinger。

5331      @Override
5332      SurfaceControl.Builder makeChildSurface(WindowContainer child) {
5333          SurfaceSession s = child != null ? child.getSession() : getSession();
5334          final SurfaceControl.Builder b = mWmService.makeSurfaceBuilder(s).setContainerLayer();
5335          if (child == null) {
5336              return b;
5337          }
5338  
5339          // WARNING: it says `mSurfaceControl` below, but this CHANGES meaning after construction!
5340          // DisplayAreas are added in `configureSurface()` *before* `mSurfaceControl` gets replaced
5341          // with a wrapper or magnification surface so they end up in the right place; however,
5342          // anything added or reparented to "the display" *afterwards* needs to be reparented to
5343          // `getWindowinglayer()` (unless it's an overlay DisplayArea).
5344          return b.setName(child.getName())
5345                  .setParent(mSurfaceControl);
5346      }

SurfaceComposerClient的成员变量mClient是一个BpSurfaceComposerClient类型的Binder代理对象,它的服务端实现是在SurfaceFlinger服务的Client类,那么这里最终是调用了服务端Client.createSurface函数

libs/gui/SurfaceComposerClient.cpp
2412  status_t SurfaceComposerClient::createSurfaceChecked(const String8& name, uint32_t w, uint32_t h,
2413                                                       PixelFormat format,
2414                                                       sp<SurfaceControl>* outSurface, int32_t flags,
2415                                                       const sp<IBinder>& parentHandle,
2416                                                       LayerMetadata metadata,
2417                                                       uint32_t* outTransformHint) {
2418      sp<SurfaceControl> sur;
2419      status_t err = mStatus;
2420  
2421      if (mStatus == NO_ERROR) {
2422          gui::CreateSurfaceResult result;
2423          binder::Status status = mClient->createSurface(std::string(name.string()), flags,
2424                                                         parentHandle, std::move(metadata), &result);
2425          err = statusTFromBinderStatus(status);
2426          if (outTransformHint) {
2427              *outTransformHint = result.transformHint;
2428          }
2429          ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err));
2430          if (err == NO_ERROR) {
2431              *outSurface = new SurfaceControl(this, result.handle, result.layerId,
2432                                               toString(result.layerName), w, h, format,
2433                                               result.transformHint, flags);
2434          }
2435      }
2436      return err;
2437  }

?已知在Client内部是通过一个sp<SurfaceFlinger>类型的成员变量mFlinger是一个SurfaceFlinger类型的强指针,那么这里调用的即是SurfaceFlinger.createLayer。

Client.cpp
51  binder::Status Client::createSurface(const std::string& name, int32_t flags,
52                                       const sp<IBinder>& parent, const gui::LayerMetadata& metadata,
53                                       gui::CreateSurfaceResult* outResult) {
54      // We rely on createLayer to check permissions.
55      sp<IBinder> handle;
56      LayerCreationArgs args(mFlinger.get(), sp<Client>::fromExisting(this), name.c_str(),
57                             static_cast<uint32_t>(flags), std::move(metadata));
58      args.parentHandle = parent;
59      const status_t status = mFlinger->createLayer(args, *outResult);
60      return binderStatusFromStatusT(status);
61  }
SurfaceFlinger.cpp
5337  status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, gui::CreateSurfaceResult& outResult) {
5338      status_t result = NO_ERROR;
5339  
5340      sp<Layer> layer;
5341  
5342      switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
5343          case ISurfaceComposerClient::eFXSurfaceBufferQueue:
5344          case ISurfaceComposerClient::eFXSurfaceContainer:
5345          case ISurfaceComposerClient::eFXSurfaceBufferState:
5346              args.flags |= ISurfaceComposerClient::eNoColorFill;
5347              FMT_FALLTHROUGH;
5348          case ISurfaceComposerClient::eFXSurfaceEffect: {
5349              result = createBufferStateLayer(args, &outResult.handle, &layer);
5350              std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
5351              if (pendingBufferCounter) {
5352                  std::string counterName = layer->getPendingBufferCounterName();
5353                  mBufferCountTracker.add(outResult.handle->localBinder(), counterName,
5354                                          pendingBufferCounter);
5355              }
5356          } break;
5357          default:
5358              result = BAD_VALUE;
5359              break;
5360      }
5361  
5362      if (result != NO_ERROR) {
5363          return result;
5364      }
5365  
5366      args.addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
5367      // We can safely promote the parent layer in binder thread because we have a strong reference
5368      // to the layer's handle inside this scope.
5369      sp<Layer> parent = LayerHandle::getLayer(args.parentHandle.promote());
5370      if (args.parentHandle != nullptr && parent == nullptr) {
5371          ALOGE("Invalid parent handle %p", args.parentHandle.promote().get());
5372          args.addToRoot = false;
5373      }
5374  
5375      uint32_t outTransformHint;
5376      result = addClientLayer(args, outResult.handle, layer, parent, &outTransformHint);
5377      if (result != NO_ERROR) {
5378          return result;
5379      }
5380  
5381      outResult.transformHint = static_cast<int32_t>(outTransformHint);
5382      outResult.layerId = layer->sequence;
5383      outResult.layerName = String16(layer->getDebugName());
5384      return result;
5385  }
5386  

这样就通过copyForm的方式使ViewRootImpl拿到了native的引用

WindowSurfaceController
    void getSurfaceControl(SurfaceControl outSurfaceControl) {
        outSurfaceControl.copyFrom(mSurfaceControl, "WindowSurfaceController.getSurfaceControl");
    }

由生成的SurfaceControl生成BLASTBufferQueue

BLASTBufferQueue生成Surface即mSurface

    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
            boolean insetsPending) throws RemoteException {

            relayoutResult = mWindowSession.relayout(mWindow, params,
                    requestedWidth, requestedHeight, viewVisibility,
                    insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, mRelayoutSeq,
                    mLastSyncSeqId, mTmpFrames, mPendingMergedConfiguration, mSurfaceControl,
                    mTempInsets, mTempControls, mRelayoutBundle);

 if (mSurfaceControl.isValid()) {
            if (!useBLAST()) {
                mSurface.copyFrom(mSurfaceControl);
            } else {
                updateBlastSurfaceIfNeeded();
            }

mSurfaceControl的初始化?

从relayoutWindow开始

2175      public int relayoutWindow(Session session, IWindow client, LayoutParams attrs,
2176              int requestedWidth, int requestedHeight, int viewVisibility, int flags, int seq,
2177              int lastSyncSeqId, ClientWindowFrames outFrames,
2178              MergedConfiguration outMergedConfiguration, SurfaceControl outSurfaceControl,
2179              InsetsState outInsetsState, InsetsSourceControl.Array outActiveControls,
2180              Bundle outSyncIdBundle) {

2394              if (shouldRelayout && outSurfaceControl != null) {
2395                  try {
2396                      result = createSurfaceControl(outSurfaceControl, result, win, winAnimator);
2397                  } catch (Exception e) {
2398                      displayContent.getInputMonitor().updateInputWindowsLw(true /*force*/);
2399  
2400                      ProtoLog.w(WM_ERROR,
2401                              "Exception thrown when creating surface for client %s (%s). %s",
2402                              client, win.mAttrs.getTitle(), e);
2403                      Binder.restoreCallingIdentity(origId);
2404                      return 0;
2405                  }
2406              }

mSurface的初始化

    void updateBlastSurfaceIfNeeded() {
        if (!mSurfaceControl.isValid()) {
            return;
        }

        if (mBlastBufferQueue != null && mBlastBufferQueue.isSameSurfaceControl(mSurfaceControl)) {
            mBlastBufferQueue.update(mSurfaceControl,
                mSurfaceSize.x, mSurfaceSize.y,
                mWindowAttributes.format);
            return;
        }

        // If the SurfaceControl has been updated, destroy and recreate the BBQ to reset the BQ and
        // BBQ states.
        if (mBlastBufferQueue != null) {
            mBlastBufferQueue.destroy();
        }
        mBlastBufferQueue = new BLASTBufferQueue(mTag, mSurfaceControl,
                mSurfaceSize.x, mSurfaceSize.y, mWindowAttributes.format);
        mBlastBufferQueue.setTransactionHangCallback(sTransactionHangCallback);
        Surface blastSurface = mBlastBufferQueue.createSurface();
        // Only call transferFrom if the surface has changed to prevent inc the generation ID and
        // causing EGL resources to be recreated.
        mSurface.transferFrom(blastSurface);
    }

由SurfaceControl作为参数BLASTBufferQueue初始化

?构造函数,首先创建了消费者生产者模型

147  BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
148        : mSurfaceControl(nullptr),
149          mSize(1, 1),
150          mRequestedSize(mSize),
151          mFormat(PIXEL_FORMAT_RGBA_8888),
152          mTransactionReadyCallback(nullptr),
153          mSyncTransaction(nullptr),
154          mUpdateDestinationFrame(updateDestinationFrame) {
155      createBufferQueue(&mProducer, &mConsumer);
156      // since the adapter is in the client process, set dequeue timeout
157      // explicitly so that dequeueBuffer will block
//设置了Dequeue的超时时间
158      mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
159  
160      // safe default, most producers are expected to override this
// 设置了最大缓冲数量
161      mProducer->setMaxDequeuedBufferCount(2);
// 初始化图形缓冲区消费者
162      mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
163                                                        GraphicBuffer::USAGE_HW_COMPOSER |
164                                                                GraphicBuffer::USAGE_HW_TEXTURE,
165                                                        1, false, this);
166      static std::atomic<uint32_t> nextId = 0;
167      mProducerId = nextId++;
168      mName = name + "#" + std::to_string(mProducerId);
169      auto consumerName = mName + "(BLAST Consumer)" + std::to_string(mProducerId);
170      mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(mProducerId);
// 设置图形缓冲区消费者名字
171      mBufferItemConsumer->setName(String8(consumerName.c_str()));
// 设置如队监听
172      mBufferItemConsumer->setFrameAvailableListener(this);
173  
174      ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
// 通过SF端计算并获取最大可消费缓冲区数量
175      mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
176      mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
177      mNumAcquired = 0;
178      mNumFrameAvailable = 0;
179  
180      TransactionCompletedListener::getInstance()->addQueueStallListener(
181              [&](const std::string& reason) {
182                  std::function<void(const std::string&)> callbackCopy;
183                  {
184                      std::unique_lock _lock{mMutex};
185                      callbackCopy = mTransactionHangCallback;
186                  }
187                  if (callbackCopy) callbackCopy(reason);
188              },
189              this);
190  
191      BQA_LOGV("BLASTBufferQueue created");
192  }

createBufferQueue 创建了

BufferQueueCore,?BBQBufferQueueProducer,BufferQueueConsumer

BufferQueueCore负责缓冲区的调度工作

BBQBufferQueueProducer 生产者

BufferQueueConsumer消费者

void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
                                         sp<IGraphicBufferConsumer>* outConsumer) {
    LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
    LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
    ALOGJIN("createBufferQueue ");
    ALOGV("increasing frame history size to" );
    android::CallStack stack(LOG_TAGJINYANMEI);
    sp<BufferQueueCore> core(new BufferQueueCore());
    LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");




    sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core, this));
    LOG_ALWAYS_FATAL_IF(producer == nullptr,
                        "BLASTBufferQueue: failed to create BBQBufferQueueProducer");

    sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
    consumer->setAllowExtraAcquire(true);
    LOG_ALWAYS_FATAL_IF(consumer == nullptr,
                        "BLASTBufferQueue: failed to create BufferQueueConsumer");

    *outProducer = producer;
    *outConsumer = consumer;
}

由BLASTBufferQueue创建Surface

BLASTBufferQueue::getSurface方法中会去创建一个BBQSurface, 这个类继承自Surface,其中保存了对应layer的handle?

953  sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
954      std::lock_guard _lock{mMutex};
955      sp<IBinder> scHandle = nullptr;
956      if (includeSurfaceControlHandle && mSurfaceControl) {
957          scHandle = mSurfaceControl->getHandle();
958      }
959      return new BBQSurface(mProducer, true, scHandle, this);
960  }
961  
    BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
               const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
          : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}


76  Surface::Surface(const sp<IGraphicBufferProducer>& bufferProducer, bool controlledByApp,
77                   const sp<IBinder>& surfaceControlHandle)
78        : mGraphicBufferProducer(bufferProducer),

其中传入的参数有图形缓冲区生产者,

SurfaceControl句柄,? 上一步createSurface构建的

总结

ViewRootImpl通过WMS创建surfaceControl
然后通过surfaceControl创建BLASTBufferQueue
让后通过BLASTBufferQueue.createSurface生成一个BBQSurface, 继承与Surface, 也就是创建了Surface, 最后返回给mSurface.

BLASTBufferQueue是连接生产者和消费者的纽带
文章来源:https://blog.csdn.net/u012627628/article/details/135750688
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。