1 /*
2  * Copyright (C) 2010 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_IGRAPHICBUFFERPRODUCER_H
18 #define ANDROID_GUI_IGRAPHICBUFFERPRODUCER_H
19 
20 #include <stdint.h>
21 #include <sys/types.h>
22 
23 #include <utils/Errors.h>
24 #include <utils/RefBase.h>
25 
26 #include <binder/IInterface.h>
27 
28 #include <ui/BufferQueueDefs.h>
29 #include <ui/Fence.h>
30 #include <ui/GraphicBuffer.h>
31 #include <ui/Rect.h>
32 #include <ui/Region.h>
33 
34 #include <gui/AdditionalOptions.h>
35 #include <gui/FrameTimestamps.h>
36 #include <gui/HdrMetadata.h>
37 
38 #include <hidl/HybridInterface.h>
39 #include <android/hardware/graphics/bufferqueue/1.0/IGraphicBufferProducer.h>
40 #include <android/hardware/graphics/bufferqueue/2.0/IGraphicBufferProducer.h>
41 
42 #include <optional>
43 #include <vector>
44 
45 #include <com_android_graphics_libgui_flags.h>
46 
47 namespace android {
48 // ----------------------------------------------------------------------------
49 
50 class IProducerListener;
51 class NativeHandle;
52 class Surface;
53 
54 using HGraphicBufferProducerV1_0 =
55         ::android::hardware::graphics::bufferqueue::V1_0::
56         IGraphicBufferProducer;
57 using HGraphicBufferProducerV2_0 =
58         ::android::hardware::graphics::bufferqueue::V2_0::
59         IGraphicBufferProducer;
60 
61 /*
62  * This class defines the Binder IPC interface for the producer side of
63  * a queue of graphics buffers.  It's used to send graphics data from one
64  * component to another.  For example, a class that decodes video for
65  * playback might use this to provide frames.  This is typically done
66  * indirectly, through Surface.
67  *
68  * The underlying mechanism is a BufferQueue, which implements
69  * BnGraphicBufferProducer.  In normal operation, the producer calls
70  * dequeueBuffer() to get an empty buffer, fills it with data, then
71  * calls queueBuffer() to make it available to the consumer.
72  *
73  * This class was previously called ISurfaceTexture.
74  */
75 #ifndef NO_BINDER
76 class IGraphicBufferProducer : public IInterface {
77     DECLARE_HYBRID_META_INTERFACE(GraphicBufferProducer,
78                                   HGraphicBufferProducerV1_0,
79                                   HGraphicBufferProducerV2_0)
80 #else
81 class IGraphicBufferProducer : public RefBase {
82 #endif
83 public:
84     enum {
85         // A flag returned by dequeueBuffer when the client needs to call
86         // requestBuffer immediately thereafter.
87         BUFFER_NEEDS_REALLOCATION = BufferQueueDefs::BUFFER_NEEDS_REALLOCATION,
88         // A flag returned by dequeueBuffer when all mirrored slots should be
89         // released by the client. This flag should always be processed first.
90         RELEASE_ALL_BUFFERS       = BufferQueueDefs::RELEASE_ALL_BUFFERS,
91     };
92 
93     enum {
94         // A parcelable magic indicates using Binder BufferQueue as transport
95         // backend.
96         USE_BUFFER_QUEUE = 0x62717565, // 'bque'
97         // A parcelable magic indicates using BufferHub as transport backend.
98         USE_BUFFER_HUB = 0x62687562, // 'bhub'
99     };
100 
101     // requestBuffer requests a new buffer for the given index. The server (i.e.
102     // the IGraphicBufferProducer implementation) assigns the newly created
103     // buffer to the given slot index, and the client is expected to mirror the
104     // slot->buffer mapping so that it's not necessary to transfer a
105     // GraphicBuffer for every dequeue operation.
106     //
107     // The slot must be in the range of [0, NUM_BUFFER_SLOTS).
108     //
109     // Return of a value other than NO_ERROR means an error has occurred:
110     // * NO_INIT - the buffer queue has been abandoned or the producer is not
111     //             connected.
112     // * BAD_VALUE - one of the two conditions occurred:
113     //              * slot was out of range (see above)
114     //              * buffer specified by the slot is not dequeued
115     virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf) = 0;
116 
117     // setMaxDequeuedBufferCount sets the maximum number of buffers that can be
118     // dequeued by the producer at one time. If this method succeeds, any new
119     // buffer slots will be both unallocated and owned by the BufferQueue object
120     // (i.e. they are not owned by the producer or consumer). Calling this may
121     // also cause some buffer slots to be emptied. If the caller is caching the
122     // contents of the buffer slots, it should empty that cache after calling
123     // this method.
124     //
125     // This function should not be called with a value of maxDequeuedBuffers
126     // that is less than the number of currently dequeued buffer slots. Doing so
127     // will result in a BAD_VALUE error.
128     //
129     // The buffer count should be at least 1 (inclusive), but at most
130     // (NUM_BUFFER_SLOTS - the minimum undequeued buffer count) (exclusive). The
131     // minimum undequeued buffer count can be obtained by calling
132     // query(NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS).
133     //
134     // Return of a value other than NO_ERROR means an error has occurred:
135     // * NO_INIT - the buffer queue has been abandoned.
136     // * BAD_VALUE - one of the below conditions occurred:
137     //     * bufferCount was out of range (see above).
138     //     * client would have more than the requested number of dequeued
139     //       buffers after this call.
140     //     * this call would cause the maxBufferCount value to be exceeded.
141     //     * failure to adjust the number of available slots.
142     virtual status_t setMaxDequeuedBufferCount(int maxDequeuedBuffers) = 0;
143 
144     // Set the async flag if the producer intends to asynchronously queue
145     // buffers without blocking. Typically this is used for triple-buffering
146     // and/or when the swap interval is set to zero.
147     //
148     // Enabling async mode will internally allocate an additional buffer to
149     // allow for the asynchronous behavior. If it is not enabled queue/dequeue
150     // calls may block.
151     //
152     // Return of a value other than NO_ERROR means an error has occurred:
153     // * NO_INIT - the buffer queue has been abandoned.
154     // * BAD_VALUE - one of the following has occurred:
155     //             * this call would cause the maxBufferCount value to be
156     //               exceeded
157     //             * failure to adjust the number of available slots.
158     virtual status_t setAsyncMode(bool async) = 0;
159 
160     // dequeueBuffer requests a new buffer slot for the client to use. Ownership
161     // of the slot is transfered to the client, meaning that the server will not
162     // use the contents of the buffer associated with that slot.
163     //
164     // The slot index returned may or may not contain a buffer (client-side).
165     // If the slot is empty the client should call requestBuffer to assign a new
166     // buffer to that slot.
167     //
168     // Once the client is done filling this buffer, it is expected to transfer
169     // buffer ownership back to the server with either cancelBuffer on
170     // the dequeued slot or to fill in the contents of its associated buffer
171     // contents and call queueBuffer.
172     //
173     // If dequeueBuffer returns the BUFFER_NEEDS_REALLOCATION flag, the client is
174     // expected to call requestBuffer immediately.
175     //
176     // If dequeueBuffer returns the RELEASE_ALL_BUFFERS flag, the client is
177     // expected to release all of the mirrored slot->buffer mappings.
178     //
179     // The fence parameter will be updated to hold the fence associated with
180     // the buffer. The contents of the buffer must not be overwritten until the
181     // fence signals. If the fence is Fence::NO_FENCE, the buffer may be written
182     // immediately.
183     //
184     // The width and height parameters must be no greater than the minimum of
185     // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
186     // An error due to invalid dimensions might not be reported until
187     // updateTexImage() is called.  If width and height are both zero, the
188     // default values specified by setDefaultBufferSize() are used instead.
189     //
190     // If the format is 0, the default format will be used.
191     //
192     // The usage argument specifies gralloc buffer usage flags.  The values
193     // are enumerated in <gralloc.h>, e.g. GRALLOC_USAGE_HW_RENDER.  These
194     // will be merged with the usage flags specified by
195     // IGraphicBufferConsumer::setConsumerUsageBits.
196     //
197     // This call will block until a buffer is available to be dequeued. If
198     // both the producer and consumer are controlled by the app, then this call
199     // can never block and will return WOULD_BLOCK if no buffer is available.
200     //
201     // A non-negative value with flags set (see above) will be returned upon
202     // success.
203     //
204     // Return of a negative means an error has occurred:
205     // * NO_INIT - the buffer queue has been abandoned or the producer is not
206     //             connected.
207     // * BAD_VALUE - both in async mode and buffer count was less than the
208     //               max numbers of buffers that can be allocated at once.
209     // * INVALID_OPERATION - cannot attach the buffer because it would cause
210     //                       too many buffers to be dequeued, either because
211     //                       the producer already has a single buffer dequeued
212     //                       and did not set a buffer count, or because a
213     //                       buffer count was set and this call would cause
214     //                       it to be exceeded.
215     // * WOULD_BLOCK - no buffer is currently available, and blocking is disabled
216     //                 since both the producer/consumer are controlled by app
217     // * NO_MEMORY - out of memory, cannot allocate the graphics buffer.
218     // * TIMED_OUT - the timeout set by setDequeueTimeout was exceeded while
219     //               waiting for a buffer to become available.
220     //
221     // All other negative values are an unknown error returned downstream
222     // from the graphics allocator (typically errno).
223     virtual status_t dequeueBuffer(int* slot, sp<Fence>* fence, uint32_t w, uint32_t h,
224                                    PixelFormat format, uint64_t usage, uint64_t* outBufferAge,
225                                    FrameEventHistoryDelta* outTimestamps) = 0;
226 
227     // detachBuffer attempts to remove all ownership of the buffer in the given
228     // slot from the buffer queue. If this call succeeds, the slot will be
229     // freed, and there will be no way to obtain the buffer from this interface.
230     // The freed slot will remain unallocated until either it is selected to
231     // hold a freshly allocated buffer in dequeueBuffer or a buffer is attached
232     // to the slot. The buffer must have already been dequeued, and the caller
233     // must already possesses the sp<GraphicBuffer> (i.e., must have called
234     // requestBuffer).
235     //
236     // Return of a value other than NO_ERROR means an error has occurred:
237     // * NO_INIT - the buffer queue has been abandoned or the producer is not
238     //             connected.
239     // * BAD_VALUE - the given slot number is invalid, either because it is
240     //               out of the range [0, NUM_BUFFER_SLOTS), or because the slot
241     //               it refers to is not currently dequeued and requested.
242     virtual status_t detachBuffer(int slot) = 0;
243 
244     // detachNextBuffer is equivalent to calling dequeueBuffer, requestBuffer,
245     // and detachBuffer in sequence, except for two things:
246     //
247     // 1) It is unnecessary to know the dimensions, format, or usage of the
248     //    next buffer.
249     // 2) It will not block, since if it cannot find an appropriate buffer to
250     //    return, it will return an error instead.
251     //
252     // Only slots that are free but still contain a GraphicBuffer will be
253     // considered, and the oldest of those will be returned. outBuffer is
254     // equivalent to outBuffer from the requestBuffer call, and outFence is
255     // equivalent to fence from the dequeueBuffer call.
256     //
257     // Return of a value other than NO_ERROR means an error has occurred:
258     // * NO_INIT - the buffer queue has been abandoned or the producer is not
259     //             connected.
260     // * BAD_VALUE - either outBuffer or outFence were NULL.
261     // * NO_MEMORY - no slots were found that were both free and contained a
262     //               GraphicBuffer.
263     virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
264             sp<Fence>* outFence) = 0;
265 
266     // attachBuffer attempts to transfer ownership of a buffer to the buffer
267     // queue. If this call succeeds, it will be as if this buffer was dequeued
268     // from the returned slot number. As such, this call will fail if attaching
269     // this buffer would cause too many buffers to be simultaneously dequeued.
270     //
271     // If attachBuffer returns the RELEASE_ALL_BUFFERS flag, the caller is
272     // expected to release all of the mirrored slot->buffer mappings.
273     //
274     // A non-negative value with flags set (see above) will be returned upon
275     // success.
276     //
277     // Return of a negative value means an error has occurred:
278     // * NO_INIT - the buffer queue has been abandoned or the producer is not
279     //             connected.
280     // * BAD_VALUE - outSlot or buffer were NULL, invalid combination of
281     //               async mode and buffer count override, or the generation
282     //               number of the buffer did not match the buffer queue.
283     // * INVALID_OPERATION - cannot attach the buffer because it would cause
284     //                       too many buffers to be dequeued, either because
285     //                       the producer already has a single buffer dequeued
286     //                       and did not set a buffer count, or because a
287     //                       buffer count was set and this call would cause
288     //                       it to be exceeded.
289     // * WOULD_BLOCK - no buffer slot is currently available, and blocking is
290     //                 disabled since both the producer/consumer are
291     //                 controlled by the app.
292     // * TIMED_OUT - the timeout set by setDequeueTimeout was exceeded while
293     //               waiting for a slot to become available.
294     virtual status_t attachBuffer(int* outSlot,
295             const sp<GraphicBuffer>& buffer) = 0;
296 
297     struct QueueBufferInput : public Flattenable<QueueBufferInput> {
QueueBufferInputQueueBufferInput298         explicit inline QueueBufferInput(const Parcel& parcel) {
299             parcel.read(*this);
300         }
301 
302         // timestamp - a monotonically increasing value in nanoseconds
303         // isAutoTimestamp - if the timestamp was synthesized at queue time
304         // dataSpace - description of the contents, interpretation depends on format
305         // crop - a crop rectangle that's used as a hint to the consumer
306         // scalingMode - a set of flags from NATIVE_WINDOW_SCALING_* in <window.h>
307         // transform - a set of flags from NATIVE_WINDOW_TRANSFORM_* in <window.h>
308         // fence - a fence that the consumer must wait on before reading the buffer,
309         //         set this to Fence::NO_FENCE if the buffer is ready immediately
310         // sticky - the sticky transform set in Surface (only used by the LEGACY
311         //          camera mode).
312         // getFrameTimestamps - whether or not the latest frame timestamps
313         //                      should be retrieved from the consumer.
314         // slot - the slot index to queue. This is used only by queueBuffers().
315         //        queueBuffer() ignores this value and uses the argument `slot`
316         //        instead.
317         inline QueueBufferInput(int64_t _timestamp, bool _isAutoTimestamp,
318                 android_dataspace _dataSpace, const Rect& _crop,
319                 int _scalingMode, uint32_t _transform, const sp<Fence>& _fence,
320                 uint32_t _sticky = 0, bool _getFrameTimestamps = false,
321                 int _slot = -1)
timestampQueueBufferInput322                 : timestamp(_timestamp), isAutoTimestamp(_isAutoTimestamp),
323                   dataSpace(_dataSpace), crop(_crop), scalingMode(_scalingMode),
324                   transform(_transform), stickyTransform(_sticky),
325                   fence(_fence), surfaceDamage(),
326                   getFrameTimestamps(_getFrameTimestamps), slot(_slot) { }
327 
328         QueueBufferInput() = default;
329 
330         inline void deflate(int64_t* outTimestamp, bool* outIsAutoTimestamp,
331                 android_dataspace* outDataSpace,
332                 Rect* outCrop, int* outScalingMode,
333                 uint32_t* outTransform, sp<Fence>* outFence,
334                 uint32_t* outStickyTransform = nullptr,
335                 bool* outGetFrameTimestamps = nullptr,
336                 int* outSlot = nullptr) const {
337             *outTimestamp = timestamp;
338             *outIsAutoTimestamp = bool(isAutoTimestamp);
339             *outDataSpace = dataSpace;
340             *outCrop = crop;
341             *outScalingMode = scalingMode;
342             *outTransform = transform;
343             *outFence = fence;
344             if (outStickyTransform != nullptr) {
345                 *outStickyTransform = stickyTransform;
346             }
347             if (outGetFrameTimestamps) {
348                 *outGetFrameTimestamps = getFrameTimestamps;
349             }
350             if (outSlot) {
351                 *outSlot = slot;
352             }
353         }
354 
355         // Flattenable protocol
356         static constexpr size_t minFlattenedSize();
357         size_t getFlattenedSize() const;
358         size_t getFdCount() const;
359         status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
360         status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
361 
getSurfaceDamageQueueBufferInput362         const Region& getSurfaceDamage() const { return surfaceDamage; }
setSurfaceDamageQueueBufferInput363         void setSurfaceDamage(const Region& damage) { surfaceDamage = damage; }
364 
getHdrMetadataQueueBufferInput365         const HdrMetadata& getHdrMetadata() const { return hdrMetadata; }
setHdrMetadataQueueBufferInput366         void setHdrMetadata(const HdrMetadata& metadata) { hdrMetadata = metadata; }
367 
368         int64_t timestamp{0};
369         int isAutoTimestamp{0};
370         android_dataspace dataSpace{HAL_DATASPACE_UNKNOWN};
371         Rect crop;
372         int scalingMode{0};
373         uint32_t transform{0};
374         uint32_t stickyTransform{0};
375         sp<Fence> fence;
376         Region surfaceDamage;
377         bool getFrameTimestamps{false};
378         int slot{-1};
379         HdrMetadata hdrMetadata;
380     };
381 
382     struct QueueBufferOutput : public Flattenable<QueueBufferOutput> {
383         QueueBufferOutput() = default;
384 
385         // Moveable.
386         QueueBufferOutput(QueueBufferOutput&& src) = default;
387         QueueBufferOutput& operator=(QueueBufferOutput&& src) = default;
388         // Not copyable.
389         QueueBufferOutput(const QueueBufferOutput& src) = delete;
390         QueueBufferOutput& operator=(const QueueBufferOutput& src) = delete;
391 
392         // Flattenable protocol
393         static constexpr size_t minFlattenedSize();
394         size_t getFlattenedSize() const;
395         size_t getFdCount() const;
396         status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
397         status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
398 
399         uint32_t width{0};
400         uint32_t height{0};
401         uint32_t transformHint{0};
402         uint32_t numPendingBuffers{0};
403         uint64_t nextFrameNumber{0};
404         FrameEventHistoryDelta frameTimestamps;
405         bool bufferReplaced{false};
406         int maxBufferCount{0};
407         status_t result{NO_ERROR};
408     };
409 
410     // queueBuffer indicates that the client has finished filling in the
411     // contents of the buffer associated with slot and transfers ownership of
412     // that slot back to the server.
413     //
414     // It is not valid to call queueBuffer on a slot that is not owned
415     // by the client or one for which a buffer associated via requestBuffer
416     // (an attempt to do so will fail with a return value of BAD_VALUE).
417     //
418     // In addition, the input must be described by the client (as documented
419     // below). Any other properties (zero point, etc)
420     // are client-dependent, and should be documented by the client.
421     //
422     // The slot must be in the range of [0, NUM_BUFFER_SLOTS).
423     //
424     // Upon success, the output will be filled with meaningful values
425     // (refer to the documentation below).
426     //
427     // Note: QueueBufferInput::slot was added to QueueBufferInput to be used by
428     // queueBuffers(), the batched version of queueBuffer(). The non-batched
429     // method (queueBuffer()) uses `slot` and ignores `input.slot`.
430     //
431     // Return of a value other than NO_ERROR means an error has occurred:
432     // * NO_INIT - the buffer queue has been abandoned or the producer is not
433     //             connected.
434     // * BAD_VALUE - one of the below conditions occurred:
435     //              * fence was NULL
436     //              * scaling mode was unknown
437     //              * both in async mode and buffer count was less than the
438     //                max numbers of buffers that can be allocated at once
439     //              * slot index was out of range (see above).
440     //              * the slot was not in the dequeued state
441     //              * the slot was enqueued without requesting a buffer
442     //              * crop rect is out of bounds of the buffer dimensions
443     virtual status_t queueBuffer(int slot, const QueueBufferInput& input,
444             QueueBufferOutput* output) = 0;
445 
446     // cancelBuffer indicates that the client does not wish to fill in the
447     // buffer associated with slot and transfers ownership of the slot back to
448     // the server.
449     //
450     // The buffer is not queued for use by the consumer.
451     //
452     // The slot must be in the range of [0, NUM_BUFFER_SLOTS).
453     //
454     // The buffer will not be overwritten until the fence signals.  The fence
455     // will usually be the one obtained from dequeueBuffer.
456     //
457     // Return of a value other than NO_ERROR means an error has occurred:
458     // * NO_INIT - the buffer queue has been abandoned or the producer is not
459     //             connected.
460     // * BAD_VALUE - one of the below conditions occurred:
461     //              * fence was NULL
462     //              * slot index was out of range (see above).
463     //              * the slot was not in the dequeued state
464     virtual status_t cancelBuffer(int slot, const sp<Fence>& fence) = 0;
465 
466     // query retrieves some information for this surface
467     // 'what' tokens allowed are that of NATIVE_WINDOW_* in <window.h>
468     //
469     // Return of a value other than NO_ERROR means an error has occurred:
470     // * NO_INIT - the buffer queue has been abandoned.
471     // * BAD_VALUE - what was out of range
472     virtual int query(int what, int* value) = 0;
473 
474     // connect attempts to connect a client API to the IGraphicBufferProducer.
475     // This must be called before any other IGraphicBufferProducer methods are
476     // called except for getAllocator. A consumer must be already connected.
477     //
478     // This method will fail if the connect was previously called on the
479     // IGraphicBufferProducer and no corresponding disconnect call was made.
480     //
481     // The listener is an optional binder callback object that can be used if
482     // the producer wants to be notified when the consumer releases a buffer
483     // back to the BufferQueue. It is also used to detect the death of the
484     // producer. If only the latter functionality is desired, there is a
485     // StubProducerListener class in IProducerListener.h that can be used.
486     //
487     // The api should be one of the NATIVE_WINDOW_API_* values in <window.h>
488     //
489     // The producerControlledByApp should be set to true if the producer is hosted
490     // by an untrusted process (typically app_process-forked processes). If both
491     // the producer and the consumer are app-controlled then all buffer queues
492     // will operate in async mode regardless of the async flag.
493     //
494     // Upon success, the output will be filled with meaningful data
495     // (refer to QueueBufferOutput documentation above).
496     //
497     // Return of a value other than NO_ERROR means an error has occurred:
498     // * NO_INIT - one of the following occurred:
499     //             * the buffer queue was abandoned
500     //             * no consumer has yet connected
501     // * BAD_VALUE - one of the following has occurred:
502     //             * the producer is already connected
503     //             * api was out of range (see above).
504     //             * output was NULL.
505     //             * Failure to adjust the number of available slots. This can
506     //               happen because of trying to allocate/deallocate the async
507     //               buffer in response to the value of producerControlledByApp.
508     // * DEAD_OBJECT - the token is hosted by an already-dead process
509     //
510     // Additional negative errors may be returned by the internals, they
511     // should be treated as opaque fatal unrecoverable errors.
512     virtual status_t connect(const sp<IProducerListener>& listener,
513             int api, bool producerControlledByApp, QueueBufferOutput* output) = 0;
514 
515     enum class DisconnectMode {
516         // Disconnect only the specified API.
517         Api,
518         // Disconnect any API originally connected from the process calling disconnect.
519         AllLocal
520     };
521 
522     // disconnect attempts to disconnect a client API from the
523     // IGraphicBufferProducer.  Calling this method will cause any subsequent
524     // calls to other IGraphicBufferProducer methods to fail except for
525     // getAllocator and connect.  Successfully calling connect after this will
526     // allow the other methods to succeed again.
527     //
528     // The api should be one of the NATIVE_WINDOW_API_* values in <window.h>
529     //
530     // Alternatively if mode is AllLocal, then the API value is ignored, and any API
531     // connected from the same PID calling disconnect will be disconnected.
532     //
533     // Disconnecting from an abandoned IGraphicBufferProducer is legal and
534     // is considered a no-op.
535     //
536     // Return of a value other than NO_ERROR means an error has occurred:
537     // * NO_INIT - the producer is not connected
538     // * BAD_VALUE - one of the following has occurred:
539     //             * the api specified does not match the one that was connected
540     //             * api was out of range (see above).
541     // * DEAD_OBJECT - the token is hosted by an already-dead process
542     virtual status_t disconnect(int api, DisconnectMode mode = DisconnectMode::Api) = 0;
543 
544     // Attaches a sideband buffer stream to the IGraphicBufferProducer.
545     //
546     // A sideband stream is a device-specific mechanism for passing buffers
547     // from the producer to the consumer without using dequeueBuffer/
548     // queueBuffer. If a sideband stream is present, the consumer can choose
549     // whether to acquire buffers from the sideband stream or from the queued
550     // buffers.
551     //
552     // Passing NULL or a different stream handle will detach the previous
553     // handle if any.
554     virtual status_t setSidebandStream(const sp<NativeHandle>& stream) = 0;
555 
556     // Allocates buffers based on the given dimensions/format.
557     //
558     // This function will allocate up to the maximum number of buffers
559     // permitted by the current BufferQueue configuration. It will use the
560     // given format, dimensions, and usage bits, which are interpreted in the
561     // same way as for dequeueBuffer, and the async flag must be set the same
562     // way as for dequeueBuffer to ensure that the correct number of buffers are
563     // allocated. This is most useful to avoid an allocation delay during
564     // dequeueBuffer. If there are already the maximum number of buffers
565     // allocated, this function has no effect.
566     virtual void allocateBuffers(uint32_t width, uint32_t height,
567             PixelFormat format, uint64_t usage) = 0;
568 
569     // Sets whether dequeueBuffer is allowed to allocate new buffers.
570     //
571     // Normally dequeueBuffer does not discriminate between free slots which
572     // already have an allocated buffer and those which do not, and will
573     // allocate a new buffer if the slot doesn't have a buffer or if the slot's
574     // buffer doesn't match the requested size, format, or usage. This method
575     // allows the producer to restrict the eligible slots to those which already
576     // have an allocated buffer of the correct size, format, and usage. If no
577     // eligible slot is available, dequeueBuffer will block or return an error
578     // as usual.
579     virtual status_t allowAllocation(bool allow) = 0;
580 
581     // Sets the current generation number of the BufferQueue.
582     //
583     // This generation number will be inserted into any buffers allocated by the
584     // BufferQueue, and any attempts to attach a buffer with a different
585     // generation number will fail. Buffers already in the queue are not
586     // affected and will retain their current generation number. The generation
587     // number defaults to 0.
588     virtual status_t setGenerationNumber(uint32_t generationNumber) = 0;
589 
590     // Returns the name of the connected consumer.
591     virtual String8 getConsumerName() const = 0;
592 
593     // Used to enable/disable shared buffer mode.
594     //
595     // When shared buffer mode is enabled the first buffer that is queued or
596     // dequeued will be cached and returned to all subsequent calls to
597     // dequeueBuffer and acquireBuffer. This allows the producer and consumer to
598     // simultaneously access the same buffer.
599     virtual status_t setSharedBufferMode(bool sharedBufferMode) = 0;
600 
601     // Used to enable/disable auto-refresh.
602     //
603     // Auto refresh has no effect outside of shared buffer mode. In shared
604     // buffer mode, when enabled, it indicates to the consumer that it should
605     // attempt to acquire buffers even if it is not aware of any being
606     // available.
607     virtual status_t setAutoRefresh(bool autoRefresh) = 0;
608 
609     // Sets how long dequeueBuffer will wait for a buffer to become available
610     // before returning an error (TIMED_OUT).
611     //
612     // This timeout also affects the attachBuffer call, which will block if
613     // there is not a free slot available into which the attached buffer can be
614     // placed.
615     //
616     // By default, the BufferQueue will wait forever, which is indicated by a
617     // timeout of -1. If set (to a value other than -1), this will disable
618     // non-blocking mode and its corresponding spare buffer (which is used to
619     // ensure a buffer is always available).
620     //
621     // Note well: queueBuffer will stop buffer dropping behavior if timeout is
622     // strictly positive. If timeout is zero or negative, previous buffer
623     // dropping behavior will not be changed.
624     //
625     // Return of a value other than NO_ERROR means an error has occurred:
626     // * BAD_VALUE - Failure to adjust the number of available slots. This can
627     //               happen because of trying to allocate/deallocate the async
628     //               buffer.
629     virtual status_t setDequeueTimeout(nsecs_t timeout) = 0;
630 
631     // Used to enable/disable buffer drop behavior of queueBuffer.
632     // If it's not used, legacy drop behavior will be retained.
633     virtual status_t setLegacyBufferDrop(bool drop);
634 
635     // Returns the last queued buffer along with a fence which must signal
636     // before the contents of the buffer are read. If there are no buffers in
637     // the queue, outBuffer will be populated with nullptr and outFence will be
638     // populated with Fence::NO_FENCE
639     //
640     // outTransformMatrix is not modified if outBuffer is null.
641     //
642     // Returns NO_ERROR or the status of the Binder transaction
643     virtual status_t getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
644             sp<Fence>* outFence, float outTransformMatrix[16]) = 0;
645 
646     // Returns the last queued buffer along with a fence which must signal
647     // before the contents of the buffer are read. If there are no buffers in
648     // the queue, outBuffer will be populated with nullptr and outFence will be
649     // populated with Fence::NO_FENCE
650     //
651     // outRect & outTransform are not modified if outBuffer is null.
652     //
653     // Returns NO_ERROR or the status of the Binder transaction
getLastQueuedBuffer(sp<GraphicBuffer> * outBuffer,sp<Fence> * outFence,Rect * outRect,uint32_t * outTransform)654     virtual status_t getLastQueuedBuffer([[maybe_unused]] sp<GraphicBuffer>* outBuffer,
655                                          [[maybe_unused]] sp<Fence>* outFence,
656                                          [[maybe_unused]] Rect* outRect,
657                                          [[maybe_unused]] uint32_t* outTransform) {
658         // Too many things implement IGraphicBufferProducer...
659         return UNKNOWN_TRANSACTION;
660     }
661 
662     // Gets the frame events that haven't already been retrieved.
getFrameTimestamps(FrameEventHistoryDelta *)663     virtual void getFrameTimestamps(FrameEventHistoryDelta* /*outDelta*/) {}
664 
665     // Returns a unique id for this BufferQueue
666     virtual status_t getUniqueId(uint64_t* outId) const = 0;
667 
668     // Returns the consumer usage flags for this BufferQueue. This returns the
669     // full 64-bit usage flags, rather than the truncated 32-bit usage flags
670     // returned by querying the now deprecated
671     // NATIVE_WINDOW_CONSUMER_USAGE_BITS attribute.
672     virtual status_t getConsumerUsage(uint64_t* outUsage) const = 0;
673 
674     // Enable/disable the auto prerotation at buffer allocation when the buffer
675     // size is driven by the consumer.
676     //
677     // When buffer size is driven by the consumer and the transform hint
678     // specifies a 90 or 270 degree rotation, if auto prerotation is enabled,
679     // the width and height used for dequeueBuffer will be additionally swapped.
680     virtual status_t setAutoPrerotation(bool autoPrerotation);
681 
682 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_SETFRAMERATE)
683     // Sets the apps intended frame rate.
684     virtual status_t setFrameRate(float frameRate, int8_t compatibility,
685                                   int8_t changeFrameRateStrategy);
686 #endif
687 
688 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
689     virtual status_t setAdditionalOptions(const std::vector<gui::AdditionalOptions>& options);
690 #endif
691 
692     struct RequestBufferOutput : public Flattenable<RequestBufferOutput> {
693         RequestBufferOutput() = default;
694 
695         // Flattenable protocol
696         static constexpr size_t minFlattenedSize();
697         size_t getFlattenedSize() const;
698         size_t getFdCount() const;
699         status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
700         status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
701 
702         status_t result;
703         sp<GraphicBuffer> buffer;
704     };
705 
706     // Batched version of requestBuffer().
707     // This method behaves like a sequence of requestBuffer() calls.
708     // The return value of the batched method will only be about the
709     // transaction. For a local call, the return value will always be NO_ERROR.
710     virtual status_t requestBuffers(
711             const std::vector<int32_t>& slots,
712             std::vector<RequestBufferOutput>* outputs);
713 
714     struct DequeueBufferInput : public LightFlattenable<DequeueBufferInput> {
715         DequeueBufferInput() = default;
716 
717         // LightFlattenable protocol
isFixedSizeDequeueBufferInput718         inline bool isFixedSize() const { return true; }
719         size_t getFlattenedSize() const;
720         status_t flatten(void* buffer, size_t size) const;
721         status_t unflatten(void const* buffer, size_t size);
722 
723         uint32_t width;
724         uint32_t height;
725         PixelFormat format;
726         uint64_t usage;
727         bool getTimestamps;
728     };
729 
730     struct DequeueBufferOutput : public Flattenable<DequeueBufferOutput> {
731         DequeueBufferOutput() = default;
732 
733         // Flattenable protocol
734         static constexpr size_t minFlattenedSize();
735         size_t getFlattenedSize() const;
736         size_t getFdCount() const;
737         status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
738         status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
739 
740         status_t result;
741         int slot = -1;
742         sp<Fence> fence = Fence::NO_FENCE;
743         uint64_t bufferAge;
744         std::optional<FrameEventHistoryDelta> timestamps;
745     };
746 
747     // Batched version of dequeueBuffer().
748     // This method behaves like a sequence of dequeueBuffer() calls.
749     // The return value of the batched method will only be about the
750     // transaction. For a local call, the return value will always be NO_ERROR.
751     virtual status_t dequeueBuffers(
752             const std::vector<DequeueBufferInput>& inputs,
753             std::vector<DequeueBufferOutput>* outputs);
754 
755     // Batched version of detachBuffer().
756     // This method behaves like a sequence of detachBuffer() calls.
757     // The return value of the batched method will only be about the
758     // transaction. For a local call, the return value will always be NO_ERROR.
759     virtual status_t detachBuffers(const std::vector<int32_t>& slots,
760                                    std::vector<status_t>* results);
761 
762 
763     struct AttachBufferOutput : public LightFlattenable<AttachBufferOutput> {
764         AttachBufferOutput() = default;
765 
766         // LightFlattenable protocol
isFixedSizeAttachBufferOutput767         inline bool isFixedSize() const { return true; }
768         size_t getFlattenedSize() const;
769         status_t flatten(void* buffer, size_t size) const;
770         status_t unflatten(void const* buffer, size_t size);
771 
772         status_t result;
773         int slot;
774     };
775     // Batched version of attachBuffer().
776     // This method behaves like a sequence of attachBuffer() calls.
777     // The return value of the batched method will only be about the
778     // transaction. For a local call, the return value will always be NO_ERROR.
779     virtual status_t attachBuffers(
780             const std::vector<sp<GraphicBuffer>>& buffers,
781             std::vector<AttachBufferOutput>* outputs);
782 
783     // Batched version of queueBuffer().
784     // This method behaves like a sequence of queueBuffer() calls.
785     // The return value of the batched method will only be about the
786     // transaction. For a local call, the return value will always be NO_ERROR.
787     //
788     // Note: QueueBufferInput::slot was added to QueueBufferInput to include the
789     // `slot` input argument of the non-batched method queueBuffer().
790     virtual status_t queueBuffers(const std::vector<QueueBufferInput>& inputs,
791                                   std::vector<QueueBufferOutput>* outputs);
792 
793     struct CancelBufferInput : public Flattenable<CancelBufferInput> {
794         CancelBufferInput() = default;
795 
796         // Flattenable protocol
797         static constexpr size_t minFlattenedSize();
798         size_t getFlattenedSize() const;
799         size_t getFdCount() const;
800         status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
801         status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
802 
803         int slot;
804         sp<Fence> fence;
805     };
806     // Batched version of cancelBuffer().
807     // This method behaves like a sequence of cancelBuffer() calls.
808     // The return value of the batched method will only be about the
809     // transaction. For a local call, the return value will always be NO_ERROR.
810     virtual status_t cancelBuffers(
811             const std::vector<CancelBufferInput>& inputs,
812             std::vector<status_t>* results);
813 
814     struct QueryOutput : public LightFlattenable<QueryOutput> {
815         QueryOutput() = default;
816 
817         // LightFlattenable protocol
isFixedSizeQueryOutput818         inline bool isFixedSize() const { return true; }
819         size_t getFlattenedSize() const;
820         status_t flatten(void* buffer, size_t size) const;
821         status_t unflatten(void const* buffer, size_t size);
822 
823         status_t result;
824         int64_t value;
825     };
826     // Batched version of query().
827     // This method behaves like a sequence of query() calls.
828     // The return value of the batched method will only be about the
829     // transaction. For a local call, the return value will always be NO_ERROR.
830     virtual status_t query(const std::vector<int32_t> inputs,
831                            std::vector<QueryOutput>* outputs);
832 
833 #ifndef NO_BINDER
834     // Static method exports any IGraphicBufferProducer object to a parcel. It
835     // handles null producer as well.
836     static status_t exportToParcel(const sp<IGraphicBufferProducer>& producer,
837                                    Parcel* parcel);
838 
839     // Factory method that creates a new IBGP instance from the parcel.
840     static sp<IGraphicBufferProducer> createFromParcel(const Parcel* parcel);
841 
842 protected:
843     // Exports the current producer as a binder parcelable object. Note that the
844     // producer must be disconnected to be exportable. After successful export,
845     // the producer queue can no longer be connected again. Returns NO_ERROR
846     // when the export is successful and writes an implementation defined
847     // parcelable object into the parcel. For traditional Android BufferQueue,
848     // it writes a strong binder object; for BufferHub, it writes a
849     // ProducerQueueParcelable object.
850     virtual status_t exportToParcel(Parcel* parcel);
851 #endif
852 };
853 
854 // ----------------------------------------------------------------------------
855 #ifndef NO_BINDER
856 class BnGraphicBufferProducer : public BnInterface<IGraphicBufferProducer>
857 {
858 public:
859     virtual status_t    onTransact( uint32_t code,
860                                     const Parcel& data,
861                                     Parcel* reply,
862                                     uint32_t flags = 0);
863 };
864 #else
865 class BnGraphicBufferProducer : public IGraphicBufferProducer {
866 };
867 #endif
868 
869 // ----------------------------------------------------------------------------
870 }; // namespace android
871 
872 #endif // ANDROID_GUI_IGRAPHICBUFFERPRODUCER_H
873