2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef ANDROID_SURFACE_FLINGER_H
18 #define ANDROID_SURFACE_FLINGER_H
21 #include <sys/types.h>
26 * NOTE: Make sure this file doesn't include anything from <gl/ > or <gl2/ >
29 #include <cutils/compiler.h>
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>
38 #include <binder/IMemory.h>
40 #include <ui/PixelFormat.h>
43 #include <gui/ISurfaceComposer.h>
44 #include <gui/ISurfaceComposerClient.h>
46 #include <hardware/hwcomposer_defs.h>
48 #include <private/gui/LayerState.h>
51 #include "DisplayDevice.h"
53 #include "FenceTracker.h"
54 #include "FrameTracker.h"
55 #include "MessageQueue.h"
57 #include "DisplayHardware/HWComposer.h"
58 #include "Effects/Daltonizer.h"
60 #include "FrameRateHelper.h"
64 // ---------------------------------------------------------------------------
67 class DisplayEventConnection;
69 class IGraphicBufferAlloc;
75 class EventControlThread;
77 // ---------------------------------------------------------------------------
80 eTransactionNeeded = 0x01,
81 eTraversalNeeded = 0x02,
82 eDisplayTransactionNeeded = 0x04,
83 eTransactionMask = 0x07
86 class SurfaceFlinger : public BnSurfaceComposer,
87 private IBinder::DeathRecipient,
88 private HWComposer::EventHandler
91 friend class ExSurfaceFlinger;
93 static char const* getServiceName() ANDROID_API {
94 return "SurfaceFlinger";
97 SurfaceFlinger() ANDROID_API;
99 // must be called before clients can connect
100 void init() ANDROID_API;
102 // starts SurfaceFlinger main loop in the current thread
103 void run() ANDROID_API;
106 EVENT_VSYNC = HWC_EVENT_VSYNC
109 // post an asynchronous message to the main thread
110 status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
112 // post a synchronous message to the main thread
113 status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
115 // force full composition on all displays
116 void repaintEverything();
118 // returns the default Display
119 sp<const DisplayDevice> getDefaultDisplayDevice() const {
120 return getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
123 // utility function to delete a texture on the main thread
124 void deleteTextureAsync(uint32_t texture);
126 // enable/disable h/w composer event
127 // TODO: this should be made accessible only to EventThread
129 void setVsyncEnabled(int disp, int enabled);
131 void eventControl(int disp, int event, int enabled);
134 // called on the main thread by MessageQueue when an internal message
136 // TODO: this should be made accessible only to MessageQueue
137 void onMessageReceived(int32_t what);
139 // for debugging only
140 // TODO: this should be made accessible only to HWComposer
141 const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
143 RenderEngine& getRenderEngine() const {
144 return *mRenderEngine;
149 friend class DisplayEventConnection;
151 friend class LayerDim;
152 friend class MonitoredProducer;
153 friend class LayerBlur;
155 // This value is specified in number of frames. Log frame stats at most
157 enum { LOG_FRAME_STATS_PERIOD = 30*60*60 };
159 static const size_t MAX_LAYERS = 4096;
161 // We're reference counted, never destroy SurfaceFlinger directly
162 virtual ~SurfaceFlinger();
164 /* ------------------------------------------------------------------------
165 * Internal data structures
168 class LayerVector : public SortedVector< sp<Layer> > {
171 LayerVector(const LayerVector& rhs);
172 virtual int do_compare(const void* lhs, const void* rhs) const;
175 struct DisplayDeviceState {
176 DisplayDeviceState();
177 DisplayDeviceState(DisplayDevice::DisplayType type, bool isSecure);
178 bool isValid() const { return type >= 0; }
179 bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
180 bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
181 DisplayDevice::DisplayType type;
182 sp<IGraphicBufferProducer> surface;
187 uint32_t width, height;
193 LayerVector layersSortedByZ;
194 DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
197 /* ------------------------------------------------------------------------
200 virtual status_t onTransact(uint32_t code, const Parcel& data,
201 Parcel* reply, uint32_t flags);
202 virtual status_t dump(int fd, const Vector<String16>& args);
204 /* ------------------------------------------------------------------------
205 * ISurfaceComposer interface
207 virtual sp<ISurfaceComposerClient> createConnection();
208 virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
209 virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
210 virtual void destroyDisplay(const sp<IBinder>& display);
211 virtual sp<IBinder> getBuiltInDisplay(int32_t id);
212 virtual void setTransactionState(const Vector<ComposerState>& state,
213 const Vector<DisplayState>& displays, uint32_t flags);
214 virtual void bootFinished();
215 virtual bool authenticateSurfaceTexture(
216 const sp<IGraphicBufferProducer>& bufferProducer) const;
217 virtual sp<IDisplayEventConnection> createDisplayEventConnection();
218 virtual status_t captureScreen(const sp<IBinder>& display,
219 const sp<IGraphicBufferProducer>& producer,
220 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
221 uint32_t minLayerZ, uint32_t maxLayerZ,
222 bool useIdentityTransform, ISurfaceComposer::Rotation rotation);
223 virtual status_t getDisplayStats(const sp<IBinder>& display,
224 DisplayStatInfo* stats);
225 virtual status_t getDisplayConfigs(const sp<IBinder>& display,
226 Vector<DisplayInfo>* configs);
227 virtual int getActiveConfig(const sp<IBinder>& display);
228 virtual void setPowerMode(const sp<IBinder>& display, int mode);
229 virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
230 virtual status_t clearAnimationFrameStats();
231 virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
232 virtual status_t getHdrCapabilities(const sp<IBinder>& display,
233 HdrCapabilities* outCapabilities) const;
235 /* ------------------------------------------------------------------------
236 * DeathRecipient interface
238 virtual void binderDied(const wp<IBinder>& who);
240 /* ------------------------------------------------------------------------
243 virtual void onFirstRef();
245 /* ------------------------------------------------------------------------
246 * HWComposer::EventHandler interface
248 virtual void onVSyncReceived(int type, nsecs_t timestamp);
249 virtual void onHotplugReceived(int disp, bool connected);
251 /* ------------------------------------------------------------------------
254 virtual void updateExtendedMode() { }
256 virtual void getIndexLOI(size_t /*dpy*/,
257 const LayerVector& /*currentLayers*/,
258 bool& /*bIgnoreLayers*/,
259 int& /*indexLOI*/) { }
261 virtual bool updateLayerVisibleNonTransparentRegion(
262 const int& dpy, const sp<Layer>& layer,
263 bool& bIgnoreLayers, int& indexLOI,
264 uint32_t layerStack, const int& i);
266 virtual void delayDPTransactionIfNeeded(
267 const Vector<DisplayState>& /*displays*/) { }
269 virtual bool canDrawLayerinScreenShot(
270 const sp<const DisplayDevice>& hw,
271 const sp<Layer>& layer);
273 virtual void isfreezeSurfacePresent(
274 bool& freezeSurfacePresent,
275 const sp<const DisplayDevice>& /*hw*/,
276 const int32_t& /*id*/) { freezeSurfacePresent = false; }
278 virtual void setOrientationEventControl(
279 bool& /*freezeSurfacePresent*/,
280 const int32_t& /*id*/) { }
282 virtual void updateVisibleRegionsDirty() { }
283 virtual void drawWormHoleIfRequired(HWComposer::LayerListIterator &cur,
284 const HWComposer::LayerListIterator &end,
285 const sp<const DisplayDevice>& hw,
286 const Region& region);
287 /* ------------------------------------------------------------------------
291 void signalTransaction();
292 void signalLayerUpdate();
293 void signalRefresh();
295 // called on the main thread in response to initializeDisplays()
296 void onInitializeDisplays();
297 // called on the main thread in response to setActiveConfig()
298 void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
299 // called on the main thread in response to setPowerMode()
300 void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
302 // Returns whether the transaction actually modified any state
303 bool handleMessageTransaction();
305 // Returns whether a new buffer has been latched (see handlePageFlip())
306 bool handleMessageInvalidate();
308 void handleMessageRefresh();
310 void handleTransaction(uint32_t transactionFlags);
311 void handleTransactionLocked(uint32_t transactionFlags);
313 void updateCursorAsync();
315 /* handlePageFlip - latch a new buffer if available and compute the dirty
316 * region. Returns whether a new buffer has been latched, i.e., whether it
317 * is necessary to perform a refresh during this vsync.
319 bool handlePageFlip();
321 /* ------------------------------------------------------------------------
324 uint32_t getTransactionFlags(uint32_t flags);
325 uint32_t peekTransactionFlags(uint32_t flags);
326 uint32_t setTransactionFlags(uint32_t flags);
327 void commitTransaction();
328 uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
329 uint32_t setDisplayStateLocked(const DisplayState& s);
331 /* ------------------------------------------------------------------------
334 status_t createLayer(const String8& name, const sp<Client>& client,
335 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
336 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
338 status_t createNormalLayer(const sp<Client>& client, const String8& name,
339 uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
340 sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
341 sp<Layer>* outLayer);
343 status_t createDimLayer(const sp<Client>& client, const String8& name,
344 uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
345 sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
347 status_t createBlurLayer(const sp<Client>& client, const String8& name,
348 uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
349 sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
351 // called in response to the window-manager calling
352 // ISurfaceComposerClient::destroySurface()
353 status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
355 // called when all clients have released all their references to
356 // this layer meaning it is entirely safe to destroy all
357 // resources associated to this layer.
358 status_t onLayerDestroyed(const wp<Layer>& layer);
360 // remove a layer from SurfaceFlinger immediately
361 status_t removeLayer(const sp<Layer>& layer);
363 // add a layer to SurfaceFlinger
364 status_t addClientLayer(const sp<Client>& client,
365 const sp<IBinder>& handle,
366 const sp<IGraphicBufferProducer>& gbc,
367 const sp<Layer>& lbc);
369 /* ------------------------------------------------------------------------
370 * Boot animation, on/off animations and screen capture
373 void startBootAnim();
375 void renderScreenImplLocked(
376 const sp<const DisplayDevice>& hw,
377 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
378 uint32_t minLayerZ, uint32_t maxLayerZ,
379 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
381 status_t captureScreenImplLocked(
382 const sp<const DisplayDevice>& hw,
383 const sp<IGraphicBufferProducer>& producer,
384 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
385 uint32_t minLayerZ, uint32_t maxLayerZ,
386 bool useIdentityTransform, Transform::orientation_flags rotation,
387 bool isLocalScreenshot);
389 /* ------------------------------------------------------------------------
392 size_t getMaxTextureSize() const;
393 size_t getMaxViewportDims() const;
395 /* ------------------------------------------------------------------------
396 * Display and layer stack management
398 // called when starting, or restarting after system_server death
399 void initializeDisplays();
401 // Create an IBinder for a builtin display and add it to current state
402 void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
404 // NOTE: can only be called from the main thread or with mStateLock held
405 sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
406 return mDisplays.valueFor(dpy);
409 // NOTE: can only be called from the main thread or with mStateLock held
410 sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
411 return mDisplays.valueFor(dpy);
414 // mark a region of a layer stack dirty. this updates the dirty
415 // region of all screens presenting this layer stack.
416 void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
419 int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
422 /* ------------------------------------------------------------------------
426 HWComposer& getHwComposer() const { return *mHwc; }
428 /* ------------------------------------------------------------------------
431 void invalidateHwcGeometry();
432 void computeVisibleRegions(size_t dpy,
433 const LayerVector& currentLayers, uint32_t layerStack,
434 Region& dirtyRegion, Region& opaqueRegion);
436 void preComposition();
437 void postComposition(nsecs_t refreshStartTime);
438 void rebuildLayerStacks();
439 void setUpHWComposer();
440 void doComposition();
441 void doDebugFlashRegions();
442 void doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& dirtyRegion);
444 // compose surfaces for display hw. this fails if using GL and the surface
445 // has been destroyed and is no longer valid.
446 bool doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty);
448 void postFramebuffer();
449 void drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const;
451 /* ------------------------------------------------------------------------
455 /* ------------------------------------------------------------------------
458 void enableHardwareVsync();
459 void resyncToHardwareVsync(bool makeAvailable);
460 void disableHardwareVsync(bool makeUnavailable);
462 void resyncWithRateLimit();
465 /* ------------------------------------------------------------------------
466 * Debugging & dumpsys
468 void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
469 void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
470 void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
471 void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
472 bool startDdmConnection();
473 static void appendSfConfigString(String8& result);
474 void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
475 const sp<const DisplayDevice>& hw,
476 uint32_t minLayerZ, uint32_t maxLayerZ);
478 void logFrameStats();
480 void dumpStaticScreenStats(String8& result) const;
481 virtual void dumpDrawCycle(bool /* prePrepare */ ) { }
483 /* ------------------------------------------------------------------------
487 // access must be protected by mStateLock
488 mutable Mutex mStateLock;
490 volatile int32_t mTransactionFlags;
491 Condition mTransactionCV;
492 bool mTransactionPending;
493 bool mAnimTransactionPending;
494 Vector< sp<Layer> > mLayersPendingRemoval;
495 SortedVector< wp<IBinder> > mGraphicBufferProducerList;
497 // protected by mStateLock (but we could use another lock)
500 // access must be protected by mInvalidateLock
501 volatile int32_t mRepaintEverything;
503 // constant members (no synchronization needed for access)
505 RenderEngine* mRenderEngine;
507 bool mGpuToCpuSupported;
508 bool mDropMissedFrames;
509 sp<EventThread> mEventThread;
510 sp<EventThread> mSFEventThread;
511 sp<EventControlThread> mEventControlThread;
512 EGLContext mEGLContext;
513 EGLDisplay mEGLDisplay;
514 sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
516 // Can only accessed from the main thread, these members
517 // don't need synchronization
519 bool mVisibleRegionsDirty;
521 bool mHwWorkListDirty;
523 bool mGeometryInvalid;
525 bool mAnimCompositionPending;
527 std::vector<sp<Layer>> mLayersWithQueuedFrames;
530 // this may only be written from the main thread with mStateLock held
531 // it may be read from other threads with mStateLock held
532 DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
534 // don't use a lock for these, we don't care
537 int mDebugDisableHWC;
538 int mDebugDisableTransformHint;
539 volatile nsecs_t mDebugInSwapBuffers;
540 nsecs_t mLastSwapBufferTime;
541 volatile nsecs_t mDebugInTransaction;
542 nsecs_t mLastTransactionTime;
544 bool mForceFullDamage;
545 FenceTracker mFenceTracker;
547 // these are thread safe
548 mutable MessageQueue mEventQueue;
549 FrameTracker mAnimFrameTracker;
550 DispSync mPrimaryDispSync;
552 // protected by mDestroyedLayerLock;
553 mutable Mutex mDestroyedLayerLock;
554 Vector<Layer const *> mDestroyedLayers;
556 // protected by mHWVsyncLock
558 bool mPrimaryHWVsyncEnabled;
559 bool mHWVsyncAvailable;
561 /* ------------------------------------------------------------------------
562 * Feature prototyping
565 Daltonizer mDaltonizer;
569 bool mHasColorMatrix;
571 mat4 mSecondaryColorMatrix;
572 bool mHasSecondaryColorMatrix;
574 // Static screen stats
576 static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
577 nsecs_t mFrameBuckets[NUM_BUCKETS];
579 std::atomic<nsecs_t> mLastSwapTime;
581 FrameRateHelper mFrameRateHelper;
584 * A number that increases on every new frame composition and screen capture.
585 * LayerBlur can speed up it's drawing by caching texture using this variable
586 * if multiple LayerBlur objects draw in one frame composition.
587 * In case of display mirroring, this variable should be increased on every display.
589 uint32_t mActiveFrameSequence;
593 }; // namespace android
595 #endif // ANDROID_SURFACE_FLINGER_H