SurfaceFlinger.h revision 2047fae0cfed99c425dc7333f31d309e5b8ee1ba
1/* 2 * Copyright (C) 2007 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_SURFACE_FLINGER_H 18#define ANDROID_SURFACE_FLINGER_H 19 20#include <stdint.h> 21#include <sys/types.h> 22 23#include <EGL/egl.h> 24 25/* 26 * NOTE: Make sure this file doesn't include anything from <gl/ > or <gl2/ > 27 */ 28 29#include <cutils/compiler.h> 30 31#include <utils/Atomic.h> 32#include <utils/Errors.h> 33#include <utils/KeyedVector.h> 34#include <utils/RefBase.h> 35#include <utils/SortedVector.h> 36#include <utils/threads.h> 37 38#include <binder/IMemory.h> 39 40#include <ui/FenceTime.h> 41#include <ui/PixelFormat.h> 42#include <ui/mat4.h> 43 44#include <gui/ISurfaceComposer.h> 45#include <gui/ISurfaceComposerClient.h> 46#include <gui/OccupancyTracker.h> 47 48#include <hardware/hwcomposer_defs.h> 49 50#include <system/graphics.h> 51 52#include <private/gui/LayerState.h> 53 54#include "Barrier.h" 55#include "DisplayDevice.h" 56#include "DispSync.h" 57#include "FrameTracker.h" 58#include "LayerVector.h" 59#include "MessageQueue.h" 60#include "SurfaceInterceptor.h" 61 62#include "DisplayHardware/HWComposer.h" 63#include "Effects/Daltonizer.h" 64 65#include <map> 66#include <string> 67 68namespace android { 69 70// --------------------------------------------------------------------------- 71 72class Client; 73class DisplayEventConnection; 74class EventThread; 75class IGraphicBufferAlloc; 76class Layer; 77class LayerDim; 78class Surface; 79class RenderEngine; 80class EventControlThread; 81class VSyncSource; 82class InjectVSyncSource; 83 84// --------------------------------------------------------------------------- 85 86enum { 87 eTransactionNeeded = 0x01, 88 eTraversalNeeded = 0x02, 89 eDisplayTransactionNeeded = 0x04, 90 eTransactionMask = 0x07 91}; 92 93class SurfaceFlinger : public BnSurfaceComposer, 94 private IBinder::DeathRecipient, 95 private HWComposer::EventHandler 96{ 97public: 98 static char const* getServiceName() ANDROID_API { 99 return "SurfaceFlinger"; 100 } 101 102 SurfaceFlinger() ANDROID_API; 103 104 // must be called before clients can connect 105 void init() ANDROID_API; 106 107 // starts SurfaceFlinger main loop in the current thread 108 void run() ANDROID_API; 109 110 enum { 111 EVENT_VSYNC = HWC_EVENT_VSYNC 112 }; 113 114 // post an asynchronous message to the main thread 115 status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0); 116 117 // post a synchronous message to the main thread 118 status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0); 119 120 // force full composition on all displays 121 void repaintEverything(); 122 123 // returns the default Display 124 sp<const DisplayDevice> getDefaultDisplayDevice() const { 125 return getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]); 126 } 127 128 // utility function to delete a texture on the main thread 129 void deleteTextureAsync(uint32_t texture); 130 131 // enable/disable h/w composer event 132 // TODO: this should be made accessible only to EventThread 133#ifdef USE_HWC2 134 void setVsyncEnabled(int disp, int enabled); 135#else 136 void eventControl(int disp, int event, int enabled); 137#endif 138 139 // called on the main thread by MessageQueue when an internal message 140 // is received 141 // TODO: this should be made accessible only to MessageQueue 142 void onMessageReceived(int32_t what); 143 144 // for debugging only 145 // TODO: this should be made accessible only to HWComposer 146 const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id); 147 148 RenderEngine& getRenderEngine() const { 149 return *mRenderEngine; 150 } 151 152private: 153 friend class Client; 154 friend class DisplayEventConnection; 155 friend class EventThread; 156 friend class Layer; 157 friend class MonitoredProducer; 158 159 // This value is specified in number of frames. Log frame stats at most 160 // every half hour. 161 enum { LOG_FRAME_STATS_PERIOD = 30*60*60 }; 162 163 static const size_t MAX_LAYERS = 4096; 164 165 // We're reference counted, never destroy SurfaceFlinger directly 166 virtual ~SurfaceFlinger(); 167 168 /* ------------------------------------------------------------------------ 169 * Internal data structures 170 */ 171 172 class State { 173 public: 174 LayerVector layersSortedByZ; 175 DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays; 176 177 void traverseInZOrder(const std::function<void(Layer*)>& consume) const; 178 void traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const; 179 }; 180 181 /* ------------------------------------------------------------------------ 182 * IBinder interface 183 */ 184 virtual status_t onTransact(uint32_t code, const Parcel& data, 185 Parcel* reply, uint32_t flags); 186 virtual status_t dump(int fd, const Vector<String16>& args); 187 188 /* ------------------------------------------------------------------------ 189 * ISurfaceComposer interface 190 */ 191 virtual sp<ISurfaceComposerClient> createConnection(); 192 virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc(); 193 virtual sp<IBinder> createDisplay(const String8& displayName, bool secure); 194 virtual void destroyDisplay(const sp<IBinder>& display); 195 virtual sp<IBinder> getBuiltInDisplay(int32_t id); 196 virtual void setTransactionState(const Vector<ComposerState>& state, 197 const Vector<DisplayState>& displays, uint32_t flags); 198 virtual void bootFinished(); 199 virtual bool authenticateSurfaceTexture( 200 const sp<IGraphicBufferProducer>& bufferProducer) const; 201 virtual status_t getSupportedFrameTimestamps( 202 std::vector<FrameEvent>* outSupported) const; 203 virtual sp<IDisplayEventConnection> createDisplayEventConnection(); 204 virtual status_t captureScreen(const sp<IBinder>& display, 205 const sp<IGraphicBufferProducer>& producer, 206 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, 207 int32_t minLayerZ, int32_t maxLayerZ, 208 bool useIdentityTransform, ISurfaceComposer::Rotation rotation); 209 virtual status_t getDisplayStats(const sp<IBinder>& display, 210 DisplayStatInfo* stats); 211 virtual status_t getDisplayConfigs(const sp<IBinder>& display, 212 Vector<DisplayInfo>* configs); 213 virtual int getActiveConfig(const sp<IBinder>& display); 214 virtual status_t getDisplayColorModes(const sp<IBinder>& display, 215 Vector<android_color_mode_t>* configs); 216 virtual android_color_mode_t getActiveColorMode(const sp<IBinder>& display); 217 virtual status_t setActiveColorMode(const sp<IBinder>& display, android_color_mode_t colorMode); 218 virtual void setPowerMode(const sp<IBinder>& display, int mode); 219 virtual status_t setActiveConfig(const sp<IBinder>& display, int id); 220 virtual status_t clearAnimationFrameStats(); 221 virtual status_t getAnimationFrameStats(FrameStats* outStats) const; 222 virtual status_t getHdrCapabilities(const sp<IBinder>& display, 223 HdrCapabilities* outCapabilities) const; 224 virtual status_t enableVSyncInjections(bool enable); 225 virtual status_t injectVSync(nsecs_t when); 226 227 228 /* ------------------------------------------------------------------------ 229 * DeathRecipient interface 230 */ 231 virtual void binderDied(const wp<IBinder>& who); 232 233 /* ------------------------------------------------------------------------ 234 * RefBase interface 235 */ 236 virtual void onFirstRef(); 237 238 /* ------------------------------------------------------------------------ 239 * HWComposer::EventHandler interface 240 */ 241 virtual void onVSyncReceived(int type, nsecs_t timestamp); 242 virtual void onHotplugReceived(int disp, bool connected); 243 244 /* ------------------------------------------------------------------------ 245 * Message handling 246 */ 247 void waitForEvent(); 248 void signalTransaction(); 249 void signalLayerUpdate(); 250 void signalRefresh(); 251 252 // called on the main thread in response to initializeDisplays() 253 void onInitializeDisplays(); 254 // called on the main thread in response to setActiveConfig() 255 void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode); 256 // called on the main thread in response to setPowerMode() 257 void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode); 258 259 // Called on the main thread in response to setActiveColorMode() 260 void setActiveColorModeInternal(const sp<DisplayDevice>& hw, android_color_mode_t colorMode); 261 262 // Returns whether the transaction actually modified any state 263 bool handleMessageTransaction(); 264 265 // Returns whether a new buffer has been latched (see handlePageFlip()) 266 bool handleMessageInvalidate(); 267 268 void handleMessageRefresh(); 269 270 void handleTransaction(uint32_t transactionFlags); 271 void handleTransactionLocked(uint32_t transactionFlags); 272 273 void updateCursorAsync(); 274 275 /* handlePageFlip - latch a new buffer if available and compute the dirty 276 * region. Returns whether a new buffer has been latched, i.e., whether it 277 * is necessary to perform a refresh during this vsync. 278 */ 279 bool handlePageFlip(); 280 281 /* ------------------------------------------------------------------------ 282 * Transactions 283 */ 284 uint32_t getTransactionFlags(uint32_t flags); 285 uint32_t peekTransactionFlags(); 286 uint32_t setTransactionFlags(uint32_t flags); 287 void commitTransaction(); 288 uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s); 289 uint32_t setDisplayStateLocked(const DisplayState& s); 290 291 /* ------------------------------------------------------------------------ 292 * Layer management 293 */ 294 status_t createLayer(const String8& name, const sp<Client>& client, 295 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags, 296 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp); 297 298 status_t createNormalLayer(const sp<Client>& client, const String8& name, 299 uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format, 300 sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp, 301 sp<Layer>* outLayer); 302 303 status_t createDimLayer(const sp<Client>& client, const String8& name, 304 uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle, 305 sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer); 306 307 // called in response to the window-manager calling 308 // ISurfaceComposerClient::destroySurface() 309 status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle); 310 311 // called when all clients have released all their references to 312 // this layer meaning it is entirely safe to destroy all 313 // resources associated to this layer. 314 status_t onLayerDestroyed(const wp<Layer>& layer); 315 316 // remove a layer from SurfaceFlinger immediately 317 status_t removeLayer(const wp<Layer>& layer); 318 319 // add a layer to SurfaceFlinger 320 status_t addClientLayer(const sp<Client>& client, 321 const sp<IBinder>& handle, 322 const sp<IGraphicBufferProducer>& gbc, 323 const sp<Layer>& lbc); 324 325 /* ------------------------------------------------------------------------ 326 * Boot animation, on/off animations and screen capture 327 */ 328 329 void startBootAnim(); 330 331 void renderScreenImplLocked( 332 const sp<const DisplayDevice>& hw, 333 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, 334 int32_t minLayerZ, int32_t maxLayerZ, 335 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation); 336 337 status_t captureScreenImplLocked( 338 const sp<const DisplayDevice>& hw, 339 const sp<IGraphicBufferProducer>& producer, 340 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, 341 int32_t minLayerZ, int32_t maxLayerZ, 342 bool useIdentityTransform, Transform::orientation_flags rotation, 343 bool isLocalScreenshot); 344 345 /* ------------------------------------------------------------------------ 346 * EGL 347 */ 348 size_t getMaxTextureSize() const; 349 size_t getMaxViewportDims() const; 350 351 /* ------------------------------------------------------------------------ 352 * Display and layer stack management 353 */ 354 // called when starting, or restarting after system_server death 355 void initializeDisplays(); 356 357 // Create an IBinder for a builtin display and add it to current state 358 void createBuiltinDisplayLocked(DisplayDevice::DisplayType type); 359 360 // NOTE: can only be called from the main thread or with mStateLock held 361 sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const { 362 return mDisplays.valueFor(dpy); 363 } 364 365 // NOTE: can only be called from the main thread or with mStateLock held 366 sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) { 367 return mDisplays.valueFor(dpy); 368 } 369 370 int32_t getDisplayType(const sp<IBinder>& display) { 371 if (!display.get()) return NAME_NOT_FOUND; 372 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) { 373 if (display == mBuiltinDisplays[i]) { 374 return i; 375 } 376 } 377 return NAME_NOT_FOUND; 378 } 379 380 // mark a region of a layer stack dirty. this updates the dirty 381 // region of all screens presenting this layer stack. 382 void invalidateLayerStack(uint32_t layerStack, const Region& dirty); 383 384#ifndef USE_HWC2 385 int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type); 386#endif 387 388 /* ------------------------------------------------------------------------ 389 * H/W composer 390 */ 391 392 HWComposer& getHwComposer() const { return *mHwc; } 393 394 /* ------------------------------------------------------------------------ 395 * Compositing 396 */ 397 void invalidateHwcGeometry(); 398 void computeVisibleRegions(uint32_t layerStack, 399 Region& dirtyRegion, Region& opaqueRegion); 400 401 void preComposition(nsecs_t refreshStartTime); 402 void postComposition(); 403 void rebuildLayerStacks(); 404 void setUpHWComposer(); 405 void doComposition(); 406 void doDebugFlashRegions(); 407 void doDisplayComposition(const sp<const DisplayDevice>& displayDevice, const Region& dirtyRegion); 408 409 // compose surfaces for display hw. this fails if using GL and the surface 410 // has been destroyed and is no longer valid. 411 bool doComposeSurfaces(const sp<const DisplayDevice>& displayDevice, const Region& dirty); 412 413 void postFramebuffer(); 414 void drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const; 415 416 /* ------------------------------------------------------------------------ 417 * Display management 418 */ 419 420 /* ------------------------------------------------------------------------ 421 * VSync 422 */ 423 void enableHardwareVsync(); 424 void resyncToHardwareVsync(bool makeAvailable); 425 void disableHardwareVsync(bool makeUnavailable); 426public: 427 void resyncWithRateLimit(); 428private: 429 430 /* ------------------------------------------------------------------------ 431 * Debugging & dumpsys 432 */ 433 void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const; 434 void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const; 435 void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result); 436 void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const; 437 bool startDdmConnection(); 438 void appendSfConfigString(String8& result) const; 439 void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr, 440 const sp<const DisplayDevice>& hw, 441 int32_t minLayerZ, int32_t maxLayerZ); 442 443 void logFrameStats(); 444 445 void dumpStaticScreenStats(String8& result) const; 446 // Not const because each Layer needs to query Fences and cache timestamps. 447 void dumpFrameEventsLocked(String8& result); 448 449 void recordBufferingStats(const char* layerName, 450 std::vector<OccupancyTracker::Segment>&& history); 451 void dumpBufferingStats(String8& result) const; 452 453 bool isLayerTripleBufferingDisabled() const { 454 return this->mLayerTripleBufferingDisabled; 455 } 456 /* ------------------------------------------------------------------------ 457 * Attributes 458 */ 459 460 // access must be protected by mStateLock 461 mutable Mutex mStateLock; 462 State mCurrentState; 463 volatile int32_t mTransactionFlags; 464 Condition mTransactionCV; 465 bool mTransactionPending; 466 bool mAnimTransactionPending; 467 Vector< sp<Layer> > mLayersPendingRemoval; 468 SortedVector< wp<IBinder> > mGraphicBufferProducerList; 469 470 // protected by mStateLock (but we could use another lock) 471 bool mLayersRemoved; 472 473 // access must be protected by mInvalidateLock 474 volatile int32_t mRepaintEverything; 475 476 // constant members (no synchronization needed for access) 477 HWComposer* mHwc; 478 RenderEngine* mRenderEngine; 479 nsecs_t mBootTime; 480 bool mGpuToCpuSupported; 481 sp<EventThread> mEventThread; 482 sp<EventThread> mSFEventThread; 483 sp<EventThread> mInjectorEventThread; 484 sp<InjectVSyncSource> mVSyncInjector; 485 sp<EventControlThread> mEventControlThread; 486 EGLContext mEGLContext; 487 EGLDisplay mEGLDisplay; 488 sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES]; 489 490 // Can only accessed from the main thread, these members 491 // don't need synchronization 492 State mDrawingState; 493 bool mVisibleRegionsDirty; 494#ifndef USE_HWC2 495 bool mHwWorkListDirty; 496#else 497 bool mGeometryInvalid; 498#endif 499 bool mAnimCompositionPending; 500#ifdef USE_HWC2 501 std::vector<sp<Layer>> mLayersWithQueuedFrames; 502 sp<Fence> mPreviousPresentFence = Fence::NO_FENCE; 503 bool mHadClientComposition = false; 504#endif 505 FenceTimeline mGlCompositionDoneTimeline; 506 FenceTimeline mDisplayTimeline; 507 508 // this may only be written from the main thread with mStateLock held 509 // it may be read from other threads with mStateLock held 510 DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays; 511 512 // don't use a lock for these, we don't care 513 int mDebugRegion; 514 int mDebugDDMS; 515 int mDebugDisableHWC; 516 int mDebugDisableTransformHint; 517 volatile nsecs_t mDebugInSwapBuffers; 518 nsecs_t mLastSwapBufferTime; 519 volatile nsecs_t mDebugInTransaction; 520 nsecs_t mLastTransactionTime; 521 bool mBootFinished; 522 bool mForceFullDamage; 523#ifdef USE_HWC2 524 bool mPropagateBackpressure = true; 525#endif 526 SurfaceInterceptor mInterceptor; 527 bool mUseHwcVirtualDisplays = true; 528 529 // Restrict layers to use two buffers in their bufferqueues. 530 bool mLayerTripleBufferingDisabled = false; 531 532 // these are thread safe 533 mutable MessageQueue mEventQueue; 534 FrameTracker mAnimFrameTracker; 535 DispSync mPrimaryDispSync; 536 537 // protected by mDestroyedLayerLock; 538 mutable Mutex mDestroyedLayerLock; 539 Vector<Layer const *> mDestroyedLayers; 540 541 // protected by mHWVsyncLock 542 Mutex mHWVsyncLock; 543 bool mPrimaryHWVsyncEnabled; 544 bool mHWVsyncAvailable; 545 546 /* ------------------------------------------------------------------------ 547 * Feature prototyping 548 */ 549 550 bool mInjectVSyncs; 551 552 Daltonizer mDaltonizer; 553#ifndef USE_HWC2 554 bool mDaltonize; 555#endif 556 557 mat4 mPreviousColorMatrix; 558 mat4 mColorMatrix; 559 bool mHasColorMatrix; 560 561 // Static screen stats 562 bool mHasPoweredOff; 563 static const size_t NUM_BUCKETS = 8; // < 1-7, 7+ 564 nsecs_t mFrameBuckets[NUM_BUCKETS]; 565 nsecs_t mTotalTime; 566 std::atomic<nsecs_t> mLastSwapTime; 567 568 // Double- vs. triple-buffering stats 569 struct BufferingStats { 570 BufferingStats() 571 : numSegments(0), 572 totalTime(0), 573 twoBufferTime(0), 574 doubleBufferedTime(0), 575 tripleBufferedTime(0) {} 576 577 size_t numSegments; 578 nsecs_t totalTime; 579 580 // "Two buffer" means that a third buffer was never used, whereas 581 // "double-buffered" means that on average the segment only used two 582 // buffers (though it may have used a third for some part of the 583 // segment) 584 nsecs_t twoBufferTime; 585 nsecs_t doubleBufferedTime; 586 nsecs_t tripleBufferedTime; 587 }; 588 mutable Mutex mBufferingStatsMutex; 589 std::unordered_map<std::string, BufferingStats> mBufferingStats; 590 591 // Verify that transaction is being called by an approved process: 592 // either AID_GRAPHICS or AID_SYSTEM. 593 status_t CheckTransactCodeCredentials(uint32_t code); 594 }; 595 596}; // namespace android 597 598#endif // ANDROID_SURFACE_FLINGER_H 599