SurfaceFlinger.h revision 479c60c85c40fd3536b0c88036e838dc1a4c56a0
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<ISurfaceComposerClient> createScopedConnection(const sp<IGraphicBufferProducer>& gbp); 193 virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc(); 194 virtual sp<IBinder> createDisplay(const String8& displayName, bool secure); 195 virtual void destroyDisplay(const sp<IBinder>& display); 196 virtual sp<IBinder> getBuiltInDisplay(int32_t id); 197 virtual void setTransactionState(const Vector<ComposerState>& state, 198 const Vector<DisplayState>& displays, uint32_t flags); 199 virtual void bootFinished(); 200 virtual bool authenticateSurfaceTexture( 201 const sp<IGraphicBufferProducer>& bufferProducer) const; 202 virtual status_t getSupportedFrameTimestamps( 203 std::vector<FrameEvent>* outSupported) const; 204 virtual sp<IDisplayEventConnection> createDisplayEventConnection(); 205 virtual status_t captureScreen(const sp<IBinder>& display, 206 const sp<IGraphicBufferProducer>& producer, 207 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, 208 int32_t minLayerZ, int32_t maxLayerZ, 209 bool useIdentityTransform, ISurfaceComposer::Rotation rotation); 210 virtual status_t getDisplayStats(const sp<IBinder>& display, 211 DisplayStatInfo* stats); 212 virtual status_t getDisplayConfigs(const sp<IBinder>& display, 213 Vector<DisplayInfo>* configs); 214 virtual int getActiveConfig(const sp<IBinder>& display); 215 virtual status_t getDisplayColorModes(const sp<IBinder>& display, 216 Vector<android_color_mode_t>* configs); 217 virtual android_color_mode_t getActiveColorMode(const sp<IBinder>& display); 218 virtual status_t setActiveColorMode(const sp<IBinder>& display, android_color_mode_t colorMode); 219 virtual void setPowerMode(const sp<IBinder>& display, int mode); 220 virtual status_t setActiveConfig(const sp<IBinder>& display, int id); 221 virtual status_t clearAnimationFrameStats(); 222 virtual status_t getAnimationFrameStats(FrameStats* outStats) const; 223 virtual status_t getHdrCapabilities(const sp<IBinder>& display, 224 HdrCapabilities* outCapabilities) const; 225 virtual status_t enableVSyncInjections(bool enable); 226 virtual status_t injectVSync(nsecs_t when); 227 228 229 /* ------------------------------------------------------------------------ 230 * DeathRecipient interface 231 */ 232 virtual void binderDied(const wp<IBinder>& who); 233 234 /* ------------------------------------------------------------------------ 235 * RefBase interface 236 */ 237 virtual void onFirstRef(); 238 239 /* ------------------------------------------------------------------------ 240 * HWComposer::EventHandler interface 241 */ 242 virtual void onVSyncReceived(int type, nsecs_t timestamp); 243 virtual void onHotplugReceived(int disp, bool connected); 244 245 /* ------------------------------------------------------------------------ 246 * Message handling 247 */ 248 void waitForEvent(); 249 void signalTransaction(); 250 void signalLayerUpdate(); 251 void signalRefresh(); 252 253 // called on the main thread in response to initializeDisplays() 254 void onInitializeDisplays(); 255 // called on the main thread in response to setActiveConfig() 256 void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode); 257 // called on the main thread in response to setPowerMode() 258 void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode); 259 260 // Called on the main thread in response to setActiveColorMode() 261 void setActiveColorModeInternal(const sp<DisplayDevice>& hw, android_color_mode_t colorMode); 262 263 // Returns whether the transaction actually modified any state 264 bool handleMessageTransaction(); 265 266 // Returns whether a new buffer has been latched (see handlePageFlip()) 267 bool handleMessageInvalidate(); 268 269 void handleMessageRefresh(); 270 271 void handleTransaction(uint32_t transactionFlags); 272 void handleTransactionLocked(uint32_t transactionFlags); 273 274 void updateCursorAsync(); 275 276 /* handlePageFlip - latch a new buffer if available and compute the dirty 277 * region. Returns whether a new buffer has been latched, i.e., whether it 278 * is necessary to perform a refresh during this vsync. 279 */ 280 bool handlePageFlip(); 281 282 /* ------------------------------------------------------------------------ 283 * Transactions 284 */ 285 uint32_t getTransactionFlags(uint32_t flags); 286 uint32_t peekTransactionFlags(); 287 uint32_t setTransactionFlags(uint32_t flags); 288 void commitTransaction(); 289 uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s); 290 uint32_t setDisplayStateLocked(const DisplayState& s); 291 292 /* ------------------------------------------------------------------------ 293 * Layer management 294 */ 295 status_t createLayer(const String8& name, const sp<Client>& client, 296 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags, 297 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle, 298 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent); 299 300 status_t createNormalLayer(const sp<Client>& client, const String8& name, 301 uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format, 302 sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp, 303 sp<Layer>* outLayer); 304 305 status_t createDimLayer(const sp<Client>& client, const String8& name, 306 uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle, 307 sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer); 308 309 // called in response to the window-manager calling 310 // ISurfaceComposerClient::destroySurface() 311 status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle); 312 313 // called when all clients have released all their references to 314 // this layer meaning it is entirely safe to destroy all 315 // resources associated to this layer. 316 status_t onLayerDestroyed(const wp<Layer>& layer); 317 318 // remove a layer from SurfaceFlinger immediately 319 status_t removeLayer(const wp<Layer>& layer); 320 321 // add a layer to SurfaceFlinger 322 status_t addClientLayer(const sp<Client>& client, 323 const sp<IBinder>& handle, 324 const sp<IGraphicBufferProducer>& gbc, 325 const sp<Layer>& lbc, 326 const sp<Layer>& parent); 327 328 /* ------------------------------------------------------------------------ 329 * Boot animation, on/off animations and screen capture 330 */ 331 332 void startBootAnim(); 333 334 void renderScreenImplLocked( 335 const sp<const DisplayDevice>& hw, 336 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, 337 int32_t minLayerZ, int32_t maxLayerZ, 338 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation); 339 340 status_t captureScreenImplLocked( 341 const sp<const DisplayDevice>& hw, 342 const sp<IGraphicBufferProducer>& producer, 343 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, 344 int32_t minLayerZ, int32_t maxLayerZ, 345 bool useIdentityTransform, Transform::orientation_flags rotation, 346 bool isLocalScreenshot); 347 348 /* ------------------------------------------------------------------------ 349 * EGL 350 */ 351 size_t getMaxTextureSize() const; 352 size_t getMaxViewportDims() const; 353 354 /* ------------------------------------------------------------------------ 355 * Display and layer stack management 356 */ 357 // called when starting, or restarting after system_server death 358 void initializeDisplays(); 359 360 // Create an IBinder for a builtin display and add it to current state 361 void createBuiltinDisplayLocked(DisplayDevice::DisplayType type); 362 363 // NOTE: can only be called from the main thread or with mStateLock held 364 sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const { 365 return mDisplays.valueFor(dpy); 366 } 367 368 // NOTE: can only be called from the main thread or with mStateLock held 369 sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) { 370 return mDisplays.valueFor(dpy); 371 } 372 373 int32_t getDisplayType(const sp<IBinder>& display) { 374 if (!display.get()) return NAME_NOT_FOUND; 375 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) { 376 if (display == mBuiltinDisplays[i]) { 377 return i; 378 } 379 } 380 return NAME_NOT_FOUND; 381 } 382 383 // mark a region of a layer stack dirty. this updates the dirty 384 // region of all screens presenting this layer stack. 385 void invalidateLayerStack(uint32_t layerStack, const Region& dirty); 386 387#ifndef USE_HWC2 388 int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type); 389#endif 390 391 /* ------------------------------------------------------------------------ 392 * H/W composer 393 */ 394 395 HWComposer& getHwComposer() const { return *mHwc; } 396 397 /* ------------------------------------------------------------------------ 398 * Compositing 399 */ 400 void invalidateHwcGeometry(); 401 void computeVisibleRegions(uint32_t layerStack, 402 Region& dirtyRegion, Region& opaqueRegion); 403 404 void preComposition(nsecs_t refreshStartTime); 405 void postComposition(); 406 void rebuildLayerStacks(); 407 void setUpHWComposer(); 408 void doComposition(); 409 void doDebugFlashRegions(); 410 void doDisplayComposition(const sp<const DisplayDevice>& displayDevice, const Region& dirtyRegion); 411 412 // compose surfaces for display hw. this fails if using GL and the surface 413 // has been destroyed and is no longer valid. 414 bool doComposeSurfaces(const sp<const DisplayDevice>& displayDevice, const Region& dirty); 415 416 void postFramebuffer(); 417 void drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const; 418 419 /* ------------------------------------------------------------------------ 420 * Display management 421 */ 422 423 /* ------------------------------------------------------------------------ 424 * VSync 425 */ 426 void enableHardwareVsync(); 427 void resyncToHardwareVsync(bool makeAvailable); 428 void disableHardwareVsync(bool makeUnavailable); 429 430public: 431 void resyncWithRateLimit(); 432private: 433 434 /* ------------------------------------------------------------------------ 435 * Debugging & dumpsys 436 */ 437 void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const; 438 void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const; 439 void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result); 440 void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const; 441 bool startDdmConnection(); 442 void appendSfConfigString(String8& result) const; 443 void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr, 444 const sp<const DisplayDevice>& hw, 445 int32_t minLayerZ, int32_t maxLayerZ); 446 447 void logFrameStats(); 448 449 void dumpStaticScreenStats(String8& result) const; 450 // Not const because each Layer needs to query Fences and cache timestamps. 451 void dumpFrameEventsLocked(String8& result); 452 453 void recordBufferingStats(const char* layerName, 454 std::vector<OccupancyTracker::Segment>&& history); 455 void dumpBufferingStats(String8& result) const; 456 457 bool isLayerTripleBufferingDisabled() const { 458 return this->mLayerTripleBufferingDisabled; 459 } 460 /* ------------------------------------------------------------------------ 461 * Attributes 462 */ 463 464 // access must be protected by mStateLock 465 mutable Mutex mStateLock; 466 State mCurrentState; 467 volatile int32_t mTransactionFlags; 468 Condition mTransactionCV; 469 bool mTransactionPending; 470 bool mAnimTransactionPending; 471 SortedVector< sp<Layer> > mLayersPendingRemoval; 472 SortedVector< wp<IBinder> > mGraphicBufferProducerList; 473 474 // protected by mStateLock (but we could use another lock) 475 bool mLayersRemoved; 476 bool mLayersAdded; 477 478 // access must be protected by mInvalidateLock 479 volatile int32_t mRepaintEverything; 480 481 // constant members (no synchronization needed for access) 482 HWComposer* mHwc; 483 RenderEngine* mRenderEngine; 484 nsecs_t mBootTime; 485 bool mGpuToCpuSupported; 486 sp<EventThread> mEventThread; 487 sp<EventThread> mSFEventThread; 488 sp<EventThread> mInjectorEventThread; 489 sp<InjectVSyncSource> mVSyncInjector; 490 sp<EventControlThread> mEventControlThread; 491 EGLContext mEGLContext; 492 EGLDisplay mEGLDisplay; 493 sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES]; 494 495 // Can only accessed from the main thread, these members 496 // don't need synchronization 497 State mDrawingState; 498 bool mVisibleRegionsDirty; 499#ifndef USE_HWC2 500 bool mHwWorkListDirty; 501#else 502 bool mGeometryInvalid; 503#endif 504 bool mAnimCompositionPending; 505#ifdef USE_HWC2 506 std::vector<sp<Layer>> mLayersWithQueuedFrames; 507 sp<Fence> mPreviousPresentFence = Fence::NO_FENCE; 508 bool mHadClientComposition = false; 509#endif 510 FenceTimeline mGlCompositionDoneTimeline; 511 FenceTimeline mDisplayTimeline; 512 513 // this may only be written from the main thread with mStateLock held 514 // it may be read from other threads with mStateLock held 515 DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays; 516 517 // don't use a lock for these, we don't care 518 int mDebugRegion; 519 int mDebugDDMS; 520 int mDebugDisableHWC; 521 int mDebugDisableTransformHint; 522 volatile nsecs_t mDebugInSwapBuffers; 523 nsecs_t mLastSwapBufferTime; 524 volatile nsecs_t mDebugInTransaction; 525 nsecs_t mLastTransactionTime; 526 bool mBootFinished; 527 bool mForceFullDamage; 528#ifdef USE_HWC2 529 bool mPropagateBackpressure = true; 530#endif 531 SurfaceInterceptor mInterceptor; 532 bool mUseHwcVirtualDisplays = true; 533 534 // Restrict layers to use two buffers in their bufferqueues. 535 bool mLayerTripleBufferingDisabled = false; 536 537 // these are thread safe 538 mutable MessageQueue mEventQueue; 539 FrameTracker mAnimFrameTracker; 540 DispSync mPrimaryDispSync; 541 542 // protected by mDestroyedLayerLock; 543 mutable Mutex mDestroyedLayerLock; 544 Vector<Layer const *> mDestroyedLayers; 545 546 // protected by mHWVsyncLock 547 Mutex mHWVsyncLock; 548 bool mPrimaryHWVsyncEnabled; 549 bool mHWVsyncAvailable; 550 551 /* ------------------------------------------------------------------------ 552 * Feature prototyping 553 */ 554 555 bool mInjectVSyncs; 556 557 Daltonizer mDaltonizer; 558#ifndef USE_HWC2 559 bool mDaltonize; 560#endif 561 562 mat4 mPreviousColorMatrix; 563 mat4 mColorMatrix; 564 bool mHasColorMatrix; 565 566 // Static screen stats 567 bool mHasPoweredOff; 568 static const size_t NUM_BUCKETS = 8; // < 1-7, 7+ 569 nsecs_t mFrameBuckets[NUM_BUCKETS]; 570 nsecs_t mTotalTime; 571 std::atomic<nsecs_t> mLastSwapTime; 572 573 size_t mNumLayers; 574 575 // Double- vs. triple-buffering stats 576 struct BufferingStats { 577 BufferingStats() 578 : numSegments(0), 579 totalTime(0), 580 twoBufferTime(0), 581 doubleBufferedTime(0), 582 tripleBufferedTime(0) {} 583 584 size_t numSegments; 585 nsecs_t totalTime; 586 587 // "Two buffer" means that a third buffer was never used, whereas 588 // "double-buffered" means that on average the segment only used two 589 // buffers (though it may have used a third for some part of the 590 // segment) 591 nsecs_t twoBufferTime; 592 nsecs_t doubleBufferedTime; 593 nsecs_t tripleBufferedTime; 594 }; 595 mutable Mutex mBufferingStatsMutex; 596 std::unordered_map<std::string, BufferingStats> mBufferingStats; 597 598 // Verify that transaction is being called by an approved process: 599 // either AID_GRAPHICS or AID_SYSTEM. 600 status_t CheckTransactCodeCredentials(uint32_t code); 601 }; 602 603}; // namespace android 604 605#endif // ANDROID_SURFACE_FLINGER_H 606