1 /* 2 * Copyright 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef ANDROID_GUI_BUFFERQUEUECORE_H 18 #define ANDROID_GUI_BUFFERQUEUECORE_H 19 20 #include <com_android_graphics_libgui_flags.h> 21 22 #include <gui/AdditionalOptions.h> 23 #include <gui/BufferItem.h> 24 #include <gui/BufferQueueDefs.h> 25 #include <gui/BufferSlot.h> 26 #include <gui/OccupancyTracker.h> 27 28 #include <utils/NativeHandle.h> 29 #include <utils/RefBase.h> 30 #include <utils/String8.h> 31 #include <utils/StrongPointer.h> 32 #include <utils/Trace.h> 33 #include <utils/Vector.h> 34 35 #include <condition_variable> 36 #include <list> 37 #include <mutex> 38 #include <set> 39 #include <vector> 40 41 #define ATRACE_BUFFER_INDEX(index) \ 42 do { \ 43 if (ATRACE_ENABLED()) { \ 44 char ___traceBuf[1024]; \ 45 snprintf(___traceBuf, 1024, "%s: %d", mCore->mConsumerName.c_str(), (index)); \ 46 android::ScopedTrace ___bufTracer(ATRACE_TAG, ___traceBuf); \ 47 } \ 48 } while (false) 49 50 namespace android { 51 52 class IConsumerListener; 53 class IProducerListener; 54 55 class BufferQueueCore : public virtual RefBase { 56 57 friend class BufferQueueProducer; 58 friend class BufferQueueConsumer; 59 60 public: 61 // Used as a placeholder slot number when the value isn't pointing to an 62 // existing buffer. 63 enum { INVALID_BUFFER_SLOT = BufferItem::INVALID_BUFFER_SLOT }; 64 65 // We reserve two slots in order to guarantee that the producer and 66 // consumer can run asynchronously. 67 enum { MAX_MAX_ACQUIRED_BUFFERS = BufferQueueDefs::NUM_BUFFER_SLOTS - 2 }; 68 69 enum { 70 // The API number used to indicate the currently connected producer 71 CURRENTLY_CONNECTED_API = -1, 72 73 // The API number used to indicate that no producer is connected 74 NO_CONNECTED_API = 0, 75 }; 76 77 typedef Vector<BufferItem> Fifo; 78 79 // BufferQueueCore manages a pool of gralloc memory slots to be used by 80 // producers and consumers. 81 BufferQueueCore(); 82 virtual ~BufferQueueCore(); 83 84 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL) 85 protected: 86 // Wake up any threads waiting for a buffer release. The BufferQueue mutex should always held 87 // when this method is called. 88 virtual void notifyBufferReleased() const; 89 #endif 90 91 private: 92 // Dump our state in a string 93 void dumpState(const String8& prefix, String8* outResult) const; 94 95 // getTotalSlotCountLocked returns the total number of slots in use by the 96 // buffer queue at this time. 97 int getTotalSlotCountLocked() const; 98 99 // getMinUndequeuedBufferCountLocked returns the minimum number of buffers 100 // that must remain in a state other than DEQUEUED. The async parameter 101 // tells whether we're in asynchronous mode. 102 int getMinUndequeuedBufferCountLocked() const; 103 104 // getMinMaxBufferCountLocked returns the minimum number of buffers allowed 105 // given the current BufferQueue state. The async parameter tells whether 106 // we're in asynchonous mode. 107 int getMinMaxBufferCountLocked() const; 108 109 // getMaxBufferCountLocked returns the maximum number of buffers that can be 110 // allocated at once. This value depends on the following member variables: 111 // 112 // mMaxDequeuedBufferCount 113 // mMaxAcquiredBufferCount 114 // mMaxBufferCount 115 // mAsyncMode 116 // mDequeueBufferCannotBlock 117 // 118 // Any time one of these member variables is changed while a producer is 119 // connected, mDequeueCondition must be broadcast. 120 int getMaxBufferCountLocked() const; 121 122 // This performs the same computation but uses the given arguments instead 123 // of the member variables for mMaxBufferCount, mAsyncMode, and 124 // mDequeueBufferCannotBlock. 125 int getMaxBufferCountLocked(bool asyncMode, 126 bool dequeueBufferCannotBlock, int maxBufferCount) const; 127 128 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_UNLIMITED_SLOTS) 129 // This resizes mSlots to the given size, but only if it's increasing. 130 status_t extendSlotCountLocked(int size); 131 #endif 132 // clearBufferSlotLocked frees the GraphicBuffer and sync resources for the 133 // given slot. 134 void clearBufferSlotLocked(int slot); 135 136 // freeAllBuffersLocked frees the GraphicBuffer and sync resources for 137 // all slots, even if they're currently dequeued, queued, or acquired. 138 void freeAllBuffersLocked(); 139 140 // discardFreeBuffersLocked releases all currently-free buffers held by the 141 // queue, in order to reduce the memory consumption of the queue to the 142 // minimum possible without discarding data. 143 void discardFreeBuffersLocked(); 144 145 // If delta is positive, makes more slots available. If negative, takes 146 // away slots. Returns false if the request can't be met. 147 bool adjustAvailableSlotsLocked(int delta); 148 149 // waitWhileAllocatingLocked blocks until mIsAllocating is false. 150 void waitWhileAllocatingLocked(std::unique_lock<std::mutex>& lock) const; 151 152 #if DEBUG_ONLY_CODE 153 // validateConsistencyLocked ensures that the free lists are in sync with 154 // the information stored in mSlots 155 void validateConsistencyLocked() const; 156 #endif 157 158 // mMutex is the mutex used to prevent concurrent access to the member 159 // variables of BufferQueueCore objects. It must be locked whenever any 160 // member variable is accessed. 161 mutable std::mutex mMutex; 162 163 // mIsAbandoned indicates that the BufferQueue will no longer be used to 164 // consume image buffers pushed to it using the IGraphicBufferProducer 165 // interface. It is initialized to false, and set to true in the 166 // consumerDisconnect method. A BufferQueue that is abandoned will return 167 // the NO_INIT error from all IGraphicBufferProducer methods capable of 168 // returning an error. 169 bool mIsAbandoned; 170 171 // mConsumerControlledByApp indicates whether the connected consumer is 172 // controlled by the application. 173 bool mConsumerControlledByApp; 174 175 // mConsumerName is a string used to identify the BufferQueue in log 176 // messages. It is set by the IGraphicBufferConsumer::setConsumerName 177 // method. 178 String8 mConsumerName; 179 180 // mConsumerListener is used to notify the connected consumer of 181 // asynchronous events that it may wish to react to. It is initially 182 // set to NULL and is written by consumerConnect and consumerDisconnect. 183 sp<IConsumerListener> mConsumerListener; 184 185 // mConsumerUsageBits contains flags that the consumer wants for 186 // GraphicBuffers. 187 uint64_t mConsumerUsageBits; 188 189 // mConsumerIsProtected indicates the consumer is ready to handle protected 190 // buffer. 191 bool mConsumerIsProtected; 192 193 // mConnectedApi indicates the producer API that is currently connected 194 // to this BufferQueue. It defaults to NO_CONNECTED_API, and gets updated 195 // by the connect and disconnect methods. 196 int mConnectedApi; 197 // PID of the process which last successfully called connect(...) 198 pid_t mConnectedPid; 199 200 // mLinkedToDeath is used to set a binder death notification on 201 // the producer. 202 sp<IProducerListener> mLinkedToDeath; 203 204 // mConnectedProducerListener is used to handle the onBufferReleased 205 // and onBuffersDiscarded notification. 206 sp<IProducerListener> mConnectedProducerListener; 207 // mBufferReleasedCbEnabled is used to indicate whether onBufferReleased() 208 // callback is registered by the listener. When set to false, 209 // mConnectedProducerListener will not trigger onBufferReleased() callback. 210 bool mBufferReleasedCbEnabled; 211 // mBufferAttachedCbEnabled is used to indicate whether onBufferAttached() 212 // callback is registered by the listener. When set to false, 213 // mConnectedProducerListener will not trigger onBufferAttached() callback. 214 bool mBufferAttachedCbEnabled; 215 216 // mSlots is a collection of buffer slots that must be mirrored on the producer 217 // side. This allows buffer ownership to be transferred between the producer 218 // and consumer without sending a GraphicBuffer over Binder. The entire 219 // array is initialized to NULL at construction time, and buffers are 220 // allocated for a slot when requestBuffer is called with that slot's index. 221 BufferQueueDefs::SlotsType mSlots; 222 223 // mQueue is a FIFO of queued buffers used in synchronous mode. 224 Fifo mQueue; 225 226 // mFreeSlots contains all of the slots which are FREE and do not currently 227 // have a buffer attached. 228 std::set<int> mFreeSlots; 229 230 // mFreeBuffers contains all of the slots which are FREE and currently have 231 // a buffer attached. 232 std::list<int> mFreeBuffers; 233 234 // mUnusedSlots contains all slots that are currently unused. They should be 235 // free and not have a buffer attached. 236 std::list<int> mUnusedSlots; 237 238 // mActiveBuffers contains all slots which have a non-FREE buffer attached. 239 std::set<int> mActiveBuffers; 240 241 // mDequeueCondition is a condition variable used for dequeueBuffer in 242 // synchronous mode. 243 mutable std::condition_variable mDequeueCondition; 244 245 // mDequeueBufferCannotBlock indicates whether dequeueBuffer is allowed to 246 // block. This flag is set during connect when both the producer and 247 // consumer are controlled by the application. 248 bool mDequeueBufferCannotBlock; 249 250 // mQueueBufferCanDrop indicates whether queueBuffer is allowed to drop 251 // buffers in non-async mode. This flag is set during connect when both the 252 // producer and consumer are controlled by application. 253 bool mQueueBufferCanDrop; 254 255 // mLegacyBufferDrop indicates whether mQueueBufferCanDrop is in effect. 256 // If this flag is set mQueueBufferCanDrop is working as explained. If not 257 // queueBuffer will not drop buffers unless consumer is SurfaceFlinger and 258 // mQueueBufferCanDrop is set. 259 bool mLegacyBufferDrop; 260 261 // mDefaultBufferFormat can be set so it will override the buffer format 262 // when it isn't specified in dequeueBuffer. 263 PixelFormat mDefaultBufferFormat; 264 265 // mDefaultWidth holds the default width of allocated buffers. It is used 266 // in dequeueBuffer if a width and height of 0 are specified. 267 uint32_t mDefaultWidth; 268 269 // mDefaultHeight holds the default height of allocated buffers. It is used 270 // in dequeueBuffer if a width and height of 0 are specified. 271 uint32_t mDefaultHeight; 272 273 // mDefaultBufferDataSpace holds the default dataSpace of queued buffers. 274 // It is used in queueBuffer if a dataspace of 0 (HAL_DATASPACE_UNKNOWN) 275 // is specified. 276 android_dataspace mDefaultBufferDataSpace; 277 278 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_UNLIMITED_SLOTS) 279 // mAllowExtendedSlotCount is set by the consumer to permit the producer to 280 // request an unlimited number of slots. 281 bool mAllowExtendedSlotCount; 282 #endif 283 284 // mMaxBufferCount is the limit on the number of buffers that will be 285 // allocated at one time. 286 int mMaxBufferCount; 287 288 // mMaxAcquiredBufferCount is the number of buffers that the consumer may 289 // acquire at one time. It defaults to 1, and can be changed by the consumer 290 // via setMaxAcquiredBufferCount, but this may only be done while no 291 // producer is connected to the BufferQueue. This value is used to derive 292 // the value returned for the MIN_UNDEQUEUED_BUFFERS query to the producer. 293 int mMaxAcquiredBufferCount; 294 295 // mMaxDequeuedBufferCount is the number of buffers that the producer may 296 // dequeue at one time. It defaults to 1, and can be changed by the producer 297 // via setMaxDequeuedBufferCount. 298 int mMaxDequeuedBufferCount; 299 300 // mBufferHasBeenQueued is true once a buffer has been queued. It is reset 301 // when something causes all buffers to be freed (e.g., changing the buffer 302 // count). 303 bool mBufferHasBeenQueued; 304 305 // mFrameCounter is the free running counter, incremented on every 306 // successful queueBuffer call and buffer allocation. 307 uint64_t mFrameCounter; 308 309 // mTransformHint is used to optimize for screen rotations. 310 uint32_t mTransformHint; 311 312 // mSidebandStream is a handle to the sideband buffer stream, if any 313 sp<NativeHandle> mSidebandStream; 314 315 // mIsAllocating indicates whether a producer is currently trying to allocate buffers (which 316 // releases mMutex while doing the allocation proper). Producers should not modify any of the 317 // FREE slots while this is true. mIsAllocatingCondition is signaled when this value changes to 318 // false. 319 bool mIsAllocating; 320 321 // mIsAllocatingCondition is a condition variable used by producers to wait until mIsAllocating 322 // becomes false. 323 mutable std::condition_variable mIsAllocatingCondition; 324 325 // mAllowAllocation determines whether dequeueBuffer is allowed to allocate 326 // new buffers 327 bool mAllowAllocation; 328 329 // mBufferAge tracks the age of the contents of the most recently dequeued 330 // buffer as the number of frames that have elapsed since it was last queued 331 uint64_t mBufferAge; 332 333 // mGenerationNumber stores the current generation number of the attached 334 // producer. Any attempt to attach a buffer with a different generation 335 // number will fail. 336 uint32_t mGenerationNumber; 337 338 // mAsyncMode indicates whether or not async mode is enabled. 339 // In async mode an extra buffer will be allocated to allow the producer to 340 // enqueue buffers without blocking. 341 bool mAsyncMode; 342 343 // mSharedBufferMode indicates whether or not shared buffer mode is enabled. 344 bool mSharedBufferMode; 345 346 // When shared buffer mode is enabled, this indicates whether the consumer 347 // should acquire buffers even if BufferQueue doesn't indicate that they are 348 // available. 349 bool mAutoRefresh; 350 351 // When shared buffer mode is enabled, this tracks which slot contains the 352 // shared buffer. 353 int mSharedBufferSlot; 354 355 // Cached data about the shared buffer in shared buffer mode 356 struct SharedBufferCache { SharedBufferCacheSharedBufferCache357 SharedBufferCache(Rect _crop, uint32_t _transform, 358 uint32_t _scalingMode, android_dataspace _dataspace) 359 : crop(_crop), 360 transform(_transform), 361 scalingMode(_scalingMode), 362 dataspace(_dataspace) { 363 } 364 365 Rect crop; 366 uint32_t transform; 367 uint32_t scalingMode; 368 android_dataspace dataspace; 369 } mSharedBufferCache; 370 371 // The slot of the last queued buffer 372 int mLastQueuedSlot; 373 374 OccupancyTracker mOccupancyTracker; 375 376 const uint64_t mUniqueId; 377 378 // When buffer size is driven by the consumer and mTransformHint specifies 379 // a 90 or 270 degree rotation, this indicates whether the width and height 380 // used by dequeueBuffer will be additionally swapped. 381 bool mAutoPrerotation; 382 383 // mTransformHintInUse is to cache the mTransformHint used by the producer. 384 uint32_t mTransformHintInUse; 385 386 // This allows the consumer to acquire an additional buffer if that buffer is not droppable and 387 // will eventually be released or acquired by the consumer. 388 bool mAllowExtraAcquire = false; 389 390 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE) 391 // Additional options to pass when allocating GraphicBuffers. 392 // GenerationID changes when the options change, indicating reallocation is required 393 uint32_t mAdditionalOptionsGenerationId = 0; 394 std::vector<gui::AdditionalOptions> mAdditionalOptions; 395 #endif 396 397 }; // class BufferQueueCore 398 399 } // namespace android 400 401 #endif 402