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