//frameworks/native/services/surfaceflinger/BufferQueueLayer.cpp
voidBufferQueueLayer::onFirstRef(){BufferLayer::onFirstRef();sp<IGraphicBufferProducer>producer;sp<IGraphicBufferConsumer>consumer;//步骤1
BufferQueue::createBufferQueue(&producer,&consumer,true);//创建BufferQueue
//步骤2
mProducer=newMonitoredProducer(producer,mFlinger,this);//创建一个生产者
{// Grab the SF state lock during this since it's the only safe way to access RenderEngine
Mutex::Autolocklock(mFlinger->mStateLock);//步骤3
mConsumer=newBufferLayerConsumer(consumer,mFlinger->getRenderEngine(),mTextureName,this);//创建一个消费者
{}//步骤4
mConsumer->setConsumerUsageBits(getEffectiveUsage(0));//设置缓冲区的类型,会保存到BufferQueueCore中的mConsumerUsageBits变量中
//步骤5
mConsumer->setContentsChangedListener(this);//设置缓冲区内容改变的监听器
mConsumer->setName(mName);// BufferQueueCore::mMaxDequeuedBufferCount is default to 1
if(!mFlinger->isLayerTripleBufferingDisabled()){mProducer->setMaxDequeuedBufferCount(2);}if(constautodisplay=mFlinger->getDefaultDisplayDevice()){updateTransformHint(display);}if(mFlinger->mLayerExt){mLayerType=mFlinger->mLayerExt->getLayerClass(mName.string());}}
//frameworks/native/services/surfaceflinger/MonitoredProducer.cpp
classMonitoredProducer:publicBnGraphicBufferProducer{public:MonitoredProducer(constsp<IGraphicBufferProducer>&producer,constsp<SurfaceFlinger>&flinger,constwp<Layer>&layer);virtual~MonitoredProducer();// From IGraphicBufferProducer
virtualstatus_trequestBuffer(intslot,sp<GraphicBuffer>*buf);virtualstatus_tsetMaxDequeuedBufferCount(intmaxDequeuedBuffers);virtualstatus_tsetAsyncMode(boolasync);virtualstatus_tdequeueBuffer(int*slot,sp<Fence>*fence,uint32_tw,uint32_th,PixelFormatformat,uint64_tusage,uint64_t*outBufferAge,FrameEventHistoryDelta*outTimestamps);virtualstatus_tdetachBuffer(intslot);virtualstatus_tdetachNextBuffer(sp<GraphicBuffer>*outBuffer,sp<Fence>*outFence);virtualstatus_tattachBuffer(int*outSlot,constsp<GraphicBuffer>&buffer);virtualstatus_tqueueBuffer(intslot,constQueueBufferInput&input,QueueBufferOutput*output);virtualstatus_tcancelBuffer(intslot,constsp<Fence>&fence);virtualintquery(intwhat,int*value);virtualstatus_tconnect(constsp<IProducerListener>&token,intapi,boolproducerControlledByApp,QueueBufferOutput*output);virtualstatus_tdisconnect(intapi,DisconnectModemode);virtualstatus_tsetSidebandStream(constsp<NativeHandle>&stream);virtualvoidallocateBuffers(uint32_twidth,uint32_theight,PixelFormatformat,uint64_tusage);virtualstatus_tallowAllocation(boolallow);virtualstatus_tsetGenerationNumber(uint32_tgenerationNumber);virtualString8getConsumerName()constoverride;virtualstatus_tsetDequeueTimeout(nsecs_ttimeout)override;virtualstatus_tsetLegacyBufferDrop(booldrop)override;virtualstatus_tgetLastQueuedBuffer(sp<GraphicBuffer>*outBuffer,sp<Fence>*outFence,floatoutTransformMatrix[16])override;virtualIBinder*onAsBinder();virtualstatus_tsetSharedBufferMode(boolsharedBufferMode)override;virtualstatus_tsetAutoRefresh(boolautoRefresh)override;virtualvoidgetFrameTimestamps(FrameEventHistoryDelta*outDelta)override;virtualstatus_tgetUniqueId(uint64_t*outId)constoverride;virtualstatus_tgetConsumerUsage(uint64_t*outUsage)constoverride;// The Layer which created this producer, and on which queued Buffer's will be displayed.
sp<Layer>getLayer()const;private:sp<IGraphicBufferProducer>mProducer;sp<SurfaceFlinger>mFlinger;// The Layer which created this producer, and on which queued Buffer's will be displayed.
wp<Layer>mLayer;};};// namespace android
//frameworks/native/services/surfaceflinger/BufferLayerConsumer.cpp
classBufferLayerConsumer:publicConsumerBase{public:staticconststatus_tBUFFER_REJECTED=UNKNOWN_ERROR+8;classBufferRejecter{friendclassBufferLayerConsumer;virtualboolreject(constsp<GraphicBuffer>&buf,constBufferItem&item)=0;protected:virtual~BufferRejecter(){}};structContentsChangedListener:publicFrameAvailableListener{virtualvoidonSidebandStreamChanged()=0;};// BufferLayerConsumer constructs a new BufferLayerConsumer object. The
// tex parameter indicates the name of the RenderEngine texture to which
// images are to be streamed.
BufferLayerConsumer(constsp<IGraphicBufferConsumer>&bq,renderengine::RenderEngine&engine,uint32_ttex,Layer*layer);// Sets the contents changed listener. This should be used instead of
// ConsumerBase::setFrameAvailableListener().
voidsetContentsChangedListener(constwp<ContentsChangedListener>&listener);// updateTexImage acquires the most recently queued buffer, and sets the
// image contents of the target texture to it.
//
// This call may only be made while RenderEngine is current.
//
// This calls doFenceWait to ensure proper synchronization unless native
// fence is supported.
//
// Unlike the GLConsumer version, this version takes a functor that may be
// used to reject the newly acquired buffer. It also does not bind the
// RenderEngine texture until bindTextureImage is called.
status_tupdateTexImage(BufferRejecter*rejecter,nsecs_texpectedPresentTime,bool*autoRefresh,bool*queuedBuffer,uint64_tmaxFrameNumber);// See BufferLayerConsumer::bindTextureImageLocked().
status_tbindTextureImage();// setReleaseFence stores a fence that will signal when the current buffer
// is no longer being read. This fence will be returned to the producer
// when the current buffer is released by updateTexImage(). Multiple
// fences can be set for a given buffer; they will be merged into a single
// union fence.
voidsetReleaseFence(constsp<Fence>&fence);boolreleasePendingBuffer();sp<Fence>getPrevFinalReleaseFence()const;// See GLConsumer::getTransformMatrix.
voidgetTransformMatrix(floatmtx[16]);// getTimestamp retrieves the timestamp associated with the texture image
// set by the most recent call to updateTexImage.
//
// The timestamp is in nanoseconds, and is monotonically increasing. Its
// other semantics (zero point, etc) are source-dependent and should be
// documented by the source.
int64_tgetTimestamp();// getDataSpace retrieves the DataSpace associated with the texture image
// set by the most recent call to updateTexImage.
ui::DataspacegetCurrentDataSpace();// getCurrentHdrMetadata retrieves the HDR metadata associated with the
// texture image set by the most recent call to updateTexImage.
constHdrMetadata&getCurrentHdrMetadata()const;// getFrameNumber retrieves the frame number associated with the texture
// image set by the most recent call to updateTexImage.
//
// The frame number is an incrementing counter set to 0 at the creation of
// the BufferQueue associated with this consumer.
uint64_tgetFrameNumber();boolgetTransformToDisplayInverse()const;// must be called from SF main thread
constRegion&getSurfaceDamage()const;// Merge the given damage region into the current damage region value.
voidmergeSurfaceDamage(constRegion&damage);// getCurrentApi retrieves the API which queues the current buffer.
intgetCurrentApi()const;// See GLConsumer::setDefaultBufferSize.
status_tsetDefaultBufferSize(uint32_twidth,uint32_theight);// setFilteringEnabled sets whether the transform matrix should be computed
// for use with bilinear filtering.
voidsetFilteringEnabled(boolenabled);// getCurrentBuffer returns the buffer associated with the current image.
// When outSlot is not nullptr, the current buffer slot index is also
// returned. Simiarly, when outFence is not nullptr, the current output
// fence is returned.
sp<GraphicBuffer>getCurrentBuffer(int*outSlot=nullptr,sp<Fence>*outFence=nullptr)const;// getCurrentCrop returns the cropping rectangle of the current buffer.
RectgetCurrentCrop()const;// getCurrentTransform returns the transform of the current buffer.
uint32_tgetCurrentTransform()const;// getCurrentScalingMode returns the scaling mode of the current buffer.
uint32_tgetCurrentScalingMode()const;// getCurrentFence returns the fence indicating when the current buffer is
// ready to be read from.
sp<Fence>getCurrentFence()const;// getCurrentFence returns the FenceTime indicating when the current
// buffer is ready to be read from.
std::shared_ptr<FenceTime>getCurrentFenceTime()const;// setConsumerUsageBits overrides the ConsumerBase method to OR
// DEFAULT_USAGE_FLAGS to usage.
status_tsetConsumerUsageBits(uint64_tusage);voidonBufferAvailable(constBufferItem&item)EXCLUDES(mImagesMutex);protected:// abandonLocked overrides the ConsumerBase method to clear
// mCurrentTextureImage in addition to the ConsumerBase behavior.
virtualvoidabandonLocked()EXCLUDES(mImagesMutex);// dumpLocked overrides the ConsumerBase method to dump BufferLayerConsumer-
// specific info in addition to the ConsumerBase behavior.
virtualvoiddumpLocked(String8&result,constchar*prefix)const;// See ConsumerBase::acquireBufferLocked
virtualstatus_tacquireBufferLocked(BufferItem*item,nsecs_tpresentWhen,uint64_tmaxFrameNumber=0)overrideEXCLUDES(mImagesMutex);boolcanUseImageCrop(constRect&crop)const;structPendingRelease{PendingRelease():isPending(false),currentTexture(-1),graphicBuffer(){}boolisPending;intcurrentTexture;sp<GraphicBuffer>graphicBuffer;};// This releases the buffer in the slot referenced by mCurrentTexture,
// then updates state to refer to the BufferItem, which must be a
// newly-acquired buffer. If pendingRelease is not null, the parameters
// which would have been passed to releaseBufferLocked upon the successful
// completion of the method will instead be returned to the caller, so that
// it may call releaseBufferLocked itself later.
status_tupdateAndReleaseLocked(constBufferItem&item,PendingRelease*pendingRelease=nullptr)EXCLUDES(mImagesMutex);// Binds mTexName and the current buffer to TEXTURE_EXTERNAL target.
// If the bind succeeds, this calls doFenceWait.
status_tbindTextureImageLocked();private:// Utility class for managing GraphicBuffer references into renderengine
classImage{public:Image(constsp<GraphicBuffer>&graphicBuffer,renderengine::RenderEngine&engine);virtual~Image();constsp<GraphicBuffer>&graphicBuffer(){returnmGraphicBuffer;}private:// mGraphicBuffer is the buffer that was used to create this image.
sp<GraphicBuffer>mGraphicBuffer;// Back-reference into renderengine to initiate cleanup.
renderengine::RenderEngine&mRE;DISALLOW_COPY_AND_ASSIGN(Image);};// freeBufferLocked frees up the given buffer slot. If the slot has been
// initialized this will release the reference to the GraphicBuffer in
// that slot. Otherwise it has no effect.
//
// This method must be called with mMutex locked.
virtualvoidfreeBufferLocked(intslotIndex)EXCLUDES(mImagesMutex);// IConsumerListener interface
voidonDisconnect()override;voidonSidebandStreamChanged()override;voidaddAndGetFrameTimestamps(constNewFrameEventsEntry*newTimestamps,FrameEventHistoryDelta*outDelta)override;// computeCurrentTransformMatrixLocked computes the transform matrix for the
// current texture. It uses mCurrentTransform and the current GraphicBuffer
// to compute this matrix and stores it in mCurrentTransformMatrix.
// mCurrentTextureImage must not be nullptr.
voidcomputeCurrentTransformMatrixLocked();// doFenceWaitLocked inserts a wait command into the RenderEngine command
// stream to ensure that it is safe for future RenderEngine commands to
// access the current texture buffer.
status_tdoFenceWaitLocked()const;// getCurrentCropLocked returns the cropping rectangle of the current buffer.
RectgetCurrentCropLocked()const;// The default consumer usage flags that BufferLayerConsumer always sets on its
// BufferQueue instance; these will be OR:d with any additional flags passed
// from the BufferLayerConsumer user. In particular, BufferLayerConsumer will always
// consume buffers as hardware textures.
staticconstuint64_tDEFAULT_USAGE_FLAGS=GraphicBuffer::USAGE_HW_TEXTURE;// mCurrentTextureBuffer is the buffer containing the current texture. It's
// possible that this buffer is not associated with any buffer slot, so we
// must track it separately in order to support the getCurrentBuffer method.
std::shared_ptr<Image>mCurrentTextureBuffer;// mCurrentCrop is the crop rectangle that applies to the current texture.
// It gets set each time updateTexImage is called.
RectmCurrentCrop;// mCurrentTransform is the transform identifier for the current texture. It
// gets set each time updateTexImage is called.
uint32_tmCurrentTransform;// mCurrentScalingMode is the scaling mode for the current texture. It gets
// set each time updateTexImage is called.
uint32_tmCurrentScalingMode;// mCurrentFence is the fence received from BufferQueue in updateTexImage.
sp<Fence>mCurrentFence;// The FenceTime wrapper around mCurrentFence.
std::shared_ptr<FenceTime>mCurrentFenceTime{FenceTime::NO_FENCE};// mCurrentTransformMatrix is the transform matrix for the current texture.
// It gets computed by computeTransformMatrix each time updateTexImage is
// called.
floatmCurrentTransformMatrix[16];// mCurrentTimestamp is the timestamp for the current texture. It
// gets set each time updateTexImage is called.
int64_tmCurrentTimestamp;// mCurrentDataSpace is the dataspace for the current texture. It
// gets set each time updateTexImage is called.
ui::DataspacemCurrentDataSpace;// mCurrentHdrMetadata is the HDR metadata for the current texture. It
// gets set each time updateTexImage is called.
HdrMetadatamCurrentHdrMetadata;// mCurrentFrameNumber is the frame counter for the current texture.
// It gets set each time updateTexImage is called.
uint64_tmCurrentFrameNumber;// Indicates this buffer must be transformed by the inverse transform of the screen
// it is displayed onto. This is applied after BufferLayerConsumer::mCurrentTransform.
// This must be set/read from SurfaceFlinger's main thread.
boolmCurrentTransformToDisplayInverse;// The portion of this surface that has changed since the previous frame
RegionmCurrentSurfaceDamage;intmCurrentApi;uint32_tmDefaultWidth,mDefaultHeight;// mFilteringEnabled indicates whether the transform matrix is computed for
// use with bilinear filtering. It defaults to true and is changed by
// setFilteringEnabled().
boolmFilteringEnabled;renderengine::RenderEngine&mRE;// mTexName is the name of the RenderEngine texture to which streamed
// images will be bound when bindTexImage is called. It is set at
// construction time.
constuint32_tmTexName;// The layer for this BufferLayerConsumer
constwp<Layer>mLayer;wp<ContentsChangedListener>mContentsChangedListener;// mCurrentTexture is the buffer slot index of the buffer that is currently
// bound to the RenderEngine texture. It is initialized to INVALID_BUFFER_SLOT,
// indicating that no buffer slot is currently bound to the texture. Note,
// however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
// that no buffer is bound to the texture. A call to setBufferCount will
// reset mCurrentTexture to INVALID_BUFFER_SLOT.
intmCurrentTexture;// Shadow buffer cache for cleaning up renderengine references.
std::shared_ptr<Image>mImages[BufferQueueDefs::NUM_BUFFER_SLOTS]GUARDED_BY(mImagesMutex);// Separate mutex guarding the shadow buffer cache.
// mImagesMutex can be manipulated with binder threads (e.g. onBuffersAllocated)
// which is contentious enough that we can't just use mMutex.
mutablestd::mutexmImagesMutex;// A release that is pending on the receipt of a new release fence from
// presentDisplay
PendingReleasemPendingRelease;}