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