2 * Copyright 2014 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef ANDROID_GUI_BUFFERQUEUECORE_H
18 #define ANDROID_GUI_BUFFERQUEUECORE_H
20 #include <gui/BufferItem.h>
21 #include <gui/BufferQueueDefs.h>
22 #include <gui/BufferSlot.h>
24 #include <utils/Condition.h>
25 #include <utils/Mutex.h>
26 #include <utils/NativeHandle.h>
27 #include <utils/RefBase.h>
28 #include <utils/String8.h>
29 #include <utils/StrongPointer.h>
30 #include <utils/Trace.h>
31 #include <utils/Vector.h>
36 #define BQ_LOGV(x, ...) ALOGV("[%s] " x, mConsumerName.string(), ##__VA_ARGS__)
37 #define BQ_LOGD(x, ...) ALOGD("[%s] " x, mConsumerName.string(), ##__VA_ARGS__)
38 #define BQ_LOGI(x, ...) ALOGI("[%s] " x, mConsumerName.string(), ##__VA_ARGS__)
39 #define BQ_LOGW(x, ...) ALOGW("[%s] " x, mConsumerName.string(), ##__VA_ARGS__)
40 #define BQ_LOGE(x, ...) ALOGE("[%s] " x, mConsumerName.string(), ##__VA_ARGS__)
42 #define ATRACE_BUFFER_INDEX(index) \
43 if (ATRACE_ENABLED()) { \
44 char ___traceBuf[1024]; \
45 snprintf(___traceBuf, 1024, "%s: %d", \
46 mCore->mConsumerName.string(), (index)); \
47 android::ScopedTrace ___bufTracer(ATRACE_TAG, ___traceBuf); \
52 class IConsumerListener;
53 class IGraphicBufferAlloc;
54 class IProducerListener;
56 class BufferQueueCore : public virtual RefBase {
58 friend class BufferQueueProducer;
59 friend class BufferQueueConsumer;
62 // Used as a placeholder slot number when the value isn't pointing to an
64 enum { INVALID_BUFFER_SLOT = BufferItem::INVALID_BUFFER_SLOT };
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 };
71 // The API number used to indicate the currently connected producer
72 CURRENTLY_CONNECTED_API = -1,
74 // The API number used to indicate that no producer is connected
78 typedef Vector<BufferItem> Fifo;
80 // BufferQueueCore manages a pool of gralloc memory slots to be used by
81 // producers and consumers. allocator is used to allocate all the needed
83 BufferQueueCore(const sp<IGraphicBufferAlloc>& allocator = NULL);
84 virtual ~BufferQueueCore();
87 // Dump our state in a string
88 void dumpState(String8& result, const char* prefix) const;
90 // getMinUndequeuedBufferCountLocked returns the minimum number of buffers
91 // that must remain in a state other than DEQUEUED. The async parameter
92 // tells whether we're in asynchronous mode.
93 int getMinUndequeuedBufferCountLocked() const;
95 // getMinMaxBufferCountLocked returns the minimum number of buffers allowed
96 // given the current BufferQueue state. The async parameter tells whether
97 // we're in asynchonous mode.
98 int getMinMaxBufferCountLocked() const;
100 // getMaxBufferCountLocked returns the maximum number of buffers that can be
101 // allocated at once. This value depends on the following member variables:
103 // mMaxDequeuedBufferCount
104 // mMaxAcquiredBufferCount
107 // mDequeueBufferCannotBlock
109 // Any time one of these member variables is changed while a producer is
110 // connected, mDequeueCondition must be broadcast.
111 int getMaxBufferCountLocked() const;
113 // This performs the same computation but uses the given arguments instead
114 // of the member variables for mMaxBufferCount, mAsyncMode, and
115 // mDequeueBufferCannotBlock.
116 int getMaxBufferCountLocked(bool asyncMode,
117 bool dequeueBufferCannotBlock, int maxBufferCount) const;
119 // clearBufferSlotLocked frees the GraphicBuffer and sync resources for the
121 void clearBufferSlotLocked(int slot);
123 // freeAllBuffersLocked frees the GraphicBuffer and sync resources for
124 // all slots, even if they're currently dequeued, queued, or acquired.
125 void freeAllBuffersLocked();
127 // discardFreeBuffersLocked releases all currently-free buffers held by the
128 // queue, in order to reduce the memory consumption of the queue to the
129 // minimum possible without discarding data.
130 void discardFreeBuffersLocked();
132 // If delta is positive, makes more slots available. If negative, takes
133 // away slots. Returns false if the request can't be met.
134 bool adjustAvailableSlotsLocked(int delta);
136 // waitWhileAllocatingLocked blocks until mIsAllocating is false.
137 void waitWhileAllocatingLocked() const;
140 // validateConsistencyLocked ensures that the free lists are in sync with
141 // the information stored in mSlots
142 void validateConsistencyLocked() const;
145 // mAllocator is the connection to SurfaceFlinger that is used to allocate
146 // new GraphicBuffer objects.
147 sp<IGraphicBufferAlloc> mAllocator;
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 Mutex mMutex;
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.
162 // mConsumerControlledByApp indicates whether the connected consumer is
163 // controlled by the application.
164 bool mConsumerControlledByApp;
166 // mConsumerName is a string used to identify the BufferQueue in log
167 // messages. It is set by the IGraphicBufferConsumer::setConsumerName
169 String8 mConsumerName;
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;
176 // mConsumerUsageBits contains flags that the consumer wants for
178 uint32_t mConsumerUsageBits;
180 // mConnectedApi indicates the producer API that is currently connected
181 // to this BufferQueue. It defaults to NO_CONNECTED_API, and gets updated
182 // by the connect and disconnect methods.
185 // mConnectedProducerToken is used to set a binder death notification on
187 sp<IProducerListener> mConnectedProducerListener;
189 // mSlots is an array of buffer slots that must be mirrored on the producer
190 // side. This allows buffer ownership to be transferred between the producer
191 // and consumer without sending a GraphicBuffer over Binder. The entire
192 // array is initialized to NULL at construction time, and buffers are
193 // allocated for a slot when requestBuffer is called with that slot's index.
194 BufferQueueDefs::SlotsType mSlots;
196 // mQueue is a FIFO of queued buffers used in synchronous mode.
199 // mFreeSlots contains all of the slots which are FREE and do not currently
200 // have a buffer attached.
201 std::set<int> mFreeSlots;
203 // mFreeBuffers contains all of the slots which are FREE and currently have
204 // a buffer attached.
205 std::list<int> mFreeBuffers;
207 // mUnusedSlots contains all slots that are currently unused. They should be
208 // free and not have a buffer attached.
209 std::list<int> mUnusedSlots;
211 // mActiveBuffers contains all slots which have a non-FREE buffer attached.
212 std::set<int> mActiveBuffers;
214 // mDequeueCondition is a condition variable used for dequeueBuffer in
216 mutable Condition mDequeueCondition;
218 // mDequeueBufferCannotBlock indicates whether dequeueBuffer is allowed to
219 // block. This flag is set during connect when both the producer and
220 // consumer are controlled by the application.
221 bool mDequeueBufferCannotBlock;
223 // mDefaultBufferFormat can be set so it will override the buffer format
224 // when it isn't specified in dequeueBuffer.
225 PixelFormat mDefaultBufferFormat;
227 // mDefaultWidth holds the default width of allocated buffers. It is used
228 // in dequeueBuffer if a width and height of 0 are specified.
229 uint32_t mDefaultWidth;
231 // mDefaultHeight holds the default height of allocated buffers. It is used
232 // in dequeueBuffer if a width and height of 0 are specified.
233 uint32_t mDefaultHeight;
235 // mDefaultBufferDataSpace holds the default dataSpace of queued buffers.
236 // It is used in queueBuffer if a dataspace of 0 (HAL_DATASPACE_UNKNOWN)
238 android_dataspace mDefaultBufferDataSpace;
240 // mMaxBufferCount is the limit on the number of buffers that will be
241 // allocated at one time. This limit can be set by the consumer.
244 // mMaxAcquiredBufferCount is the number of buffers that the consumer may
245 // acquire at one time. It defaults to 1, and can be changed by the consumer
246 // via setMaxAcquiredBufferCount, but this may only be done while no
247 // producer is connected to the BufferQueue. This value is used to derive
248 // the value returned for the MIN_UNDEQUEUED_BUFFERS query to the producer.
249 int mMaxAcquiredBufferCount;
251 // mMaxDequeuedBufferCount is the number of buffers that the producer may
252 // dequeue at one time. It defaults to 1, and can be changed by the producer
253 // via setMaxDequeuedBufferCount.
254 int mMaxDequeuedBufferCount;
256 // mBufferHasBeenQueued is true once a buffer has been queued. It is reset
257 // when something causes all buffers to be freed (e.g., changing the buffer
259 bool mBufferHasBeenQueued;
261 // mFrameCounter is the free running counter, incremented on every
262 // successful queueBuffer call and buffer allocation.
263 uint64_t mFrameCounter;
265 // mTransformHint is used to optimize for screen rotations.
266 uint32_t mTransformHint;
268 // mSidebandStream is a handle to the sideband buffer stream, if any
269 sp<NativeHandle> mSidebandStream;
271 // mIsAllocating indicates whether a producer is currently trying to allocate buffers (which
272 // releases mMutex while doing the allocation proper). Producers should not modify any of the
273 // FREE slots while this is true. mIsAllocatingCondition is signaled when this value changes to
277 // mIsAllocatingCondition is a condition variable used by producers to wait until mIsAllocating
279 mutable Condition mIsAllocatingCondition;
281 // mAllowAllocation determines whether dequeueBuffer is allowed to allocate
283 bool mAllowAllocation;
285 // mBufferAge tracks the age of the contents of the most recently dequeued
286 // buffer as the number of frames that have elapsed since it was last queued
289 // mGenerationNumber stores the current generation number of the attached
290 // producer. Any attempt to attach a buffer with a different generation
292 uint32_t mGenerationNumber;
294 // mAsyncMode indicates whether or not async mode is enabled.
295 // In async mode an extra buffer will be allocated to allow the producer to
296 // enqueue buffers without blocking.
299 // mSharedBufferMode indicates whether or not shared buffer mode is enabled.
300 bool mSharedBufferMode;
302 // When shared buffer mode is enabled, this indicates whether the consumer
303 // should acquire buffers even if BufferQueue doesn't indicate that they are
307 // When shared buffer mode is enabled, this tracks which slot contains the
309 int mSharedBufferSlot;
311 // Cached data about the shared buffer in shared buffer mode
312 struct SharedBufferCache {
313 SharedBufferCache(Rect _crop, uint32_t _transform, int _scalingMode,
314 android_dataspace _dataspace)
316 transform(_transform),
317 scalingMode(_scalingMode),
318 dataspace(_dataspace) {
323 uint32_t scalingMode;
324 android_dataspace dataspace;
325 } mSharedBufferCache;
327 // The slot of the last queued buffer
330 const uint64_t mUniqueId;
332 }; // class BufferQueueCore
334 } // namespace android