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