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