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