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_BUFFERQUEUEPRODUCER_H
18 #define ANDROID_GUI_BUFFERQUEUEPRODUCER_H
19 
20 #include <gui/AdditionalOptions.h>
21 #include <gui/BufferQueueDefs.h>
22 
23 #include <gui/IGraphicBufferProducer.h>
24 
25 namespace android {
26 
27 class IBinder;
28 struct BufferSlot;
29 
30 #ifndef NO_BINDER
31 class BufferQueueProducer : public BnGraphicBufferProducer,
32                             private IBinder::DeathRecipient {
33 #else
34 class BufferQueueProducer : public BnGraphicBufferProducer {
35 #endif
36 public:
37     friend class BufferQueue; // Needed to access binderDied
38 
39     explicit BufferQueueProducer(const sp<BufferQueueCore>& core,
40                                  bool consumerIsSurfaceFlinger = false);
41     ~BufferQueueProducer() override;
42 
43     // requestBuffer returns the GraphicBuffer for slot N.
44     //
45     // In normal operation, this is called the first time slot N is returned
46     // by dequeueBuffer.  It must be called again if dequeueBuffer returns
47     // flags indicating that previously-returned buffers are no longer valid.
48     virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf);
49 
50     // see IGraphicsBufferProducer::setMaxDequeuedBufferCount
51     virtual status_t setMaxDequeuedBufferCount(int maxDequeuedBuffers);
52 
53     // see IGraphicsBufferProducer::setAsyncMode
54     virtual status_t setAsyncMode(bool async);
55 
56     // dequeueBuffer gets the next buffer slot index for the producer to use.
57     // If a buffer slot is available then that slot index is written to the
58     // location pointed to by the buf argument and a status of OK is returned.
59     // If no slot is available then a status of -EBUSY is returned and buf is
60     // unmodified.
61     //
62     // The outFence parameter will be updated to hold the fence associated with
63     // the buffer. The contents of the buffer must not be overwritten until the
64     // fence signals. If the fence is Fence::NO_FENCE, the buffer may be
65     // written immediately.
66     //
67     // The width and height parameters must be no greater than the minimum of
68     // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
69     // An error due to invalid dimensions might not be reported until
70     // updateTexImage() is called.  If width and height are both zero, the
71     // default values specified by setDefaultBufferSize() are used instead.
72     //
73     // If the format is 0, the default format will be used.
74     //
75     // The usage argument specifies gralloc buffer usage flags.  The values
76     // are enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER.  These
77     // will be merged with the usage flags specified by setConsumerUsageBits.
78     //
79     // The return value may be a negative error value or a non-negative
80     // collection of flags.  If the flags are set, the return values are
81     // valid, but additional actions must be performed.
82     //
83     // If IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION is set, the
84     // producer must discard cached GraphicBuffer references for the slot
85     // returned in buf.
86     // If IGraphicBufferProducer::RELEASE_ALL_BUFFERS is set, the producer
87     // must discard cached GraphicBuffer references for all slots.
88     //
89     // In both cases, the producer will need to call requestBuffer to get a
90     // GraphicBuffer handle for the returned slot.
91     virtual status_t dequeueBuffer(int* outSlot, sp<Fence>* outFence, uint32_t width,
92                                    uint32_t height, PixelFormat format, uint64_t usage,
93                                    uint64_t* outBufferAge,
94                                    FrameEventHistoryDelta* outTimestamps) override;
95 
96     // See IGraphicBufferProducer::detachBuffer
97     virtual status_t detachBuffer(int slot);
98 
99     // See IGraphicBufferProducer::detachNextBuffer
100     virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
101             sp<Fence>* outFence);
102 
103     // See IGraphicBufferProducer::attachBuffer
104     virtual status_t attachBuffer(int* outSlot, const sp<GraphicBuffer>& buffer);
105 
106     // queueBuffer returns a filled buffer to the BufferQueue.
107     //
108     // Additional data is provided in the QueueBufferInput struct.  Notably,
109     // a timestamp must be provided for the buffer. The timestamp is in
110     // nanoseconds, and must be monotonically increasing. Its other semantics
111     // (zero point, etc) are producer-specific and should be documented by the
112     // producer.
113     //
114     // The caller may provide a fence that signals when all rendering
115     // operations have completed.  Alternatively, NO_FENCE may be used,
116     // indicating that the buffer is ready immediately.
117     //
118     // Some values are returned in the output struct: the current settings
119     // for default width and height, the current transform hint, and the
120     // number of queued buffers.
121     virtual status_t queueBuffer(int slot,
122             const QueueBufferInput& input, QueueBufferOutput* output);
123 
124     // cancelBuffer returns a dequeued buffer to the BufferQueue, but doesn't
125     // queue it for use by the consumer.
126     //
127     // The buffer will not be overwritten until the fence signals.  The fence
128     // will usually be the one obtained from dequeueBuffer.
129     virtual status_t cancelBuffer(int slot, const sp<Fence>& fence);
130 
131     // Query native window attributes.  The "what" values are enumerated in
132     // window.h (e.g. NATIVE_WINDOW_FORMAT).
133     virtual int query(int what, int* outValue);
134 
135     // connect attempts to connect a producer API to the BufferQueue.  This
136     // must be called before any other IGraphicBufferProducer methods are
137     // called except for getAllocator.  A consumer must already be connected.
138     //
139     // This method will fail if connect was previously called on the
140     // BufferQueue and no corresponding disconnect call was made (i.e. if
141     // it's still connected to a producer).
142     //
143     // APIs are enumerated in window.h (e.g. NATIVE_WINDOW_API_CPU).
144     virtual status_t connect(const sp<IProducerListener>& listener,
145             int api, bool producerControlledByApp, QueueBufferOutput* output);
146 
147     // See IGraphicBufferProducer::disconnect
148     virtual status_t disconnect(int api, DisconnectMode mode = DisconnectMode::Api);
149 
150     // Attaches a sideband buffer stream to the IGraphicBufferProducer.
151     //
152     // A sideband stream is a device-specific mechanism for passing buffers
153     // from the producer to the consumer without using dequeueBuffer/
154     // queueBuffer. If a sideband stream is present, the consumer can choose
155     // whether to acquire buffers from the sideband stream or from the queued
156     // buffers.
157     //
158     // Passing NULL or a different stream handle will detach the previous
159     // handle if any.
160     virtual status_t setSidebandStream(const sp<NativeHandle>& stream);
161 
162     // See IGraphicBufferProducer::allocateBuffers
163     virtual void allocateBuffers(uint32_t width, uint32_t height,
164             PixelFormat format, uint64_t usage) override;
165 
166     // See IGraphicBufferProducer::allowAllocation
167     virtual status_t allowAllocation(bool allow);
168 
169     // See IGraphicBufferProducer::setGenerationNumber
170     virtual status_t setGenerationNumber(uint32_t generationNumber);
171 
172     // See IGraphicBufferProducer::getConsumerName
173     virtual String8 getConsumerName() const override;
174 
175     // See IGraphicBufferProducer::setSharedBufferMode
176     virtual status_t setSharedBufferMode(bool sharedBufferMode) override;
177 
178     // See IGraphicBufferProducer::setAutoRefresh
179     virtual status_t setAutoRefresh(bool autoRefresh) override;
180 
181     // See IGraphicBufferProducer::setDequeueTimeout
182     virtual status_t setDequeueTimeout(nsecs_t timeout) override;
183 
184     // see IGraphicBufferProducer::setLegacyBufferDrop
185     virtual status_t setLegacyBufferDrop(bool drop);
186 
187     // See IGraphicBufferProducer::getLastQueuedBuffer
188     virtual status_t getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
189             sp<Fence>* outFence, float outTransformMatrix[16]) override;
190 
191     // See IGraphicBufferProducer::getLastQueuedBuffer
192     virtual status_t getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer, sp<Fence>* outFence,
193                                          Rect* outRect, uint32_t* outTransform) override;
194 
195     // See IGraphicBufferProducer::getFrameTimestamps
196     virtual void getFrameTimestamps(FrameEventHistoryDelta* outDelta) override;
197 
198     // See IGraphicBufferProducer::getUniqueId
199     virtual status_t getUniqueId(uint64_t* outId) const override;
200 
201     // See IGraphicBufferProducer::getConsumerUsage
202     virtual status_t getConsumerUsage(uint64_t* outUsage) const override;
203 
204     // See IGraphicBufferProducer::setAutoPrerotation
205     virtual status_t setAutoPrerotation(bool autoPrerotation);
206 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_SETFRAMERATE)
207     // See IGraphicBufferProducer::setFrameRate
208     status_t setFrameRate(float frameRate, int8_t compatibility,
209                           int8_t changeFrameRateStrategy) override;
210 #endif
211 
212 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
213     status_t setAdditionalOptions(const std::vector<gui::AdditionalOptions>& options) override;
214 #endif
215 
216 protected:
217     // see IGraphicsBufferProducer::setMaxDequeuedBufferCount, but with the ability to retrieve the
218     // total maximum buffer count for the buffer queue (dequeued AND acquired)
219     status_t setMaxDequeuedBufferCount(int maxDequeuedBuffers, int* maxBufferCount);
220 
221 private:
222     // This is required by the IBinder::DeathRecipient interface
223     virtual void binderDied(const wp<IBinder>& who);
224 
225     // Returns the slot of the next free buffer if one is available or
226     // BufferQueueCore::INVALID_BUFFER_SLOT otherwise
227     int getFreeBufferLocked() const;
228 
229     // Returns the next free slot if one is available or
230     // BufferQueueCore::INVALID_BUFFER_SLOT otherwise
231     int getFreeSlotLocked() const;
232 
233     void addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
234             FrameEventHistoryDelta* outDelta);
235 
236     // waitForFreeSlotThenRelock finds the oldest slot in the FREE state. It may
237     // block if there are no available slots and we are not in non-blocking
238     // mode (producer and consumer controlled by the application). If it blocks,
239     // it will release mCore->mMutex while blocked so that other operations on
240     // the BufferQueue may succeed.
241     enum class FreeSlotCaller {
242         Dequeue,
243         Attach,
244     };
245     status_t waitForFreeSlotThenRelock(FreeSlotCaller caller, std::unique_lock<std::mutex>& lock,
246             int* found) const;
247 
248     sp<BufferQueueCore> mCore;
249 
250     // This references mCore->mSlots. Lock mCore->mMutex while accessing.
251     BufferQueueDefs::SlotsType& mSlots;
252 
253     // This is a cached copy of the name stored in the BufferQueueCore.
254     // It's updated during connect and dequeueBuffer (which should catch
255     // most updates).
256     String8 mConsumerName;
257 
258     uint32_t mStickyTransform;
259 
260     // This controls whether the GraphicBuffer pointer in the BufferItem is
261     // cleared after being queued
262     bool mConsumerIsSurfaceFlinger;
263 
264     // This saves the fence from the last queueBuffer, such that the
265     // next queueBuffer call can throttle buffer production. The prior
266     // queueBuffer's fence is not nessessarily available elsewhere,
267     // since the previous buffer might have already been acquired.
268     sp<Fence> mLastQueueBufferFence;
269 
270     Rect mLastQueuedCrop;
271     uint32_t mLastQueuedTransform;
272 
273     // Take-a-ticket system for ensuring that onFrame* callbacks are called in
274     // the order that frames are queued. While the BufferQueue lock
275     // (mCore->mMutex) is held, a ticket is retained by the producer. After
276     // dropping the BufferQueue lock, the producer must wait on the condition
277     // variable until the current callback ticket matches its retained ticket.
278     std::mutex mCallbackMutex;
279     int mNextCallbackTicket; // Protected by mCore->mMutex
280     int mCurrentCallbackTicket; // Protected by mCallbackMutex
281     std::condition_variable mCallbackCondition;
282 
283     // Sets how long dequeueBuffer or attachBuffer will block if a buffer or
284     // slot is not yet available.
285     nsecs_t mDequeueTimeout;
286 
287     // If set to true, dequeueBuffer() is currently waiting for buffer allocation to complete.
288     bool mDequeueWaitingForAllocation;
289 
290     // Condition variable to signal allocateBuffers() that dequeueBuffer() is no longer waiting for
291     // allocation to complete.
292     std::condition_variable mDequeueWaitingForAllocationCondition;
293 
294 }; // class BufferQueueProducer
295 
296 } // namespace android
297 
298 #endif
299