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
92 friend class ExSurfaceFlinger;
95 static char const* getServiceName() ANDROID_API {
96 return "SurfaceFlinger";
99 SurfaceFlinger() ANDROID_API;
101 // must be called before clients can connect
102 void init() ANDROID_API;
104 // starts SurfaceFlinger main loop in the current thread
105 void run() ANDROID_API;
108 EVENT_VSYNC = HWC_EVENT_VSYNC
111 // post an asynchronous message to the main thread
112 status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
114 // post a synchronous message to the main thread
115 status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
117 // force full composition on all displays
118 void repaintEverything();
120 // returns the default Display
121 sp<const DisplayDevice> getDefaultDisplayDevice() const {
122 return getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
125 // utility function to delete a texture on the main thread
126 void deleteTextureAsync(uint32_t texture);
128 // enable/disable h/w composer event
129 // TODO: this should be made accessible only to EventThread
131 void setVsyncEnabled(int disp, int enabled);
133 void eventControl(int disp, int event, int enabled);
136 // called on the main thread by MessageQueue when an internal message
138 // TODO: this should be made accessible only to MessageQueue
139 void onMessageReceived(int32_t what);
141 // for debugging only
142 // TODO: this should be made accessible only to HWComposer
143 const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
145 RenderEngine& getRenderEngine() const {
146 return *mRenderEngine;
151 friend class DisplayEventConnection;
153 friend class LayerDim;
154 friend class MonitoredProducer;
155 friend class LayerBlur;
157 // This value is specified in number of frames. Log frame stats at most
159 enum { LOG_FRAME_STATS_PERIOD = 30*60*60 };
161 static const size_t MAX_LAYERS = 4096;
163 // We're reference counted, never destroy SurfaceFlinger directly
164 virtual ~SurfaceFlinger();
166 /* ------------------------------------------------------------------------
167 * Internal data structures
170 class LayerVector : public SortedVector< sp<Layer> > {
173 LayerVector(const LayerVector& rhs);
174 virtual int do_compare(const void* lhs, const void* rhs) const;
177 struct DisplayDeviceState {
178 DisplayDeviceState();
179 DisplayDeviceState(DisplayDevice::DisplayType type, bool isSecure);
180 bool isValid() const { return type >= 0; }
181 bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
182 bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
183 DisplayDevice::DisplayType type;
184 sp<IGraphicBufferProducer> surface;
189 uint32_t width, height;
195 LayerVector layersSortedByZ;
196 DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
199 /* ------------------------------------------------------------------------
202 virtual status_t onTransact(uint32_t code, const Parcel& data,
203 Parcel* reply, uint32_t flags);
204 virtual status_t dump(int fd, const Vector<String16>& args);
206 /* ------------------------------------------------------------------------
207 * ISurfaceComposer interface
209 virtual sp<ISurfaceComposerClient> createConnection();
210 virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
211 virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
212 virtual void destroyDisplay(const sp<IBinder>& display);
213 virtual sp<IBinder> getBuiltInDisplay(int32_t id);
214 virtual void setTransactionState(const Vector<ComposerState>& state,
215 const Vector<DisplayState>& displays, uint32_t flags);
216 virtual void bootFinished();
217 virtual bool authenticateSurfaceTexture(
218 const sp<IGraphicBufferProducer>& bufferProducer) const;
219 virtual sp<IDisplayEventConnection> createDisplayEventConnection();
220 virtual status_t captureScreen(const sp<IBinder>& display,
221 const sp<IGraphicBufferProducer>& producer,
222 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
223 uint32_t minLayerZ, uint32_t maxLayerZ,
224 bool useIdentityTransform, ISurfaceComposer::Rotation rotation,
226 virtual status_t getDisplayStats(const sp<IBinder>& display,
227 DisplayStatInfo* stats);
228 virtual status_t getDisplayConfigs(const sp<IBinder>& display,
229 Vector<DisplayInfo>* configs);
230 virtual int getActiveConfig(const sp<IBinder>& display);
231 virtual void setPowerMode(const sp<IBinder>& display, int mode);
232 virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
233 virtual status_t clearAnimationFrameStats();
234 virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
235 virtual status_t getHdrCapabilities(const sp<IBinder>& display,
236 HdrCapabilities* outCapabilities) const;
238 /* ------------------------------------------------------------------------
239 * DeathRecipient interface
241 virtual void binderDied(const wp<IBinder>& who);
243 /* ------------------------------------------------------------------------
246 virtual void onFirstRef();
248 /* ------------------------------------------------------------------------
249 * HWComposer::EventHandler interface
251 virtual void onVSyncReceived(int type, nsecs_t timestamp);
252 virtual void onHotplugReceived(int disp, bool connected);
254 /* ------------------------------------------------------------------------
257 virtual void updateExtendedMode() { }
259 virtual void getIndexLOI(size_t /*dpy*/,
260 const LayerVector& /*currentLayers*/,
261 bool& /*bIgnoreLayers*/,
262 int& /*indexLOI*/) { }
265 virtual bool updateLayerVisibleNonTransparentRegion(
266 const int& dpy, const sp<Layer>& layer,
267 bool& bIgnoreLayers, int& indexLOI,
268 uint32_t layerStack, const int& i);
270 virtual void delayDPTransactionIfNeeded(
271 const Vector<DisplayState>& /*displays*/) { }
273 virtual bool canDrawLayerinScreenShot(
274 const sp<const DisplayDevice>& hw,
275 const sp<Layer>& layer);
277 virtual void isfreezeSurfacePresent(
278 bool& freezeSurfacePresent,
279 const sp<const DisplayDevice>& /*hw*/,
280 const int32_t& /*id*/) { freezeSurfacePresent = false; }
282 virtual void setOrientationEventControl(
283 bool& /*freezeSurfacePresent*/,
284 const int32_t& /*id*/) { }
286 virtual void updateVisibleRegionsDirty() { }
288 virtual void drawWormHoleIfRequired(HWComposer::LayerListIterator &cur,
289 const HWComposer::LayerListIterator &end,
290 const sp<const DisplayDevice>& hw,
291 const Region& region);
293 virtual bool isS3DLayerPresent(const sp<const DisplayDevice>& /*hw*/)
295 /* ------------------------------------------------------------------------
299 void signalTransaction();
300 void signalLayerUpdate();
301 void signalRefresh();
303 // called on the main thread in response to initializeDisplays()
304 void onInitializeDisplays();
305 // called on the main thread in response to setActiveConfig()
306 void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
307 // called on the main thread in response to setPowerMode()
308 void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
310 // Returns whether the transaction actually modified any state
311 bool handleMessageTransaction();
313 // Returns whether a new buffer has been latched (see handlePageFlip())
314 bool handleMessageInvalidate();
316 void handleMessageRefresh();
318 void handleTransaction(uint32_t transactionFlags);
319 void handleTransactionLocked(uint32_t transactionFlags);
321 void updateCursorAsync();
323 /* handlePageFlip - latch a new buffer if available and compute the dirty
324 * region. Returns whether a new buffer has been latched, i.e., whether it
325 * is necessary to perform a refresh during this vsync.
327 bool handlePageFlip();
329 /* ------------------------------------------------------------------------
332 uint32_t getTransactionFlags(uint32_t flags);
333 uint32_t peekTransactionFlags(uint32_t flags);
334 uint32_t setTransactionFlags(uint32_t flags);
335 void commitTransaction();
336 uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
337 uint32_t setDisplayStateLocked(const DisplayState& s);
339 /* ------------------------------------------------------------------------
342 status_t createLayer(const String8& name, const sp<Client>& client,
343 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
344 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
346 status_t createNormalLayer(const sp<Client>& client, const String8& name,
347 uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
348 sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
349 sp<Layer>* outLayer);
351 status_t createDimLayer(const sp<Client>& client, const String8& name,
352 uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
353 sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
355 status_t createBlurLayer(const sp<Client>& client, const String8& name,
356 uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
357 sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
359 // called in response to the window-manager calling
360 // ISurfaceComposerClient::destroySurface()
361 status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
363 // called when all clients have released all their references to
364 // this layer meaning it is entirely safe to destroy all
365 // resources associated to this layer.
366 status_t onLayerDestroyed(const wp<Layer>& layer);
368 // remove a layer from SurfaceFlinger immediately
369 status_t removeLayer(const wp<Layer>& layer);
371 // add a layer to SurfaceFlinger
372 status_t addClientLayer(const sp<Client>& client,
373 const sp<IBinder>& handle,
374 const sp<IGraphicBufferProducer>& gbc,
375 const sp<Layer>& lbc);
377 /* ------------------------------------------------------------------------
378 * Boot animation, on/off animations and screen capture
381 void startBootAnim();
383 void renderScreenImplLocked(
384 const sp<const DisplayDevice>& hw,
385 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
386 uint32_t minLayerZ, uint32_t maxLayerZ,
387 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
389 status_t captureScreenImplLocked(
390 const sp<const DisplayDevice>& hw,
391 const sp<IGraphicBufferProducer>& producer,
392 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
393 uint32_t minLayerZ, uint32_t maxLayerZ,
394 bool useIdentityTransform, Transform::orientation_flags rotation,
395 bool isLocalScreenshot, bool useReadPixels);
397 /* ------------------------------------------------------------------------
400 size_t getMaxTextureSize() const;
401 size_t getMaxViewportDims() const;
403 /* ------------------------------------------------------------------------
404 * Display and layer stack management
406 // called when starting, or restarting after system_server death
407 void initializeDisplays();
409 // Create an IBinder for a builtin display and add it to current state
410 void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
412 // NOTE: can only be called from the main thread or with mStateLock held
413 sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
414 return mDisplays.valueFor(dpy);
417 // NOTE: can only be called from the main thread or with mStateLock held
418 sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
419 return mDisplays.valueFor(dpy);
422 // mark a region of a layer stack dirty. this updates the dirty
423 // region of all screens presenting this layer stack.
424 void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
427 int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
430 /* ------------------------------------------------------------------------
434 HWComposer& getHwComposer() const { return *mHwc; }
436 /* ------------------------------------------------------------------------
439 void invalidateHwcGeometry();
440 void computeVisibleRegions(size_t dpy,
441 const LayerVector& currentLayers, uint32_t layerStack,
442 Region& dirtyRegion, Region& opaqueRegion);
444 void preComposition();
445 void postComposition(nsecs_t refreshStartTime);
446 void rebuildLayerStacks();
447 void setUpHWComposer();
448 void doComposition();
449 void doDebugFlashRegions();
450 void doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& dirtyRegion);
452 // compose surfaces for display hw. this fails if using GL and the surface
453 // has been destroyed and is no longer valid.
454 bool doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty);
456 void postFramebuffer();
457 void drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const;
459 /* ------------------------------------------------------------------------
463 /* ------------------------------------------------------------------------
466 void enableHardwareVsync();
467 void resyncToHardwareVsync(bool makeAvailable);
468 void disableHardwareVsync(bool makeUnavailable);
470 void resyncWithRateLimit();
473 /* ------------------------------------------------------------------------
474 * Debugging & dumpsys
476 void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
477 void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
478 void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
479 void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
480 bool startDdmConnection();
481 static void appendSfConfigString(String8& result);
482 void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
483 const sp<const DisplayDevice>& hw,
484 uint32_t minLayerZ, uint32_t maxLayerZ);
486 void logFrameStats();
488 void dumpStaticScreenStats(String8& result) const;
489 virtual void dumpDrawCycle(bool /* prePrepare */ ) { }
491 /* ------------------------------------------------------------------------
495 // access must be protected by mStateLock
496 mutable Mutex mStateLock;
498 volatile int32_t mTransactionFlags;
499 Condition mTransactionCV;
500 bool mTransactionPending;
501 bool mAnimTransactionPending;
502 Vector< sp<Layer> > mLayersPendingRemoval;
503 SortedVector< wp<IBinder> > mGraphicBufferProducerList;
505 // protected by mStateLock (but we could use another lock)
508 // access must be protected by mInvalidateLock
509 volatile int32_t mRepaintEverything;
511 // constant members (no synchronization needed for access)
513 RenderEngine* mRenderEngine;
515 bool mGpuToCpuSupported;
516 bool mDropMissedFrames;
517 sp<EventThread> mEventThread;
518 sp<EventThread> mSFEventThread;
519 sp<EventControlThread> mEventControlThread;
520 EGLContext mEGLContext;
521 EGLDisplay mEGLDisplay;
522 sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
524 // Can only accessed from the main thread, these members
525 // don't need synchronization
527 bool mVisibleRegionsDirty;
529 bool mHwWorkListDirty;
531 bool mGeometryInvalid;
533 bool mAnimCompositionPending;
535 std::vector<sp<Layer>> mLayersWithQueuedFrames;
538 // this may only be written from the main thread with mStateLock held
539 // it may be read from other threads with mStateLock held
540 DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
542 // don't use a lock for these, we don't care
545 int mDebugDisableHWC;
546 int mDebugDisableTransformHint;
547 volatile nsecs_t mDebugInSwapBuffers;
548 nsecs_t mLastSwapBufferTime;
549 volatile nsecs_t mDebugInTransaction;
550 nsecs_t mLastTransactionTime;
552 bool mForceFullDamage;
553 FenceTracker mFenceTracker;
555 // these are thread safe
556 mutable MessageQueue mEventQueue;
557 FrameTracker mAnimFrameTracker;
558 DispSync mPrimaryDispSync;
560 // protected by mDestroyedLayerLock;
561 mutable Mutex mDestroyedLayerLock;
562 Vector<Layer const *> mDestroyedLayers;
564 // protected by mHWVsyncLock
566 bool mPrimaryHWVsyncEnabled;
567 bool mHWVsyncAvailable;
569 /* ------------------------------------------------------------------------
570 * Feature prototyping
573 Daltonizer mDaltonizer;
577 bool mHasColorMatrix;
579 mat4 mSecondaryColorMatrix;
580 bool mHasSecondaryColorMatrix;
582 // Static screen stats
584 static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
585 nsecs_t mFrameBuckets[NUM_BUCKETS];
587 std::atomic<nsecs_t> mLastSwapTime;
589 FrameRateHelper mFrameRateHelper;
592 * A number that increases on every new frame composition and screen capture.
593 * LayerBlur can speed up it's drawing by caching texture using this variable
594 * if multiple LayerBlur objects draw in one frame composition.
595 * In case of display mirroring, this variable should be increased on every display.
597 uint32_t mActiveFrameSequence;
601 }; // namespace android
603 #endif // ANDROID_SURFACE_FLINGER_H