// mSlots is an array of buffer slots that must be mirrored on the producer
// side. This allows buffer ownership to be transferred between the producer
// and consumer without sending a GraphicBuffer over Binder. The entire
// array is initialized to NULL at construction time, and buffers are
// allocated for a slot when requestBuffer is called with that slot's index.
BufferQueueDefs::SlotsTypemSlots;// mQueue is a FIFO of queued buffers used in synchronous mode.
FifomQueue;// mFreeSlots contains all of the slots which are FREE and do not currently
// have a buffer attached.
std::set<int>mFreeSlots;// mFreeBuffers contains all of the slots which are FREE and currently have
// a buffer attached.
std::list<int>mFreeBuffers;// mUnusedSlots contains all slots that are currently unused. They should be
// free and not have a buffer attached.
std::list<int>mUnusedSlots;// mActiveBuffers contains all slots which have a non-FREE buffer attached.
std::set<int>mActiveBuffers;
// BufferState tracks the states in which a buffer slot can be.
structBufferState{// All slots are initially FREE (not dequeued, queued, acquired, or shared).
BufferState():mDequeueCount(0),mQueueCount(0),mAcquireCount(0),mShared(false){}uint32_tmDequeueCount;uint32_tmQueueCount;uint32_tmAcquireCount;boolmShared;// A buffer can be in one of five states, represented as below:
//
// | mShared | mDequeueCount | mQueueCount | mAcquireCount |
// --------|---------|---------------|-------------|---------------|
// FREE | false | 0 | 0 | 0 |
// DEQUEUED| false | 1 | 0 | 0 |
// QUEUED | false | 0 | 1 | 0 |
// ACQUIRED| false | 0 | 0 | 1 |
// SHARED | true | any | any | any |
//
// FREE indicates that the buffer is available to be dequeued by the
// producer. The slot is "owned" by BufferQueue. It transitions to DEQUEUED
// when dequeueBuffer is called.
//
// DEQUEUED indicates that the buffer has been dequeued by the producer, but
// has not yet been queued or canceled. The producer may modify the
// buffer's contents as soon as the associated release fence is signaled.
// The slot is "owned" by the producer. It can transition to QUEUED (via
// queueBuffer or attachBuffer) or back to FREE (via cancelBuffer or
// detachBuffer).
//
// QUEUED indicates that the buffer has been filled by the producer and
// queued for use by the consumer. The buffer contents may continue to be
// modified for a finite time, so the contents must not be accessed until
// the associated fence is signaled. The slot is "owned" by BufferQueue. It
// can transition to ACQUIRED (via acquireBuffer) or to FREE (if another
// buffer is queued in asynchronous mode).
//
// ACQUIRED indicates that the buffer has been acquired by the consumer. As
// with QUEUED, the contents must not be accessed by the consumer until the
// acquire fence is signaled. The slot is "owned" by the consumer. It
// transitions to FREE when releaseBuffer (or detachBuffer) is called. A
// detached buffer can also enter the ACQUIRED state via attachBuffer.
//
// SHARED indicates that this buffer is being used in shared buffer
// mode. It can be in any combination of the other states at the same time,
// except for FREE (since that excludes being in any other state). It can
// also be dequeued, queued, or acquired multiple times.
status_tBufferQueueProducer::dequeueBuffer(int*outSlot,sp<android::Fence>*outFence,uint32_twidth,uint32_theight,PixelFormatformat,uint64_tusage,uint64_t*outBufferAge,FrameEventHistoryDelta*outTimestamps){//省略
intfound=BufferItem::INVALID_BUFFER_SLOT;//作为入参found
while(found==BufferItem::INVALID_BUFFER_SLOT){//核心方法从mSlots数组找到一个可以用的BufferSlot,把相关的index赋值到found这个变量
status_tstatus=waitForFreeSlotThenRelock(FreeSlotCaller::Dequeue,lock,&found);//省略
}ATRACE_FORMAT("dequeueBuffer found = %d",found);constsp<GraphicBuffer>&buffer(mSlots[found].mGraphicBuffer);*outSlot=found;ATRACE_BUFFER_INDEX(found);attachedByConsumer=mSlots[found].mNeedsReallocation;mSlots[found].mNeedsReallocation=false;mSlots[found].mBufferState.dequeue();//把状态变成Dequeue
if((buffer==nullptr)||buffer->needsReallocation(width,height,format,BQ_LAYER_COUNT,usage)){//如果需要进行buffer申请
returnFlags|=BUFFER_NEEDS_REALLOCATION;}else{// We add 1 because that will be the frame number when this buffer
// is queued
mCore->mBufferAge=mCore->mFrameCounter+1-mSlots[found].mFrameNumber;}//省略部分
if(!(returnFlags&BUFFER_NEEDS_REALLOCATION)){//不需要allocation
if(mCore->mConsumerListener!=nullptr){//通知回调一下consumeronFrameDequeued
mCore->mConsumerListener->onFrameDequeued(mSlots[*outSlot].mGraphicBuffer->getId());}}}// Autolock scope
if(returnFlags&BUFFER_NEEDS_REALLOCATION){//开始申请GraphicBuffer
sp<GraphicBuffer>graphicBuffer=newGraphicBuffer(width,height,format,BQ_LAYER_COUNT,usage,{mConsumerName.string(),mConsumerName.size()});status_terror=graphicBuffer->initCheck();//申请GraphicBuffer成功
if(error==NO_ERROR&&!mCore->mIsAbandoned){graphicBuffer->setGenerationNumber(mCore->mGenerationNumber);//把申请成功的buffer赋值到了mSlots的mGraphicBuffer中
mSlots[*outSlot].mGraphicBuffer=graphicBuffer;if(mCore->mConsumerListener!=nullptr){mCore->mConsumerListener->onFrameDequeued(mSlots[*outSlot].mGraphicBuffer->getId());}}}// Autolock scope
}//省略
returnreturnFlags;}
status_tBufferQueueProducer::waitForFreeSlotThenRelock(FreeSlotCallercaller,std::unique_lock<std::mutex>&lock,int*found)const{while(tryAgain){intdequeuedCount=0;intacquiredCount=0;for(ints:mCore->mActiveBuffers){if(mSlots[s].mBufferState.isDequeued()){++dequeuedCount;}if(mSlots[s].mBufferState.isAcquired()){++acquiredCount;}}*found=BufferQueueCore::INVALID_BUFFER_SLOT;//省略部分
if(tooManyBuffers){}else{// If in shared buffer mode and a shared buffer exists, always
// return it.
if(mCore->mSharedBufferMode&&mCore->mSharedBufferSlot!=BufferQueueCore::INVALID_BUFFER_SLOT){*found=mCore->mSharedBufferSlot;}else{if(caller==FreeSlotCaller::Dequeue){//如果dequeue方法
// If we're calling this from dequeue, prefer free buffers
intslot=getFreeBufferLocked();//先从FreeBuffer的数组中获取
if(slot!=BufferQueueCore::INVALID_BUFFER_SLOT){*found=slot;}elseif(mCore->mAllowAllocation){//如果没有找到则到FreeSlot数组中找
*found=getFreeSlotLocked();}}else{// If we're calling this from attach, prefer free slots
intslot=getFreeSlotLocked();//先从FreeSlot数组中找
if(slot!=BufferQueueCore::INVALID_BUFFER_SLOT){*found=slot;}else{//没找到再去FreeBuffer中找
*found=getFreeBufferLocked();}}}}//省略
returnNO_ERROR;}intBufferQueueProducer::getFreeSlotLocked()const{if(mCore->mFreeSlots.empty()){returnBufferQueueCore::INVALID_BUFFER_SLOT;}intslot=*(mCore->mFreeSlots.begin());mCore->mFreeSlots.erase(slot);returnslot;}
//注意传递参数里面有一个关键的slot即mSlots中的index
status_tBufferQueueProducer::queueBuffer(intslot,constQueueBufferInput&input,QueueBufferOutput*output){BufferItemitem;{mSlots[slot].mFence=acquireFence;mSlots[slot].mBufferState.queue();//这个地方就会调用mBufferState的queue,状态就改变了
//开始把mSlots[slot]挨个赋值给BufferItem
item.mAcquireCalled=mSlots[slot].mAcquireCalled;item.mGraphicBuffer=mSlots[slot].mGraphicBuffer;item.mCrop=crop;item.mTransform=transform&~static_cast<uint32_t>(NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);item.mTransformToDisplayInverse=(transform&NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY)!=0;item.mScalingMode=static_cast<uint32_t>(scalingMode);item.mTimestamp=requestedPresentTimestamp;item.mIsAutoTimestamp=isAutoTimestamp;item.mDataSpace=dataSpace;item.mHdrMetadata=hdrMetadata;item.mFrameNumber=currentFrameNumber;item.mSlot=slot;item.mFence=acquireFence;item.mFenceTime=acquireFenceTime;item.mIsDroppable=mCore->mAsyncMode||(mConsumerIsSurfaceFlinger&&mCore->mQueueBufferCanDrop)||(mCore->mLegacyBufferDrop&&mCore->mQueueBufferCanDrop)||(mCore->mSharedBufferMode&&mCore->mSharedBufferSlot==slot);item.mSurfaceDamage=surfaceDamage;item.mQueuedBuffer=true;item.mAutoRefresh=mCore->mSharedBufferMode&&mCore->mAutoRefresh;item.mApi=mCore->mConnectedApi;if(mCore->mQueue.empty()){//如果mQueue为空
mCore->mQueue.push_back(item);//直接push到mQueue的
frameAvailableListener=mCore->mConsumerListener;}else{// When the queue is not empty, we need to look at the last buffer
// in the queue to see if we need to replace it
constBufferItem&last=mCore->mQueue.itemAt(mCore->mQueue.size()-1);//获取末尾的Item
//判断末尾Item是不是可以被丢弃的
if(last.mIsDroppable){//省略
}else{mCore->mQueue.push_back(item);//直接push
frameAvailableListener=mCore->mConsumerListener;}}if(frameAvailableListener!=nullptr){frameAvailableListener->onFrameAvailable(item);//这里核心部分,会调用到消费者的onFrameAvailable
}elseif(frameReplacedListener!=nullptr){frameReplacedListener->onFrameReplaced(item);}returnNO_ERROR;}
voidBLASTBufferQueue::onFrameAvailable(constBufferItem&item){std::function<void(SurfaceComposerClient::Transaction*)>prevCallback=nullptr;SurfaceComposerClient::Transaction*prevTransaction=nullptr;boolwaitForTransactionCallback=!mSyncedFrameNumbers.empty();ATRACE_CALL();{BBQ_TRACE();std::unique_lock_lock{mMutex};constboolsyncTransactionSet=mTransactionReadyCallback!=nullptr;BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s",boolToString(syncTransactionSet));if(syncTransactionSet){boolmayNeedToWaitForBuffer=true;// If we are going to re-use the same mSyncTransaction, release the buffer that may
// already be set in the Transaction. This is to allow us a free slot early to continue
// processing a new buffer.
if(!mAcquireSingleBuffer){autobufferData=mSyncTransaction->getAndClearBuffer(mSurfaceControl);if(bufferData){BQA_LOGD("Releasing previous buffer when syncing: framenumber=%"PRIu64,bufferData->frameNumber);releaseBuffer(bufferData->generateReleaseCallbackId(),bufferData->acquireFence);// Because we just released a buffer, we know there's no need to wait for a free
// buffer.
mayNeedToWaitForBuffer=false;}}if(mayNeedToWaitForBuffer){flushAndWaitForFreeBuffer(_lock);}}// add to shadow queue
mNumFrameAvailable++;if(waitForTransactionCallback&&mNumFrameAvailable>=2){acquireAndReleaseBuffer();}ATRACE_INT(mQueuedBufferTrace.c_str(),mNumFrameAvailable+mNumAcquired-mPendingRelease.size());BQA_LOGV("onFrameAvailable framenumber=%"PRIu64" syncTransactionSet=%s",item.mFrameNumber,boolToString(syncTransactionSet));{ATRACE_FORMAT("onFrameAvailable syncTransactionSet = %d",syncTransactionSet);}if(syncTransactionSet){acquireNextBufferLocked(mSyncTransaction);// Only need a commit callback when syncing to ensure the buffer that's synced has been
// sent to SF
incStrong((void*)transactionCommittedCallbackThunk);mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,static_cast<void*>(this));mSyncedFrameNumbers.emplace(item.mFrameNumber);if(mAcquireSingleBuffer){prevCallback=mTransactionReadyCallback;prevTransaction=mSyncTransaction;mTransactionReadyCallback=nullptr;mSyncTransaction=nullptr;}}elseif(!waitForTransactionCallback){acquireNextBufferLocked(std::nullopt);}}if(prevCallback){prevCallback(prevTransaction);}}
voidTransactionCallbackInvoker::sendCallbacks(boolonCommitOnly){ATRACE_CALL();// For each listener
//获取全局的mCompletedTransactions变量再进行遍历
autocompletedTransactionsItr=mCompletedTransactions.begin();BackgroundExecutor::Callbackscallbacks;while(completedTransactionsItr!=mCompletedTransactions.end()){//省略部分
// If the listener has completed transactions
if(!listenerStats.transactionStats.empty()){// If the listener is still alive
if(listener->isBinderAlive()){//塞入callbacks集合
callbacks.emplace_back([stats=std::move(listenerStats)](){ATRACE_NAME("ITransactionCompletedListener onTransactionCompleted");interface_cast<ITransactionCompletedListener>(stats.listener)->onTransactionCompleted(stats);});}}completedTransactionsItr++;}BackgroundExecutor::getInstance().sendCallbacks(std::move(callbacks));}