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