• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_SURFACE_H
18 #define ANDROID_GUI_SURFACE_H
19 
20 #include <android/gui/FrameTimelineInfo.h>
21 #include <com_android_graphics_libgui_flags.h>
22 #include <gui/BufferQueueDefs.h>
23 #include <gui/HdrMetadata.h>
24 #include <gui/IGraphicBufferProducer.h>
25 #include <gui/IProducerListener.h>
26 #include <system/window.h>
27 #include <ui/ANativeObjectBase.h>
28 #include <ui/GraphicTypes.h>
29 #include <ui/Region.h>
30 #include <utils/Condition.h>
31 #include <utils/Mutex.h>
32 #include <utils/RefBase.h>
33 
34 #include <shared_mutex>
35 #include <unordered_set>
36 
37 namespace android {
38 
39 class GraphicBuffer;
40 
41 namespace gui {
42 class ISurfaceComposer;
43 } // namespace gui
44 
45 class ISurfaceComposer;
46 
47 using gui::FrameTimelineInfo;
48 
49 /* This is the same as ProducerListener except that onBuffersDiscarded is
50  * called with a vector of graphic buffers instead of buffer slots.
51  */
52 class SurfaceListener : public virtual RefBase
53 {
54 public:
55     SurfaceListener() = default;
56     virtual ~SurfaceListener() = default;
57 
58     virtual void onBufferReleased() = 0;
59     virtual bool needsReleaseNotify() = 0;
60 
61     virtual void onBuffersDiscarded(const std::vector<sp<GraphicBuffer>>& buffers) = 0;
62     virtual void onBufferDetached(int slot) = 0;
63 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_CONSUMER_ATTACH_CALLBACK)
onBufferAttached()64     virtual void onBufferAttached() {}
needsAttachNotify()65     virtual bool needsAttachNotify() { return false; }
66 #endif
67 
68 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
69     // Called if this Surface is connected to a remote implementation and it
70     // dies or becomes unavailable.
onRemoteDied()71     virtual void onRemoteDied() {}
72 
73     // Clients will overwrite this if they want to receive a notification
74     // via onRemoteDied. This should return a constant value.
needsDeathNotify()75     virtual bool needsDeathNotify() { return false; }
76 #endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
77 };
78 
79 class StubSurfaceListener : public SurfaceListener {
80 public:
~StubSurfaceListener()81     virtual ~StubSurfaceListener() {}
onBufferReleased()82     virtual void onBufferReleased() override {}
needsReleaseNotify()83     virtual bool needsReleaseNotify() { return false; }
onBuffersDiscarded(const std::vector<sp<GraphicBuffer>> &)84     virtual void onBuffersDiscarded(const std::vector<sp<GraphicBuffer>>& /*buffers*/) override {}
onBufferDetached(int)85     virtual void onBufferDetached(int /*slot*/) override {}
86 };
87 
88 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
89 // Contains additional data from the queueBuffer operation.
90 struct SurfaceQueueBufferOutput {
91     // True if this queueBuffer caused a buffer to be replaced in the queue
92     // (and therefore not will not be acquired)
93     bool bufferReplaced = false;
94 };
95 #endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
96 
97 /*
98  * An implementation of ANativeWindow that feeds graphics buffers into a
99  * BufferQueue.
100  *
101  * This is typically used by programs that want to render frames through
102  * some means (maybe OpenGL, a software renderer, or a hardware decoder)
103  * and have the frames they create forwarded to SurfaceFlinger for
104  * compositing.  For example, a video decoder could render a frame and call
105  * eglSwapBuffers(), which invokes ANativeWindow callbacks defined by
106  * Surface.  Surface then forwards the buffers through Binder IPC
107  * to the BufferQueue's producer interface, providing the new frame to a
108  * consumer such as GLConsumer.
109  */
110 class Surface
111     : public ANativeObjectBase<ANativeWindow, Surface, RefBase>
112 {
113 public:
114     /*
115      * creates a Surface from the given IGraphicBufferProducer (which concrete
116      * implementation is a BufferQueue).
117      *
118      * Surface is mainly state-less while it's disconnected, it can be
119      * viewed as a glorified IGraphicBufferProducer holder. It's therefore
120      * safe to create other Surfaces from the same IGraphicBufferProducer.
121      *
122      * However, once a Surface is connected, it'll prevent other Surfaces
123      * referring to the same IGraphicBufferProducer to become connected and
124      * therefore prevent them to be used as actual producers of buffers.
125      *
126      * the controlledByApp flag indicates that this Surface (producer) is
127      * controlled by the application. This flag is used at connect time.
128      *
129      * Pass in the SurfaceControlHandle to store a weak reference to the layer
130      * that the Surface was created from. This handle can be used to create a
131      * child surface without using the IGBP to identify the layer. This is used
132      * for surfaces created by the BlastBufferQueue whose IGBP is created on the
133      * client and cannot be verified in SF.
134      */
135     explicit Surface(const sp<IGraphicBufferProducer>& bufferProducer, bool controlledByApp = false,
136                      const sp<IBinder>& surfaceControlHandle = nullptr);
137 
138     /* getIGraphicBufferProducer() returns the IGraphicBufferProducer this
139      * Surface was created with. Usually it's an error to use the
140      * IGraphicBufferProducer while the Surface is connected.
141      */
142     sp<IGraphicBufferProducer> getIGraphicBufferProducer() const;
143 
144     sp<IBinder> getSurfaceControlHandle() const;
145 
146     /* convenience function to check that the given surface is non NULL as
147      * well as its IGraphicBufferProducer */
isValid(const sp<Surface> & surface)148     static bool isValid(const sp<Surface>& surface) {
149         return surface != nullptr && surface->getIGraphicBufferProducer() != nullptr;
150     }
151 
getIGraphicBufferProducer(ANativeWindow * window)152     static sp<IGraphicBufferProducer> getIGraphicBufferProducer(ANativeWindow* window) {
153         int val;
154         if (window->query(window, NATIVE_WINDOW_CONCRETE_TYPE, &val) >= 0 &&
155             val == NATIVE_WINDOW_SURFACE) {
156             return ((Surface*) window)->mGraphicBufferProducer;
157         }
158         return nullptr;
159     }
160 
getSurfaceControlHandle(ANativeWindow * window)161     static sp<IBinder> getSurfaceControlHandle(ANativeWindow* window) {
162         int val;
163         if (window->query(window, NATIVE_WINDOW_CONCRETE_TYPE, &val) >= 0 &&
164             val == NATIVE_WINDOW_SURFACE) {
165             return ((Surface*) window)->mSurfaceControlHandle;
166         }
167         return nullptr;
168     }
169 
170     /* Attaches a sideband buffer stream to the Surface's IGraphicBufferProducer.
171      *
172      * A sideband stream is a device-specific mechanism for passing buffers
173      * from the producer to the consumer without using dequeueBuffer/
174      * queueBuffer. If a sideband stream is present, the consumer can choose
175      * whether to acquire buffers from the sideband stream or from the queued
176      * buffers.
177      *
178      * Passing NULL or a different stream handle will detach the previous
179      * handle if any.
180      */
181     void setSidebandStream(const sp<NativeHandle>& stream);
182 
183     /* Allocates buffers based on the current dimensions/format.
184      *
185      * This function will allocate up to the maximum number of buffers
186      * permitted by the current BufferQueue configuration. It will use the
187      * default format and dimensions. This is most useful to avoid an allocation
188      * delay during dequeueBuffer. If there are already the maximum number of
189      * buffers allocated, this function has no effect.
190      */
191     virtual void allocateBuffers();
192 
193 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
194     // See IGraphicBufferProducer::allowAllocation
195     status_t allowAllocation(bool allowAllocation);
196 #endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
197 
198     /* Sets the generation number on the IGraphicBufferProducer and updates the
199      * generation number on any buffers attached to the Surface after this call.
200      * See IGBP::setGenerationNumber for more information. */
201     status_t setGenerationNumber(uint32_t generationNumber);
202 
203     // See IGraphicBufferProducer::getConsumerName
204     String8 getConsumerName() const;
205 
206     // See IGraphicBufferProducer::getNextFrameNumber
207     uint64_t getNextFrameNumber() const;
208 
209     /* Set the scaling mode to be used with a Surface.
210      * See NATIVE_WINDOW_SET_SCALING_MODE and its parameters
211      * in <system/window.h>. */
212     int setScalingMode(int mode);
213 
214     virtual int setBuffersTimestamp(int64_t timestamp);
215     virtual int setBuffersDataSpace(ui::Dataspace dataSpace);
216     virtual int setCrop(Rect const* rect);
217     virtual int setBuffersTransform(uint32_t transform);
218     virtual int setBuffersStickyTransform(uint32_t transform);
219     virtual int setBuffersFormat(PixelFormat format);
220     virtual int setUsage(uint64_t reqUsage);
221 
222     // See IGraphicBufferProducer::setDequeueTimeout
223     status_t setDequeueTimeout(nsecs_t timeout);
224 
225     /*
226      * Wait for frame number to increase past lastFrame for at most
227      * timeoutNs. Useful for one thread to wait for another unknown
228      * thread to queue a buffer.
229      */
230     bool waitForNextFrame(uint64_t lastFrame, nsecs_t timeout);
231 
232     // See IGraphicBufferProducer::getLastQueuedBuffer
233     // See GLConsumer::getTransformMatrix for outTransformMatrix format
234     status_t getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
235             sp<Fence>* outFence, float outTransformMatrix[16]);
236 
237     status_t getDisplayRefreshCycleDuration(nsecs_t* outRefreshDuration);
238 
239     /* Enables or disables frame timestamp tracking. It is disabled by default
240      * to avoid overhead during queue and dequeue for applications that don't
241      * need the feature. If disabled, calls to getFrameTimestamps will fail.
242      */
243     void enableFrameTimestamps(bool enable);
244 
245     status_t getCompositorTiming(
246             nsecs_t* compositeDeadline, nsecs_t* compositeInterval,
247             nsecs_t* compositeToPresentLatency);
248 
249     // See IGraphicBufferProducer::getFrameTimestamps
250     status_t getFrameTimestamps(uint64_t frameNumber,
251             nsecs_t* outRequestedPresentTime, nsecs_t* outAcquireTime,
252             nsecs_t* outLatchTime, nsecs_t* outFirstRefreshStartTime,
253             nsecs_t* outLastRefreshStartTime, nsecs_t* outGlCompositionDoneTime,
254             nsecs_t* outDisplayPresentTime, nsecs_t* outDequeueReadyTime,
255             nsecs_t* outReleaseTime);
256 
257     status_t getWideColorSupport(bool* supported) __attribute__((__deprecated__));
258     status_t getHdrSupport(bool* supported) __attribute__((__deprecated__));
259 
260     status_t getUniqueId(uint64_t* outId) const;
261     status_t getConsumerUsage(uint64_t* outUsage) const;
262 
263     virtual status_t setFrameRate(float frameRate, int8_t compatibility,
264                                   int8_t changeFrameRateStrategy);
265     virtual status_t setFrameTimelineInfo(uint64_t frameNumber, const FrameTimelineInfo& info);
266 
267 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
268     /**
269      * Set additional options to be passed when allocating a buffer. Only valid if IAllocator-V2
270      * or newer is available, otherwise will return INVALID_OPERATION. Only allowed to be called
271      * after connect and options are cleared when disconnect happens. Returns NO_INIT if not
272      * connected
273      */
274     status_t setAdditionalOptions(const std::vector<gui::AdditionalOptions>& options);
275 #endif
276 
277 protected:
278     virtual ~Surface();
279 
280     // Virtual for testing.
281     virtual sp<ISurfaceComposer> composerService() const;
282     virtual sp<gui::ISurfaceComposer> composerServiceAIDL() const;
283     virtual nsecs_t now() const;
284 
285 private:
286     // can't be copied
287     Surface& operator = (const Surface& rhs);
288     Surface(const Surface& rhs);
289 
290     // ANativeWindow hooks
291     static int hook_cancelBuffer(ANativeWindow* window,
292             ANativeWindowBuffer* buffer, int fenceFd);
293     static int hook_dequeueBuffer(ANativeWindow* window,
294             ANativeWindowBuffer** buffer, int* fenceFd);
295     static int hook_perform(ANativeWindow* window, int operation, ...);
296     static int hook_query(const ANativeWindow* window, int what, int* value);
297     static int hook_queueBuffer(ANativeWindow* window,
298             ANativeWindowBuffer* buffer, int fenceFd);
299     static int hook_setSwapInterval(ANativeWindow* window, int interval);
300 
301     static int cancelBufferInternal(ANativeWindow* window, ANativeWindowBuffer* buffer,
302                                     int fenceFd);
303     static int dequeueBufferInternal(ANativeWindow* window, ANativeWindowBuffer** buffer,
304                                      int* fenceFd);
305     static int performInternal(ANativeWindow* window, int operation, va_list args);
306     static int queueBufferInternal(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd);
307     static int queryInternal(const ANativeWindow* window, int what, int* value);
308 
309     static int hook_cancelBuffer_DEPRECATED(ANativeWindow* window,
310             ANativeWindowBuffer* buffer);
311     static int hook_dequeueBuffer_DEPRECATED(ANativeWindow* window,
312             ANativeWindowBuffer** buffer);
313     static int hook_lockBuffer_DEPRECATED(ANativeWindow* window,
314             ANativeWindowBuffer* buffer);
315     static int hook_queueBuffer_DEPRECATED(ANativeWindow* window,
316             ANativeWindowBuffer* buffer);
317 
318     int dispatchConnect(va_list args);
319     int dispatchDisconnect(va_list args);
320     int dispatchSetBufferCount(va_list args);
321     int dispatchSetBuffersGeometry(va_list args);
322     int dispatchSetBuffersDimensions(va_list args);
323     int dispatchSetBuffersUserDimensions(va_list args);
324     int dispatchSetBuffersFormat(va_list args);
325     int dispatchSetScalingMode(va_list args);
326     int dispatchSetBuffersTransform(va_list args);
327     int dispatchSetBuffersStickyTransform(va_list args);
328     int dispatchSetBuffersTimestamp(va_list args);
329     int dispatchSetCrop(va_list args);
330     int dispatchSetUsage(va_list args);
331     int dispatchSetUsage64(va_list args);
332     int dispatchLock(va_list args);
333     int dispatchUnlockAndPost(va_list args);
334     int dispatchSetSidebandStream(va_list args);
335     int dispatchSetBuffersDataSpace(va_list args);
336     int dispatchSetBuffersSmpte2086Metadata(va_list args);
337     int dispatchSetBuffersCta8613Metadata(va_list args);
338     int dispatchSetBuffersHdr10PlusMetadata(va_list args);
339     int dispatchSetSurfaceDamage(va_list args);
340     int dispatchSetSharedBufferMode(va_list args);
341     int dispatchSetAutoRefresh(va_list args);
342     int dispatchGetDisplayRefreshCycleDuration(va_list args);
343     int dispatchGetNextFrameId(va_list args);
344     int dispatchEnableFrameTimestamps(va_list args);
345     int dispatchGetCompositorTiming(va_list args);
346     int dispatchGetFrameTimestamps(va_list args);
347     int dispatchGetWideColorSupport(va_list args);
348     int dispatchGetHdrSupport(va_list args);
349     int dispatchGetConsumerUsage64(va_list args);
350     int dispatchSetAutoPrerotation(va_list args);
351     int dispatchGetLastDequeueStartTime(va_list args);
352     int dispatchSetDequeueTimeout(va_list args);
353     int dispatchGetLastDequeueDuration(va_list args);
354     int dispatchGetLastQueueDuration(va_list args);
355     int dispatchSetFrameRate(va_list args);
356     int dispatchAddCancelInterceptor(va_list args);
357     int dispatchAddDequeueInterceptor(va_list args);
358     int dispatchAddPerformInterceptor(va_list args);
359     int dispatchAddQueueInterceptor(va_list args);
360     int dispatchAddQueryInterceptor(va_list args);
361     int dispatchGetLastQueuedBuffer(va_list args);
362     int dispatchGetLastQueuedBuffer2(va_list args);
363     int dispatchSetFrameTimelineInfo(va_list args);
364     int dispatchSetAdditionalOptions(va_list args);
365 
366     std::mutex mNameMutex;
367     std::string mName;
368     const char* getDebugName();
369 
370 protected:
371     virtual int dequeueBuffer(ANativeWindowBuffer** buffer, int* fenceFd);
372     virtual int cancelBuffer(ANativeWindowBuffer* buffer, int fenceFd);
373 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
374     virtual int queueBuffer(ANativeWindowBuffer* buffer, int fenceFd,
375                             SurfaceQueueBufferOutput* surfaceOutput = nullptr);
376 #else
377     virtual int queueBuffer(ANativeWindowBuffer* buffer, int fenceFd);
378 #endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
379     virtual int perform(int operation, va_list args);
380     virtual int setSwapInterval(int interval);
381 
382     virtual int lockBuffer_DEPRECATED(ANativeWindowBuffer* buffer);
383 
384     virtual int connect(int api);
385     virtual int setBufferCount(int bufferCount);
386     virtual int setBuffersUserDimensions(uint32_t width, uint32_t height);
387     virtual int setBuffersSmpte2086Metadata(const android_smpte2086_metadata* metadata);
388     virtual int setBuffersCta8613Metadata(const android_cta861_3_metadata* metadata);
389     virtual int setBuffersHdr10PlusMetadata(const size_t size, const uint8_t* metadata);
390     virtual void setSurfaceDamage(android_native_rect_t* rects, size_t numRects);
391 
392 public:
393     virtual int disconnect(int api,
394             IGraphicBufferProducer::DisconnectMode mode =
395                     IGraphicBufferProducer::DisconnectMode::Api);
396 
397     virtual int setMaxDequeuedBufferCount(int maxDequeuedBuffers);
398     virtual int setAsyncMode(bool async);
399     virtual int setSharedBufferMode(bool sharedBufferMode);
400     virtual int setAutoRefresh(bool autoRefresh);
401     virtual int setAutoPrerotation(bool autoPrerotation);
402     virtual int setBuffersDimensions(uint32_t width, uint32_t height);
403     virtual int lock(ANativeWindow_Buffer* outBuffer, ARect* inOutDirtyBounds);
404     virtual int unlockAndPost();
405     virtual int query(int what, int* value) const;
406 
407     // When reportBufferRemoval is true, clients must call getAndFlushRemovedBuffers to fetch
408     // GraphicBuffers removed from this surface after a dequeueBuffer, detachNextBuffer or
409     // attachBuffer call. This allows clients with their own buffer caches to free up buffers no
410     // longer in use by this surface.
411     virtual int connect(int api, const sp<SurfaceListener>& listener,
412                         bool reportBufferRemoval = false);
413     virtual int detachNextBuffer(sp<GraphicBuffer>* outBuffer, sp<Fence>* outFence);
414     virtual int attachBuffer(ANativeWindowBuffer*);
415 
416     virtual void destroy();
417 
418     // When client connects to Surface with reportBufferRemoval set to true, any buffers removed
419     // from this Surface will be collected and returned here. Once this method returns, these
420     // buffers will no longer be referenced by this Surface unless they are attached to this
421     // Surface later. The list of removed buffers will only be stored until the next dequeueBuffer,
422     // detachNextBuffer, or attachBuffer call.
423     status_t getAndFlushRemovedBuffers(std::vector<sp<GraphicBuffer>>* out);
424 
425     ui::Dataspace getBuffersDataSpace();
426 
427     static status_t attachAndQueueBufferWithDataspace(Surface* surface, sp<GraphicBuffer> buffer,
428                                                       ui::Dataspace dataspace);
429 
430 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
431     // Dequeues a buffer and its outFence, which must be signalled before the buffer can be used.
432     status_t dequeueBuffer(sp<GraphicBuffer>* buffer, sp<Fence>* outFence);
433 
434     // Queues a buffer, with an optional fd fence that captures pending work on the buffer. This
435     // buffer must have been returned by dequeueBuffer or associated with this Surface via an
436     // attachBuffer operation.
437     status_t queueBuffer(const sp<GraphicBuffer>& buffer, const sp<Fence>& fd = Fence::NO_FENCE,
438                          SurfaceQueueBufferOutput* output = nullptr);
439 
440     // Detaches this buffer, dissociating it from this Surface. This buffer must have been returned
441     // by queueBuffer or associated with this Surface via an attachBuffer operation.
442     status_t detachBuffer(const sp<GraphicBuffer>& buffer);
443 #endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
444 
445     // Sets outIsOwned to true if the given buffer is currently known to be owned by this Surface.
446     status_t isBufferOwned(const sp<GraphicBuffer>& buffer, bool* outIsOwned) const;
447 
448     // Batch version of dequeueBuffer, cancelBuffer and queueBuffer
449     // Note that these batched operations are not supported when shared buffer mode is being used.
450     struct BatchBuffer {
451         ANativeWindowBuffer* buffer = nullptr;
452         int fenceFd = -1;
453     };
454     virtual int dequeueBuffers(std::vector<BatchBuffer>* buffers);
455     virtual int cancelBuffers(const std::vector<BatchBuffer>& buffers);
456 
457     struct BatchQueuedBuffer {
458         ANativeWindowBuffer* buffer = nullptr;
459         int fenceFd = -1;
460         nsecs_t timestamp = NATIVE_WINDOW_TIMESTAMP_AUTO;
461     };
462 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
463     virtual int queueBuffers(const std::vector<BatchQueuedBuffer>& buffers,
464                              std::vector<SurfaceQueueBufferOutput>* queueBufferOutputs = nullptr);
465 #else
466     virtual int queueBuffers(
467             const std::vector<BatchQueuedBuffer>& buffers);
468 #endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
469 
470 protected:
471     enum { NUM_BUFFER_SLOTS = BufferQueueDefs::NUM_BUFFER_SLOTS };
472     enum { DEFAULT_FORMAT = PIXEL_FORMAT_RGBA_8888 };
473 
474     class ProducerListenerProxy : public BnProducerListener {
475     public:
ProducerListenerProxy(wp<Surface> parent,sp<SurfaceListener> listener)476         ProducerListenerProxy(wp<Surface> parent, sp<SurfaceListener> listener)
477                : mParent(parent), mSurfaceListener(listener) {}
~ProducerListenerProxy()478         virtual ~ProducerListenerProxy() {}
479 
onBufferReleased()480         virtual void onBufferReleased() {
481             mSurfaceListener->onBufferReleased();
482         }
483 
needsReleaseNotify()484         virtual bool needsReleaseNotify() {
485             return mSurfaceListener->needsReleaseNotify();
486         }
487 
onBufferDetached(int slot)488         virtual void onBufferDetached(int slot) { mSurfaceListener->onBufferDetached(slot); }
489 
490         virtual void onBuffersDiscarded(const std::vector<int32_t>& slots);
491 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_CONSUMER_ATTACH_CALLBACK)
onBufferAttached()492         virtual void onBufferAttached() {
493             mSurfaceListener->onBufferAttached();
494         }
495 
needsAttachNotify()496         virtual bool needsAttachNotify() {
497             return mSurfaceListener->needsAttachNotify();
498         }
499 #endif
500     private:
501         wp<Surface> mParent;
502         sp<SurfaceListener> mSurfaceListener;
503     };
504 
505 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
506     class ProducerDeathListenerProxy : public IBinder::DeathRecipient {
507     public:
508         ProducerDeathListenerProxy(wp<SurfaceListener> surfaceListener);
509         ProducerDeathListenerProxy(ProducerDeathListenerProxy&) = delete;
510 
511         // IBinder::DeathRecipient
512         virtual void binderDied(const wp<IBinder>&) override;
513 
514     private:
515         wp<SurfaceListener> mSurfaceListener;
516     };
517     friend class ProducerDeathListenerProxy;
518 #endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
519 
520     void querySupportedTimestampsLocked() const;
521 
522     void freeAllBuffers();
523     int getSlotFromBufferLocked(android_native_buffer_t* buffer) const;
524 
525     void getDequeueBufferInputLocked(IGraphicBufferProducer::DequeueBufferInput* dequeueInput);
526 
527     void getQueueBufferInputLocked(android_native_buffer_t* buffer, int fenceFd, nsecs_t timestamp,
528             IGraphicBufferProducer::QueueBufferInput* out);
529 
530     // For easing in adoption of gralloc4 metadata by vendor components, as well as for supporting
531     // the public ANativeWindow api, allow setting relevant metadata when queueing a buffer through
532     // a native window
533     void applyGrallocMetadataLocked(
534             android_native_buffer_t* buffer,
535             const IGraphicBufferProducer::QueueBufferInput& queueBufferInput);
536 
537     void onBufferQueuedLocked(int slot, sp<Fence> fence,
538             const IGraphicBufferProducer::QueueBufferOutput& output);
539 
540     struct BufferSlot {
541         sp<GraphicBuffer> buffer;
542         Region dirtyRegion;
543     };
544 
545     // mSurfaceTexture is the interface to the surface texture server. All
546     // operations on the surface texture client ultimately translate into
547     // interactions with the server using this interface.
548     // TODO: rename to mBufferProducer
549     sp<IGraphicBufferProducer> mGraphicBufferProducer;
550 
551 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
552     // mSurfaceDeathListener gets registered as mGraphicBufferProducer's
553     // DeathRecipient when SurfaceListener::needsDeathNotify returns true and
554     // gets notified when it dies.
555     sp<ProducerDeathListenerProxy> mSurfaceDeathListener;
556 #endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS)
557 
558     // mSlots stores the buffers that have been allocated for each buffer slot.
559     // It is initialized to null pointers, and gets filled in with the result of
560     // IGraphicBufferProducer::requestBuffer when the client dequeues a buffer from a
561     // slot that has not yet been used. The buffer allocated to a slot will also
562     // be replaced if the requested buffer usage or geometry differs from that
563     // of the buffer allocated to a slot.
564 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_UNLIMITED_SLOTS)
565     std::vector<BufferSlot> mSlots;
566 #else
567     BufferSlot mSlots[NUM_BUFFER_SLOTS];
568 #endif
569 
570     // mReqWidth is the buffer width that will be requested at the next dequeue
571     // operation. It is initialized to 1.
572     uint32_t mReqWidth;
573 
574     // mReqHeight is the buffer height that will be requested at the next
575     // dequeue operation. It is initialized to 1.
576     uint32_t mReqHeight;
577 
578     // mReqFormat is the buffer pixel format that will be requested at the next
579     // dequeue operation. It is initialized to PIXEL_FORMAT_RGBA_8888.
580     PixelFormat mReqFormat;
581 
582     // mReqUsage is the set of buffer usage flags that will be requested
583     // at the next dequeue operation. It is initialized to 0.
584     uint64_t mReqUsage;
585 
586     // mTimestamp is the timestamp that will be used for the next buffer queue
587     // operation. It defaults to NATIVE_WINDOW_TIMESTAMP_AUTO, which means that
588     // a timestamp is auto-generated when queueBuffer is called.
589     int64_t mTimestamp;
590 
591     // mDataSpace is the buffer dataSpace that will be used for the next buffer
592     // queue operation. It defaults to Dataspace::UNKNOWN, which
593     // means that the buffer contains some type of color data.
594     ui::Dataspace mDataSpace;
595 
596     // mHdrMetadata is the HDR metadata that will be used for the next buffer
597     // queue operation.  There is no HDR metadata by default.
598     HdrMetadata mHdrMetadata;
599 
600     // mHdrMetadataIsSet is a bitfield to track which HDR metadata has been set.
601     // Prevent Surface from resetting HDR metadata that was set on a bufer when
602     // HDR metadata is not set on this Surface.
603     uint32_t mHdrMetadataIsSet{0};
604 
605     // mCrop is the crop rectangle that will be used for the next buffer
606     // that gets queued. It is set by calling setCrop.
607     Rect mCrop;
608 
609     // mScalingMode is the scaling mode that will be used for the next
610     // buffers that get queued. It is set by calling setScalingMode.
611     int mScalingMode;
612 
613     // mTransform is the transform identifier that will be used for the next
614     // buffer that gets queued. It is set by calling setTransform.
615     uint32_t mTransform;
616 
617     // mStickyTransform is a transform that is applied on top of mTransform
618     // in each buffer that is queued.  This is typically used to force the
619     // compositor to apply a transform, and will prevent the transform hint
620     // from being set by the compositor.
621     uint32_t mStickyTransform;
622 
623     // mDefaultWidth is default width of the buffers, regardless of the
624     // native_window_set_buffers_dimensions call.
625     uint32_t mDefaultWidth;
626 
627     // mDefaultHeight is default height of the buffers, regardless of the
628     // native_window_set_buffers_dimensions call.
629     uint32_t mDefaultHeight;
630 
631     // mUserWidth, if non-zero, is an application-specified override
632     // of mDefaultWidth.  This is lower priority than the width set by
633     // native_window_set_buffers_dimensions.
634     uint32_t mUserWidth;
635 
636     // mUserHeight, if non-zero, is an application-specified override
637     // of mDefaultHeight.  This is lower priority than the height set
638     // by native_window_set_buffers_dimensions.
639     uint32_t mUserHeight;
640 
641     // mTransformHint is the transform probably applied to buffers of this
642     // window. this is only a hint, actual transform may differ.
643     uint32_t mTransformHint;
getTransformHint()644     virtual uint32_t getTransformHint() const { return mTransformHint; }
645     bool transformToDisplayInverse() const;
646 
647     // mProducerControlledByApp whether this buffer producer is controlled
648     // by the application
649     bool mProducerControlledByApp;
650 
651     // mSwapIntervalZero set if we should drop buffers at queue() time to
652     // achieve an asynchronous swap interval
653     bool mSwapIntervalZero;
654 
655     // mConsumerRunningBehind whether the consumer is running more than
656     // one buffer behind the producer.
657     mutable bool mConsumerRunningBehind;
658 
659     // mMutex is the mutex used to prevent concurrent access to the member
660     // variables of Surface objects. It must be locked whenever the
661     // member variables are accessed.
662     mutable Mutex mMutex;
663 
664     // mInterceptorMutex is the mutex guarding interceptors.
665     mutable std::shared_mutex mInterceptorMutex;
666 
667     ANativeWindow_cancelBufferInterceptor mCancelInterceptor = nullptr;
668     void* mCancelInterceptorData = nullptr;
669     ANativeWindow_dequeueBufferInterceptor mDequeueInterceptor = nullptr;
670     void* mDequeueInterceptorData = nullptr;
671     ANativeWindow_performInterceptor mPerformInterceptor = nullptr;
672     void* mPerformInterceptorData = nullptr;
673     ANativeWindow_queueBufferInterceptor mQueueInterceptor = nullptr;
674     void* mQueueInterceptorData = nullptr;
675     ANativeWindow_queryInterceptor mQueryInterceptor = nullptr;
676     void* mQueryInterceptorData = nullptr;
677 
678     // must be used from the lock/unlock thread
679     sp<GraphicBuffer>           mLockedBuffer;
680     sp<GraphicBuffer>           mPostedBuffer;
681     bool                        mConnectedToCpu;
682 
683     // When a CPU producer is attached, this reflects the region that the
684     // producer wished to update as well as whether the Surface was able to copy
685     // the previous buffer back to allow a partial update.
686     //
687     // When a non-CPU producer is attached, this reflects the surface damage
688     // (the change since the previous frame) passed in by the producer.
689     Region mDirtyRegion;
690 
691     // mBufferAge tracks the age of the contents of the most recently dequeued
692     // buffer as the number of frames that have elapsed since it was last queued
693     uint64_t mBufferAge;
694 
695     // Stores the current generation number. See setGenerationNumber and
696     // IGraphicBufferProducer::setGenerationNumber for more information.
697     uint32_t mGenerationNumber;
698 
699     // Caches the values that have been passed to the producer.
700     bool mSharedBufferMode;
701     bool mAutoRefresh;
702     bool mAutoPrerotation;
703 
704     // If in shared buffer mode and auto refresh is enabled, store the shared
705     // buffer slot and return it for all calls to queue/dequeue without going
706     // over Binder.
707     int mSharedBufferSlot;
708 
709     // This is true if the shared buffer has already been queued/canceled. It's
710     // used to prevent a mismatch between the number of queue/dequeue calls.
711     bool mSharedBufferHasBeenQueued;
712 
713     // These are used to satisfy the NATIVE_WINDOW_LAST_*_DURATION queries
714     nsecs_t mLastDequeueDuration = 0;
715     nsecs_t mLastQueueDuration = 0;
716 
717     // Stores the time right before we call IGBP::dequeueBuffer
718     nsecs_t mLastDequeueStartTime = 0;
719 
720     Condition mQueueBufferCondition;
721 
722     uint64_t mNextFrameNumber = 1;
723     uint64_t mLastFrameNumber = 0;
724 
725     // Mutable because ANativeWindow::query needs this class const.
726     mutable bool mQueriedSupportedTimestamps;
727     mutable bool mFrameTimestampsSupportsPresent;
728 
729     // A cached copy of the FrameEventHistory maintained by the consumer.
730     bool mEnableFrameTimestamps = false;
731     std::unique_ptr<ProducerFrameEventHistory> mFrameEventHistory;
732 
733     // Reference to the SurfaceFlinger layer that was used to create this
734     // surface. This is only populated when the Surface is created from
735     // a BlastBufferQueue.
736     sp<IBinder> mSurfaceControlHandle;
737 
738     bool mReportRemovedBuffers = false;
739     std::vector<sp<GraphicBuffer>> mRemovedBuffers;
740     int mMaxBufferCount;
741 
742 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_UNLIMITED_SLOTS)
743     bool mIsSlotExpansionAllowed;
744 #endif
745 
746     sp<IProducerListener> mListenerProxy;
747 
748     // Get and flush the buffers of given slots, if the buffer in the slot
749     // is currently dequeued then it won't be flushed and won't be returned
750     // in outBuffers.
751     status_t getAndFlushBuffersFromSlots(const std::vector<int32_t>& slots,
752             std::vector<sp<GraphicBuffer>>* outBuffers);
753 
754     // Buffers that are successfully dequeued/attached and handed to clients
755     std::unordered_set<int> mDequeuedSlots;
756 };
757 
758 } // namespace android
759 
760 #endif  // ANDROID_GUI_SURFACE_H
761