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 // Batch version of dequeueBuffer, cancelBuffer and queueBuffer 446 // Note that these batched operations are not supported when shared buffer mode is being used. 447 struct BatchBuffer { 448 ANativeWindowBuffer* buffer = nullptr; 449 int fenceFd = -1; 450 }; 451 virtual int dequeueBuffers(std::vector<BatchBuffer>* buffers); 452 virtual int cancelBuffers(const std::vector<BatchBuffer>& buffers); 453 454 struct BatchQueuedBuffer { 455 ANativeWindowBuffer* buffer = nullptr; 456 int fenceFd = -1; 457 nsecs_t timestamp = NATIVE_WINDOW_TIMESTAMP_AUTO; 458 }; 459 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS) 460 virtual int queueBuffers(const std::vector<BatchQueuedBuffer>& buffers, 461 std::vector<SurfaceQueueBufferOutput>* queueBufferOutputs = nullptr); 462 #else 463 virtual int queueBuffers( 464 const std::vector<BatchQueuedBuffer>& buffers); 465 #endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS) 466 467 protected: 468 enum { NUM_BUFFER_SLOTS = BufferQueueDefs::NUM_BUFFER_SLOTS }; 469 enum { DEFAULT_FORMAT = PIXEL_FORMAT_RGBA_8888 }; 470 471 class ProducerListenerProxy : public BnProducerListener { 472 public: ProducerListenerProxy(wp<Surface> parent,sp<SurfaceListener> listener)473 ProducerListenerProxy(wp<Surface> parent, sp<SurfaceListener> listener) 474 : mParent(parent), mSurfaceListener(listener) {} ~ProducerListenerProxy()475 virtual ~ProducerListenerProxy() {} 476 onBufferReleased()477 virtual void onBufferReleased() { 478 mSurfaceListener->onBufferReleased(); 479 } 480 needsReleaseNotify()481 virtual bool needsReleaseNotify() { 482 return mSurfaceListener->needsReleaseNotify(); 483 } 484 onBufferDetached(int slot)485 virtual void onBufferDetached(int slot) { mSurfaceListener->onBufferDetached(slot); } 486 487 virtual void onBuffersDiscarded(const std::vector<int32_t>& slots); 488 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_CONSUMER_ATTACH_CALLBACK) onBufferAttached()489 virtual void onBufferAttached() { 490 mSurfaceListener->onBufferAttached(); 491 } 492 needsAttachNotify()493 virtual bool needsAttachNotify() { 494 return mSurfaceListener->needsAttachNotify(); 495 } 496 #endif 497 private: 498 wp<Surface> mParent; 499 sp<SurfaceListener> mSurfaceListener; 500 }; 501 502 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS) 503 class ProducerDeathListenerProxy : public IBinder::DeathRecipient { 504 public: 505 ProducerDeathListenerProxy(wp<SurfaceListener> surfaceListener); 506 ProducerDeathListenerProxy(ProducerDeathListenerProxy&) = delete; 507 508 // IBinder::DeathRecipient 509 virtual void binderDied(const wp<IBinder>&) override; 510 511 private: 512 wp<SurfaceListener> mSurfaceListener; 513 }; 514 friend class ProducerDeathListenerProxy; 515 #endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS) 516 517 void querySupportedTimestampsLocked() const; 518 519 void freeAllBuffers(); 520 int getSlotFromBufferLocked(android_native_buffer_t* buffer) const; 521 522 void getDequeueBufferInputLocked(IGraphicBufferProducer::DequeueBufferInput* dequeueInput); 523 524 void getQueueBufferInputLocked(android_native_buffer_t* buffer, int fenceFd, nsecs_t timestamp, 525 IGraphicBufferProducer::QueueBufferInput* out); 526 527 // For easing in adoption of gralloc4 metadata by vendor components, as well as for supporting 528 // the public ANativeWindow api, allow setting relevant metadata when queueing a buffer through 529 // a native window 530 void applyGrallocMetadataLocked( 531 android_native_buffer_t* buffer, 532 const IGraphicBufferProducer::QueueBufferInput& queueBufferInput); 533 534 void onBufferQueuedLocked(int slot, sp<Fence> fence, 535 const IGraphicBufferProducer::QueueBufferOutput& output); 536 537 struct BufferSlot { 538 sp<GraphicBuffer> buffer; 539 Region dirtyRegion; 540 }; 541 542 // mSurfaceTexture is the interface to the surface texture server. All 543 // operations on the surface texture client ultimately translate into 544 // interactions with the server using this interface. 545 // TODO: rename to mBufferProducer 546 sp<IGraphicBufferProducer> mGraphicBufferProducer; 547 548 #if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS) 549 // mSurfaceDeathListener gets registered as mGraphicBufferProducer's 550 // DeathRecipient when SurfaceListener::needsDeathNotify returns true and 551 // gets notified when it dies. 552 sp<ProducerDeathListenerProxy> mSurfaceDeathListener; 553 #endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_PLATFORM_API_IMPROVEMENTS) 554 555 // mSlots stores the buffers that have been allocated for each buffer slot. 556 // It is initialized to null pointers, and gets filled in with the result of 557 // IGraphicBufferProducer::requestBuffer when the client dequeues a buffer from a 558 // slot that has not yet been used. The buffer allocated to a slot will also 559 // be replaced if the requested buffer usage or geometry differs from that 560 // of the buffer allocated to a slot. 561 BufferSlot mSlots[NUM_BUFFER_SLOTS]; 562 563 // mReqWidth is the buffer width that will be requested at the next dequeue 564 // operation. It is initialized to 1. 565 uint32_t mReqWidth; 566 567 // mReqHeight is the buffer height that will be requested at the next 568 // dequeue operation. It is initialized to 1. 569 uint32_t mReqHeight; 570 571 // mReqFormat is the buffer pixel format that will be requested at the next 572 // dequeue operation. It is initialized to PIXEL_FORMAT_RGBA_8888. 573 PixelFormat mReqFormat; 574 575 // mReqUsage is the set of buffer usage flags that will be requested 576 // at the next dequeue operation. It is initialized to 0. 577 uint64_t mReqUsage; 578 579 // mTimestamp is the timestamp that will be used for the next buffer queue 580 // operation. It defaults to NATIVE_WINDOW_TIMESTAMP_AUTO, which means that 581 // a timestamp is auto-generated when queueBuffer is called. 582 int64_t mTimestamp; 583 584 // mDataSpace is the buffer dataSpace that will be used for the next buffer 585 // queue operation. It defaults to Dataspace::UNKNOWN, which 586 // means that the buffer contains some type of color data. 587 ui::Dataspace mDataSpace; 588 589 // mHdrMetadata is the HDR metadata that will be used for the next buffer 590 // queue operation. There is no HDR metadata by default. 591 HdrMetadata mHdrMetadata; 592 593 // mHdrMetadataIsSet is a bitfield to track which HDR metadata has been set. 594 // Prevent Surface from resetting HDR metadata that was set on a bufer when 595 // HDR metadata is not set on this Surface. 596 uint32_t mHdrMetadataIsSet{0}; 597 598 // mCrop is the crop rectangle that will be used for the next buffer 599 // that gets queued. It is set by calling setCrop. 600 Rect mCrop; 601 602 // mScalingMode is the scaling mode that will be used for the next 603 // buffers that get queued. It is set by calling setScalingMode. 604 int mScalingMode; 605 606 // mTransform is the transform identifier that will be used for the next 607 // buffer that gets queued. It is set by calling setTransform. 608 uint32_t mTransform; 609 610 // mStickyTransform is a transform that is applied on top of mTransform 611 // in each buffer that is queued. This is typically used to force the 612 // compositor to apply a transform, and will prevent the transform hint 613 // from being set by the compositor. 614 uint32_t mStickyTransform; 615 616 // mDefaultWidth is default width of the buffers, regardless of the 617 // native_window_set_buffers_dimensions call. 618 uint32_t mDefaultWidth; 619 620 // mDefaultHeight is default height of the buffers, regardless of the 621 // native_window_set_buffers_dimensions call. 622 uint32_t mDefaultHeight; 623 624 // mUserWidth, if non-zero, is an application-specified override 625 // of mDefaultWidth. This is lower priority than the width set by 626 // native_window_set_buffers_dimensions. 627 uint32_t mUserWidth; 628 629 // mUserHeight, if non-zero, is an application-specified override 630 // of mDefaultHeight. This is lower priority than the height set 631 // by native_window_set_buffers_dimensions. 632 uint32_t mUserHeight; 633 634 // mTransformHint is the transform probably applied to buffers of this 635 // window. this is only a hint, actual transform may differ. 636 uint32_t mTransformHint; getTransformHint()637 virtual uint32_t getTransformHint() const { return mTransformHint; } 638 bool transformToDisplayInverse() const; 639 640 // mProducerControlledByApp whether this buffer producer is controlled 641 // by the application 642 bool mProducerControlledByApp; 643 644 // mSwapIntervalZero set if we should drop buffers at queue() time to 645 // achieve an asynchronous swap interval 646 bool mSwapIntervalZero; 647 648 // mConsumerRunningBehind whether the consumer is running more than 649 // one buffer behind the producer. 650 mutable bool mConsumerRunningBehind; 651 652 // mMutex is the mutex used to prevent concurrent access to the member 653 // variables of Surface objects. It must be locked whenever the 654 // member variables are accessed. 655 mutable Mutex mMutex; 656 657 // mInterceptorMutex is the mutex guarding interceptors. 658 mutable std::shared_mutex mInterceptorMutex; 659 660 ANativeWindow_cancelBufferInterceptor mCancelInterceptor = nullptr; 661 void* mCancelInterceptorData = nullptr; 662 ANativeWindow_dequeueBufferInterceptor mDequeueInterceptor = nullptr; 663 void* mDequeueInterceptorData = nullptr; 664 ANativeWindow_performInterceptor mPerformInterceptor = nullptr; 665 void* mPerformInterceptorData = nullptr; 666 ANativeWindow_queueBufferInterceptor mQueueInterceptor = nullptr; 667 void* mQueueInterceptorData = nullptr; 668 ANativeWindow_queryInterceptor mQueryInterceptor = nullptr; 669 void* mQueryInterceptorData = nullptr; 670 671 // must be used from the lock/unlock thread 672 sp<GraphicBuffer> mLockedBuffer; 673 sp<GraphicBuffer> mPostedBuffer; 674 bool mConnectedToCpu; 675 676 // When a CPU producer is attached, this reflects the region that the 677 // producer wished to update as well as whether the Surface was able to copy 678 // the previous buffer back to allow a partial update. 679 // 680 // When a non-CPU producer is attached, this reflects the surface damage 681 // (the change since the previous frame) passed in by the producer. 682 Region mDirtyRegion; 683 684 // mBufferAge tracks the age of the contents of the most recently dequeued 685 // buffer as the number of frames that have elapsed since it was last queued 686 uint64_t mBufferAge; 687 688 // Stores the current generation number. See setGenerationNumber and 689 // IGraphicBufferProducer::setGenerationNumber for more information. 690 uint32_t mGenerationNumber; 691 692 // Caches the values that have been passed to the producer. 693 bool mSharedBufferMode; 694 bool mAutoRefresh; 695 bool mAutoPrerotation; 696 697 // If in shared buffer mode and auto refresh is enabled, store the shared 698 // buffer slot and return it for all calls to queue/dequeue without going 699 // over Binder. 700 int mSharedBufferSlot; 701 702 // This is true if the shared buffer has already been queued/canceled. It's 703 // used to prevent a mismatch between the number of queue/dequeue calls. 704 bool mSharedBufferHasBeenQueued; 705 706 // These are used to satisfy the NATIVE_WINDOW_LAST_*_DURATION queries 707 nsecs_t mLastDequeueDuration = 0; 708 nsecs_t mLastQueueDuration = 0; 709 710 // Stores the time right before we call IGBP::dequeueBuffer 711 nsecs_t mLastDequeueStartTime = 0; 712 713 Condition mQueueBufferCondition; 714 715 uint64_t mNextFrameNumber = 1; 716 uint64_t mLastFrameNumber = 0; 717 718 // Mutable because ANativeWindow::query needs this class const. 719 mutable bool mQueriedSupportedTimestamps; 720 mutable bool mFrameTimestampsSupportsPresent; 721 722 // A cached copy of the FrameEventHistory maintained by the consumer. 723 bool mEnableFrameTimestamps = false; 724 std::unique_ptr<ProducerFrameEventHistory> mFrameEventHistory; 725 726 // Reference to the SurfaceFlinger layer that was used to create this 727 // surface. This is only populated when the Surface is created from 728 // a BlastBufferQueue. 729 sp<IBinder> mSurfaceControlHandle; 730 731 bool mReportRemovedBuffers = false; 732 std::vector<sp<GraphicBuffer>> mRemovedBuffers; 733 int mMaxBufferCount; 734 735 sp<IProducerListener> mListenerProxy; 736 737 // Get and flush the buffers of given slots, if the buffer in the slot 738 // is currently dequeued then it won't be flushed and won't be returned 739 // in outBuffers. 740 status_t getAndFlushBuffersFromSlots(const std::vector<int32_t>& slots, 741 std::vector<sp<GraphicBuffer>>* outBuffers); 742 743 // Buffers that are successfully dequeued/attached and handed to clients 744 std::unordered_set<int> mDequeuedSlots; 745 }; 746 747 } // namespace android 748 749 #endif // ANDROID_GUI_SURFACE_H 750