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